This repository has been archived by the owner on Nov 22, 2017. It is now read-only.
/
chain_runner.js
225 lines (187 loc) · 6.49 KB
/
chain_runner.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
var _ = require('lodash');
var glob = require('glob');
var Promise = require('bluebird');
var parseSheet = require('./lib/parse_sheet.js');
var parseDateMath = require('../lib/date_math.js');
var calculateInterval = require('../../public/lib/calculate_interval.js');
var loadFunctions = require('../lib/load_functions.js');
var repositionArguments = require('./lib/reposition_arguments.js');
var indexArguments = require('./lib/index_arguments.js');
var getFunctionByName = require('./lib/get_function_by_name.js');
var preprocessChain = require('./lib/preprocess_chain');
var validateTime = require('./lib/validate_time.js');
var functions = loadFunctions('series_functions');
var fitFunctions = loadFunctions('fit_functions');
module.exports = function (tlConfig) {
var queryCache = {};
var stats = {};
var sheet;
function getQueryCacheKey(query) {
return JSON.stringify(_.omit(query, 'label'));
}
function throwWithCell(cell, exception) {
throw new Error(' in cell #' + (cell + 1) + ': ' + exception.message);
}
// Invokes a modifier function, resolving arguments into series as needed
function invoke(fnName, args) {
var functionDef = getFunctionByName(fnName);
function resolveArgument(item) {
if (_.isArray(item)) {
return Promise.all(_.map(item, resolveArgument));
}
if (_.isObject(item)) {
switch (item.type) {
case 'function':
var itemFunctionDef = getFunctionByName(item.function);
if (itemFunctionDef.cacheKey && queryCache[itemFunctionDef.cacheKey(item)]) {
stats.queryCount++;
return Promise.resolve(_.cloneDeep(queryCache[itemFunctionDef.cacheKey(item)]));
}
return invoke(item.function, item.arguments);
case 'reference':
var reference;
if (item.series) {
reference = sheet[item.plot - 1][item.series - 1];
} else {
reference = {
type: 'chainList',
list: sheet[item.plot - 1]
};
}
return invoke('first', [reference]);
case 'chain':
return invokeChain(item);
case 'chainList':
return resolveChainList(item.list);
case 'literal':
return item.value;
case 'requestList':
case 'seriesList':
return item;
}
throw new Error ('Argument type not supported: ' + JSON.stringify(item));
} else {
return item;
}
}
args = repositionArguments(functionDef, args);
args = _.map(args, resolveArgument);
return Promise.all(args).then(function (args) {
args.byName = indexArguments(functionDef, args);
return functionDef.fn(args, tlConfig);
});
}
function invokeChain(chainObj, result) {
if (chainObj.chain.length === 0) return result[0];
var chain = _.clone(chainObj.chain);
var link = chain.shift();
var promise;
if (link.type === 'chain') {
promise = invokeChain(link);
} else if (!result) {
promise = invoke('first', [link]);
} else {
var args = link.arguments ? result.concat(link.arguments) : result;
promise = invoke(link.function, args);
}
return promise.then(function (result) {
return invokeChain({type:'chain', chain: chain}, [result]);
});
}
function resolveChainList(chainList) {
var seriesList = _.map(chainList, function (chain) {
var values = invoke('first', [chain]);
return values.then(function (args) {
return args;
});
});
return Promise.all(seriesList).then(function (args) {
var list = _.chain(args).pluck('list').flatten().value();
return {type: 'seriesList', list: list};
});
}
function preProcessSheet(sheet) {
var queries = {};
_.each(sheet, function (chainList, i) {
try {
var queriesInCell = _.mapValues(preprocessChain(chainList), function (val) {
val.cell = i;
return val;
});
queries = _.extend(queries, queriesInCell);
} catch (e) {
throwWithCell(i, e);
}
});
queries = _.values(queries);
var promises = _.chain(queries).values().map(function (query) {
return invoke(query.function, query.arguments);
}).value();
return Promise.settle(promises).then(function (resolvedDatasources) {
stats.queryTime = (new Date()).getTime();
_.each(queries, function (query, i) {
var functionDef = getFunctionByName(query.function);
var resolvedDatasource = resolvedDatasources[i];
if (resolvedDatasource.isRejected()) {
if (resolvedDatasource.reason().isBoom) {
throw resolvedDatasource.reason();
} else {
throwWithCell(query.cell, resolvedDatasource.reason());
}
}
queryCache[functionDef.cacheKey(query)] = resolvedDatasource.value();
});
stats.cacheCount = _.keys(queryCache).length;
return sheet;
});
}
function processRequest(request) {
if (!request) throw new Error('Empty request body');
validateTime(request.time, tlConfig);
tlConfig.time = request.time;
tlConfig.time.to = parseDateMath(request.time.to, true).valueOf();
tlConfig.time.from = parseDateMath(request.time.from).valueOf();
tlConfig.time.interval = calculateInterval(
tlConfig.time.from,
tlConfig.time.to,
tlConfig.file.target_buckets || 200,
tlConfig.time.interval
);
tlConfig.setTargetSeries();
stats.invokeTime = (new Date()).getTime();
stats.queryCount = 0;
queryCache = {};
// This is setting the "global" sheet, required for resolving references
sheet = parseSheet(request.sheet);
return preProcessSheet(sheet).then(function () {
return _.map(sheet, function (chainList, i) {
return resolveChainList(chainList).then(function (seriesList) {
stats.sheetTime = (new Date()).getTime();
return seriesList.list;
}).catch(function (e) {
throwWithCell(i, e);
});
});
});
}
return {
processRequest: processRequest,
getStats: function () { return stats; }
};
};
/*
function logObj(obj, thing) {
return JSON.stringify(obj, null, thing ? ' ' : undefined);
}
function debugSheet(sheet) {
sheet = processRequest(sheet);
Promise.all(sheet).then(function (sheet) {
console.log(logObj(sheet, 1));
console.log(logObj({done:true}));
return sheet;
});
}
debugSheet(
{sheet:['es(q=-*)'], time: tlConfig.time}
);
*/