forked from maxsivanov/influxdb-timeshift-proxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandlers.js
233 lines (222 loc) · 8.67 KB
/
handlers.js
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
const deb_rewrite = require('debug')('rewrite');
const deb_query = require('debug')('query');
const deb_math = require('debug')('math');
const moment = require('moment');
const { resolve } = require('url');
const units = [
'years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds', 'quarters',
'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'quarter',
'y', 'M', 'w', 'd', 'h', 'm', 's', 'ms', 'Q',
];
const shift_re = new RegExp(`[Aa][Ss]\\s+"shift_([0-9]+)_(${units.join('|')})"`);
const from = /(time\s*>=?\s*)([0-9]+)(ms)/;
const to = /(time\s*<=?\s*)([0-9]+)(ms)/;
const from_rel = /(time\s*>=?\s*)(now\(\)\s*-\s*)([0-9]+)([usmhdw])/;
const to_rel = /(time\s*<=?\s*)(now\(\)\s*-\s*)([0-9]+)([usmhdw])/;
const singlestat = /singlestat/;
const math_re = /^MATH /;
const math_name = /name="([0-9a-zA-Z]+)"/;
const math_expr = /expr="([+*/%$0-9.() -]+)"/;
const math_keep = /keep="([$0-9, ]+)"/;
function fix_query_time(q, reg, count, unit) {
const match = q.match(reg);
if (match) {
const time = moment(parseInt(match[2], 10));
time.subtract(count, unit);
if (reg == from) {
if (q.match(to) || q.match(to_rel))
return q.replace(reg, match[1] + time.valueOf() + match[3]);
else
return q.replace(reg, match[1] + time.valueOf() + match[3] + " AND time < now() - 0h");
}
return q.replace(reg, match[1] + time.valueOf() + match[3]);
}
return q;
}
function fix_query_time_relative(q, reg, count, unit) {
const match = q.match(reg);
if (match) {
if (reg == from_rel) {
if (q.match(to) || q.match(to_rel))
return q.replace(match[0], match[0] + " - " + moment.duration(count, unit).valueOf() + "ms");
else
return q.replace(match[0], match[0] + " - " + moment.duration(count, unit).valueOf() + "ms AND time < now() - 0h");
}
return q.replace(match[0], match[0] + " - " + moment.duration(count, unit).valueOf() + "ms");
}
return q;
}
function get_result(results, statement, time) {
try {
const found = results[statement].series[0].values.find(function (item) {
return item[0] === time;
});
if (found) {
return found[1];
}
} catch (err) { }
return null;
}
function calculate_values(results, math) {
if (math.vars && math.vars.length) {
const indexes = math.vars.map(function (item) {
return parseInt(item.substr(1), 10);
});
const func = new Function(...math.vars, "return " + math.expr);
const ret = [];
try {
const base = results[indexes[0]].series[0].values;
base.forEach(function (rec) {
const digits = [];
indexes.forEach(function (idx) {
digits.push(get_result(results, idx, rec[0]));
});
let result = func.apply(this, digits);
deb_math(rec[0], digits, result);
if (result === Infinity) {
result = null;
}
if (isNaN(result)) {
result = null;
}
ret.push([rec[0], result]);
});
} catch (err) {}
return ret;
}
deb_math("No vars found:", math.expr);
return [];
}
const reLeadingSlash = /^\//;
const reLeadingSemicolon = /^;+/;
const reEveryVar = /\$[0-9]+/g;
const reTwoSemicolon = /;;/;
function forward(path, req, res) {
if ((req.url.indexOf("/query") === 0) && (req.query.q)) {
const query = req.query.q.replace(reLeadingSemicolon, '').replace(reTwoSemicolon, '');
const parts = query.split(';').map((q, idx) => {
let match;
deb_query(idx, q);
match = q.match(math_re);
if (match) {
const name_parts = math_name.exec(q);
const expr_parts = math_expr.exec(q);
const keep_parts = math_keep.exec(q);
if (name_parts && expr_parts) {
if (!req.proxyMath) {
req.proxyMath = {};
}
req.proxyMath[idx] = {
name: name_parts[1],
expr: expr_parts[1],
vars: expr_parts[1].match(reEveryVar),
singlestat: q.match(singlestat),
keep: keep_parts ? keep_parts[1].split(',').map(idx => {
return parseInt(idx.trim().substring(1), 10);
}) : []
};
return '';
}
}
match = q.match(shift_re);
if (match) {
if (!req.proxyShift) {
req.proxyShift = {};
}
req.proxyShift[idx] = {
count: parseInt(match[1], 10),
unit: match[2]
};
deb_rewrite("<-- " + q);
let select = fix_query_time(q, from, parseInt(match[1], 10), match[2]);
select = fix_query_time(select, to, parseInt(match[1], 10), match[2]);
select = fix_query_time_relative(select, from_rel, parseInt(match[1], 10), match[2]);
select = fix_query_time_relative(select, to_rel, parseInt(match[1], 10), match[2]);
deb_rewrite("--> " + select);
return select;
} else {
return q;
}
});
const ret = Object.assign({}, req.query, {
q: parts.join(';')
});
const queries = [];
for (let key in ret) {
if (ret.hasOwnProperty(key)) {
queries.push(key + "=" + encodeURIComponent(ret[key]));
}
}
return resolve(path, "query") + "?" + queries.join("&");
} else {
return resolve(path, req.url.replace(reLeadingSlash, ''));
}
}
function intercept(rsp, data, req, res) {
if (req.proxyShift || req.proxyMath) {
const json = JSON.parse(data.toString());
if (req.proxyMath && json.results) {
Object.keys(req.proxyMath).forEach(key => {
json.results.splice(parseInt(key, 10), 0, {
statement_id: null,
series: []
});
});
}
if (req.proxyShift && Object.keys(req.proxyShift).length && json.results) {
const results = json.results.map((result, idx) => {
if (req.proxyShift[idx] && result.series) {
return Object.assign({}, result, {
series: result.series.map(serie => {
return Object.assign({}, serie, { values: serie.values.map(item => {
const time = moment(item[0]);
time.add(req.proxyShift[idx].count, req.proxyShift[idx].unit);
return [ time.valueOf(), item[1]];
})});
})
});
}
return result;
});
json.results = results;
}
if (req.proxyMath && json.results) {
Object.keys(req.proxyMath).forEach(key => {
const math = req.proxyMath[key];
if (json.results[key]) {
deb_math("Do math:", math.expr, "for statement:", key);
json.results[key] = {
statement_id: null,
series: [{
name: math.name,
columns: ["time", "value"],
values: calculate_values(json.results, math)
}]
};
if (math.vars) {
math.vars.forEach(item => {
const idx = parseInt(item.substr(1), 10);
if (math.keep.indexOf(idx) === -1) {
if (math.singlestat) {
json.results[idx] = {};
} else {
json.results[idx].series[0].values = [];
}
deb_math("Clear values for statement:", idx);
}
});
}
}
});
json.results.forEach((result, idx) => {
result.statement_id = idx;
});
}
return JSON.stringify(json);
}
return data;
}
module.exports = {
forward,
intercept
};