/
beacon.js
370 lines (337 loc) · 11.5 KB
/
beacon.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
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
/**
* @title joola
* @overview the open-source data analytics framework
* @copyright Joola Smart Solutions, Ltd. <info@joo.la>
* @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
*
* Licensed under GNU General Public License 3.0 or later.
* Some rights reserved. See LICENSE, AUTHORS.
**/
'use strict';
var
joola = require('../joola'),
domain = require('domain'),
diff = require('deep-diff').diff,
async = require('async'),
traverse = require('traverse'),
router = require('../webserver/routes/index'),
equal = require('deep-equal'),
ce = require('cloneextend'),
path = require('path'),
_ = require('underscore'),
fs = require('fs');
var etl = {};
exports.etl = etl;
etl.verify = function (context, workspace, collection, documents, callback) {
var _document;
if (!Array.isArray(documents))
documents = [documents];
var buildRowKey = function (obj) {
var key = '';
Object.keys(obj).forEach(function (k) {
var value = obj[k];
var type = typeof value;
if (type === 'string' || k === 'timestamp')
key += value;
});
key = joola.common.hash(key);
return key;
};
async.map(documents, function (doc, cb) {
try {
if (!doc.timestamp)
doc.timestamp = new Date();
else {
doc.timestamp = new Date(doc.timestamp.value || doc.timestamp);
}
doc._key = buildRowKey(doc);
}
catch (ex) {
return cb(ex);
}
return cb(null);
}, function (err) {
if (err)
return callback(err);
if (documents.length > 0)
_document = ce.clone(documents[0]);
joola.dispatch.collections.metadata(context, workspace, null, _document, function (err, meta) {
/* istanbul ignore if */
if (err)
return callback(err);
joola.dispatch.collections.get(context, workspace, collection, function (err, _collection) {
if (err) {
meta.key = collection;
meta.name = collection;
joola.dispatch.collections.add(context, workspace, meta, function (err, _collection) {
/* istanbul ignore if */
if (err && err.message != 'Collection already exist') {
return callback(err);
}
joola.dispatch.collections.get(context, workspace, collection, function (err, _collection) {
if (err) {
return callback(err);
}
if (joola.datastore.providers.default.addcollection) {
joola.datastore.providers.default.addcollection(meta.key, meta, function (err) {
if (err)
return callback(err);
return callback(null);
});
}
else {
return callback(null);
}
});
});
}
else {
joola.dispatch.collections.metadata(context, workspace, collection, _document, function (err, _meta) {
/* istanbul ignore if */
if (err)
return callback(err);
var differences;
delete meta._key;
var match = equal(meta, _meta);
if (!match) {
differences = diff(meta, _meta);
differences = _.filter(differences, function (diff) {
return diff.kind !== 'N';
});
}
if (differences) {
match = differences.length === 0;
}
if (!match && _collection.strongTyped) {
joola.logger.warn({
category: 'beacon',
diff: differences
}, 'Strong-typed collection [' + collection + '] cannot be modified by Beacon.');
return callback(new Error('Strong-typed collection [' + collection + '] cannot be modified by Beacon.'));
}
else if (!match) {
differences = diff(meta, _meta);
meta.key = collection;
meta.name = collection;
joola.dispatch.collections.patch(context, workspace, meta.key, meta, function (err) {
joola.logger.debug({
category: 'beacon',
diff: differences
}, 'Updating collection [' + collection + '] due to meta change.');
if (joola.datastore.providers.default.altercollection) {
joola.datastore.providers.default.altercollection(meta.key, meta, differences, function (err) {
if (err)
return callback(err);
return callback(null);
});
}
else {
return callback(null);
}
});
}
else {
return callback(null);
}
});
}
});
});
});
};
etl.load = function (context, workspace, collection, documents, options, callback) {
joola.dispatch.collections.metadata(context, workspace, collection, ce.clone(documents[0]), function (err, meta, _collection) {
if (err)
return callback(err);
_collection.meta = meta;
_collection.storeKey = (workspace + '_' + collection).replace(/[^\w\s]/gi, '');
//cleanup the object if we passed adhoc values;
async.map(documents, function (document, cb) {
traverse.forEach(document, function (x) {
if (x && typeof x === 'object' && x.hasOwnProperty('value'))
this.update(x.value);
});
return cb(null);
}, function () {
var d = domain.create();
d.on('error', function (err) {
console.log(err);
joola.logger.error('Failed to insert document, ' + err);
return callback('Failed to insert document: ' + err);
});
d.run(function () {
var filtered = _.filter(Object.keys(joola.datastore.providers), function (key) {
var p = joola.datastore.providers[key];
return key !== 'default' && (p.enabled || !p.hasOwnProperty('enabled'));
});
async.map(filtered, function (key, cb) {
var provider = joola.datastore.providers[key];
provider.insert(_collection, ce.clone(documents), options, function (err, results) {
if (err)
return cb(err);
return cb(null, results);
});
}, function (err, results) {
if (err)
return callback(err);
async.map(documents, function (d, cb) {
d.saved = true;
return cb(null, d);
}, function (err, arrdocuments) {
if (err)
return callback(err);
return callback(null, arrdocuments, results);
});
});
});
});
});
};
exports.insert = {
name: "/beacon/insert",
description: "",
inputs: {
required: ['workspace', 'collection', 'document'],
optional: ['options']
},
_outputExample: {},
_permission: ['beacon:insert'],
_dispatch: {
message: 'beacon:insert'
},
_route: function (req, res) {
var _params = {};//req.parsed;
var context = {};
context.user = req.user;
_params.workspace = context.user.workspace;
if (!req.parsed.workspace)
_params.workspace = req.user.workspace;
_params.collection = req.parsed.collection;
_params.document = req.parsed.document || req.parsed.payload;
var beaconConfig = joola.config.get('beacon');
var w = beaconConfig && beaconConfig.hasOwnProperty('wait') ? beaconConfig.wait : false;
if (!req.parsed.options)
req.parsed.options = {
wait: w
};
else if (!req.parsed.options.hasOwnProperty('wait'))
req.parsed.options.wait = w;
if (typeof _params.document === 'string') {
try {
_params.document = JSON.parse(_params.document);
}
catch (ex) {
return router.responseError(400, new router.ErrorTemplate('Document must be a valid JSON'), req, res);
}
}
if (_params.document.length > 0 && typeof _params.document[0] === 'string') {
try {
_params.document.forEach(function (d, i, arr) {
arr[i] = JSON.parse(d);
});
}
catch (ex) {
return router.responseError(400, new router.ErrorTemplate('Document must be a valid JSON'), req, res);
}
}
try {
var _token = req.token;
var cb = function (err, result, headers) {
if (err)
return router.responseError(500, new router.ErrorTemplate('Failed to route action [' + 'insert' + ']: ' + (typeof(err) === 'object' ? err.message : err)), req, res);
return router.responseSuccess(result, headers, req, res);
};
if (joola.dispatch.enabled)
joola.dispatch.request(_token._ || _token, 'beacon:insert', _params, req.parsed.options.wait ? cb : function () {
});
else
exports.insert.run.apply(this, [context, _params.workspace, _params.collection, _params.document, _params.options, req.parsed.options.wait ? cb : function () {
}]);
if (!req.parsed.options.wait) {
cb(null, _params.document, {});
}
}
catch (ex) {
return router.responseError(500, new router.ErrorTemplate(ex), req, res);
}
},
run: function (context, workspace, collection, documents, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
else if (typeof documents === 'function') {
callback = documents;
options = {};
documents = collection;
collection = workspace;
workspace = context.user.workspace;
}
callback = callback || function () {
};
if (context.user.workspace !== workspace && context.user.permissions.indexOf('superuser') === -1) {
var err = new Error('Forbidden');
err.code = 403;
return callback(err);
}
try {
if (!Array.isArray(documents)) {
documents = [documents];
}
var start_ts = new Date().getTime();
var count = documents.length;
etl.verify(context, workspace, collection, documents, function (err) {
if (err)
return callback(err);
etl.load(context, workspace, collection, documents, {}, function (err, documents) {
if (err)
return callback(err);
var end_ts = new Date().getTime();
if (count > 1)
joola.logger.trace('Beacon insert, count: ' + count + ', total: ' + (end_ts - start_ts) + 'ms, rate: ' + (count / (end_ts - start_ts)) + 'doc/ms');
//if (workspace != '_stats')
// joola.stats.emit({event: 'writes', workspace: workspace, username: context.user.username, collection: collection, writeCount: count, duration_per_doc: (count / (end_ts - start_ts))});
subscribers.forEach(function (subscriber, i) {
if (subscriber.disconnected)
subscribers.splice(i, 1);
else {
subscriber.emit('event', collection, documents);
}
});
return callback(null, documents);
});
});
}
catch (ex) {
/* istanbul ignore next */
console.log('exception', ex);
/* istanbul ignore next */
console.log(ex.stack);
return callback(ex);
}
}
};
var subscribers = [];
exports.subscribe = {
name: "/beacon/subscribe",
description: "I subscribe to socket.io",
inputs: {
required: [],
optional: []
},
_outputExample: {},
_permission: ['beacon:subscribe'],
_dispatch: {
message: 'subscribe',
limit: -1
},
_route: function (req, res, next) {
subscribers.push(req.socket);
},
run: function (context, callback) {
callback = callback || function () {
};
//subscribers.push(req.socket);
return callback();
}
};