-
Notifications
You must be signed in to change notification settings - Fork 4
/
api.d
415 lines (335 loc) · 11.8 KB
/
api.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
module influxdb.api;
static import influxdb.vibe;
version(unittest) import unit_threaded;
alias Database = DatabaseImpl!(influxdb.vibe.manage, influxdb.vibe.query, influxdb.vibe.write);
/**
Holds information about the database name and URL, forwards
it to the implemetation functions for managing, querying and
writing to the DB
*/
struct DatabaseImpl(alias manageFunc, alias queryFunc, alias writeFunc) {
import influxdb.api;
string url; // e.g. http://localhost:8086
string db; // e.g. mydb
@disable this();
this(string url, string db) {
this.url = url;
this.db = db;
manage("CREATE DATABASE " ~ db);
}
/**
Sends management commands to the DB (CREATE, DROP).
The parameter must be the full command (e.g. "DROP DATABASE mydb")
*/
void manage(in string cmd) const {
manageFunc(url, cmd);
}
/**
Queries the DB. The query must be a full InfluxDB query
(e.g. "SELECT * FROM foo")
*/
Response query(in string query) @trusted const { // deserialize is @system
import asdf: deserialize;
return queryFunc(url, db, query).deserialize!Response;
}
/**
Insert data into the DB.
*/
void insert(in Measurement[] measurements) const {
import std.algorithm: map;
import std.array: array, join;
writeFunc(url, db, measurements.map!(a => a.toString).array.join("\n"));
}
/**
Insert data into the DB.
*/
void insert(in Measurement[] measurements...) const {
insert(measurements);
}
/*
Delete this DB
*/
void drop() const {
manage("DROP DATABASE " ~ db);
}
}
///
@("Database")
@safe unittest { // not pure because of asdf.deserialize
string[string][] manages;
string[string][] queries;
string[string][] writes;
alias TestDatabase = DatabaseImpl!(
(url, cmd) => manages ~= ["url": url, "cmd": cmd], // manage
(url, db, query) { // query
queries ~= ["url": url, "db": db, "query": query];
return
`{
"results": [{
"series": [{
"columns": ["time", "othervalue", "tag1", "tag2", "value"],
"name": "lename",
"values": [
["2015-06-11T20:46:02Z", 4, "toto", "titi", 2],
["2017-03-14T23:15:01.06282785Z", 3, "letag", "othertag", 1]
]
}],
"statement_id": 33
}]
}`;
},
(url, db, line) => writes ~= ["url": url, "db": db, "line": line]
);
manages.shouldBeEmpty;
const database = TestDatabase("http://db.com", "testdb");
manages.shouldEqual([["url": "http://db.com", "cmd": "CREATE DATABASE testdb"]]);
writes.shouldBeEmpty;
database.insert(Measurement("cpu", ["tag1": "foo"], ["temperature": "42"]));
writes.shouldEqual([["url": "http://db.com", "db": "testdb",
"line": "cpu,tag1=foo temperature=42"]]);
queries.shouldBeEmpty;
const response = database.query("SELECT * from foo");
queries.shouldEqual([["url": "http://db.com", "db": "testdb", "query": "SELECT * from foo"]]);
response.results.length.shouldEqual(1);
response.results[0].statement_id.shouldEqual(33);
response.results[0].series.length.shouldEqual(1);
const series = response.results[0].series[0];
series.shouldEqual(
MeasurementSeries(
"lename", //name
["time", "othervalue", "tag1", "tag2", "value"], //columns
//values
[
["2015-06-11T20:46:02Z", "4", "toto", "titi", "2"],
["2017-03-14T23:15:01.06282785Z", "3", "letag", "othertag", "1"],
]
)
);
}
@("insert")
@safe unittest {
string[] lines;
alias TestDatabase = DatabaseImpl!(
(url, cmd) { }, // manage
(url, db, query) => `{}`, // query
(url, db, line) => lines ~= line // write
);
const database = TestDatabase("http://db.com", "testdb");
database.insert(
Measurement("cpu", ["index": "1"], ["temperature": "42"]),
Measurement("cpu", ["index": "2"], ["temperature": "42"]),
Measurement("cpu", ["index": "2"], ["temperature": "42"]),
);
() @trusted {
lines.shouldEqual(
[
"cpu,index=1 temperature=42\ncpu,index=2 temperature=42\ncpu,index=2 temperature=42",
]
);
}();
}
/**
An InfluxDB measurement
*/
struct Measurement {
import std.datetime: SysTime;
string name;
string[string] tags;
string[string] fields;
long timestamp;
this(string name,
string[string] fields,
SysTime time = SysTime.fromUnixTime(0))
@safe pure nothrow {
string[string] tags;
this(name, tags, fields);
}
this(string name,
string[string] tags,
string[string] fields,
SysTime time = SysTime.fromUnixTime(0))
@safe pure nothrow {
this.name = name;
this.tags = tags;
this.fields = fields;
this.timestamp = time.toUnixTime;
}
string toString() @safe pure const {
import std.range: chain;
import std.conv: to;
import std.array: join;
// @trusted due to aa.keys
auto aaToString(in string[string] aa) @trusted {
import std.algorithm: map;
return aa.keys.map!(k => k ~ "=" ~ aa[k]);
}
const nameTags = chain([name], aaToString(tags)).join(",");
const fields = aaToString(fields).join(",");
auto parts = [nameTags.to!string, fields.to!string];
if(timestamp != 0) parts ~= timestamp.to!string;
return parts.join(" ");
}
}
///
@("Measurement.toString no timestamp")
@safe pure unittest {
{
auto m = Measurement("cpu",
["tag1": "toto", "tag2": "foo"],
["load": "42", "temperature": "53"]);
m.toString.shouldEqualLine("cpu,tag1=toto,tag2=foo load=42,temperature=53");
}
{
auto m = Measurement("thingie",
["foo": "bar"],
["value": "7"]);
m.toString.shouldEqualLine("thingie,foo=bar value=7");
}
}
@("Measurement.toString no timestamp no tags")
@safe pure unittest {
auto m = Measurement("cpu",
["load": "42", "temperature": "53"]);
m.toString.shouldEqualLine("cpu load=42,temperature=53");
}
@("Measurement.toString with timestamp")
@safe pure unittest {
import std.datetime: SysTime;
auto m = Measurement("cpu",
["tag1": "toto", "tag2": "foo"],
["load": "42", "temperature": "53"],
SysTime.fromUnixTime(7));
m.toString.shouldEqualLine("cpu,tag1=toto,tag2=foo load=42,temperature=53 7");
}
/**
A query response
*/
struct Response {
Result[] results;
}
/**
A result of a query
*/
struct Result {
MeasurementSeries[] series;
int statement_id;
}
/**
Data for one measurement
*/
struct MeasurementSeries {
import asdf: serializationIgnoreIn, Asdf;
string name;
string[] columns;
@serializationIgnoreIn string[][] values;
static struct Rows {
const string[] columns;
const(string[])[] rows;
static struct Row {
import std.datetime: SysTime;
const string[] columnNames;
const string[] columnValues;
string opIndex(in string key) @safe pure const {
import std.algorithm: countUntil;
return columnValues[columnNames.countUntil(key)];
}
SysTime time() @safe const {
return SysTime.fromISOExtString(this["time"]);
}
string toString() @safe const pure nothrow {
import std.string: join;
string[] ret;
foreach(i, ref value; columnValues) {
ret ~= columnNames[i] ~ ": " ~ value;
}
return "Row(" ~ ret.join(", ") ~ ")";
}
}
Row opIndex(in size_t i) @safe pure const nothrow {
return Row(columns, rows[i]);
}
size_t length() @safe pure const nothrow { return rows.length; }
void popFront() @safe pure nothrow {
rows = rows[1 .. $];
}
Row front() @safe pure nothrow {
return this[0];
}
bool empty() @safe pure nothrow const {
return rows.length == 0;
}
}
inout(Rows) rows() @safe pure nothrow inout {
return inout(Rows)(columns, values);
}
void finalizeDeserialization(Asdf data) {
import std.algorithm: map;
import std.array: array;
auto dataValues = data["values"];
foreach(row; dataValues.byElement) {
values ~= row.byElement.map!(a => cast(string)a).array;
}
}
}
///
@("MeasurementSeries")
@safe unittest {
import std.datetime: SysTime, DateTime, UTC;
import std.array: array;
auto series = MeasurementSeries("coolness",
["time", "foo", "bar"],
[
["2015-06-11T20:46:02Z", "red", "blue"],
["2013-02-09T12:34:56Z", "green", "yellow"],
]);
series.rows[0]["foo"].shouldEqual("red");
series.rows[0]["time"].shouldEqual("2015-06-11T20:46:02Z");
series.rows[0].time.shouldEqual(SysTime(DateTime(2015, 06, 11, 20, 46, 2), UTC()));
series.rows[1]["bar"].shouldEqual("yellow");
series.rows[1]["time"].shouldEqual("2013-02-09T12:34:56Z");
series.rows[1].time.shouldEqual(SysTime(DateTime(2013, 2, 9, 12, 34, 56), UTC()));
series.rows.array.shouldEqual(
[
MeasurementSeries.Rows.Row(["time", "foo", "bar"],
["2015-06-11T20:46:02Z", "red", "blue"],
),
MeasurementSeries.Rows.Row(["time", "foo", "bar"],
["2013-02-09T12:34:56Z", "green", "yellow"],
),
]
);
}
version(unittest) {
/**
The two lines must be equivalent under InfluxDB's line protocol
Since the tags and fields aren't ordered, a straight comparison
might yield false errors.
The timestamp is also taken care of by comparing it to the current timestamp
and making sure not too much time has passed since then
*/
void shouldEqualLine(in string actual,
in string expected,
in string file = __FILE__,
in size_t line = __LINE__) @safe pure {
// reassemble the protocol line with sorted tags and fields
string sortLine(in string line) {
import std.string: split, join;
import std.range: chain;
import std.algorithm: sort;
import std.conv: text;
auto parts = line.split(" ");
assert(parts.length == 3 || parts.length == 2,
text("Illegal number of parts( ", parts.length, ") in ", line));
auto nameTags = parts[0].split(",");
const name = nameTags[0];
auto tags = nameTags[1..$];
auto fields = parts[1].split(",");
auto newNameTags = chain([name], sort(tags)).join(",");
auto newFields = sort(fields).join(",");
auto newParts = [newNameTags, newFields];
if(parts.length > 2) newParts ~= parts[2];
return newParts.join(" ");
}
sortLine(actual).shouldEqual(sortLine(expected), file, line);
}
}