forked from senecajs/seneca-redis-store
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis-store.js
executable file
·520 lines (425 loc) · 12.1 KB
/
redis-store.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
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/*jslint node: true */
/*
/* Copyright (c) 2012 Marius Ursache
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
var assert = require("assert");
var _ = require('underscore');
var redis = require('redis');
var uuid = require('node-uuid');
var NAME = "redis-store";
var MIN_WAIT = 16;
var MAX_WAIT = 65336;
var OBJECT_TYPE_STATIC = 's';
var OBJECT_TYPE_OBJECT = 'o';
var OBJECT_TYPE_DATE = 'd';
var globalObjectMap = {};
module.exports = function(opts) {
var seneca = this;
var desc;
var minwait;
var dbConn = null;
var connectSpec = null;
var waitmillis = MAX_WAIT;
opts.minwait = opts.minwait || MIN_WAIT;
opts.maxwait = opts.maxwait || MAX_WAIT;
/**
* check and report error conditions seneca.fail will execute the callback
* in the case of an error. Optionally attempt reconnect to the store depending
* on error condition
*/
function error(args, err, cb) {
if( err ) {
seneca.log.debug('error: '+err);
seneca.fail({code:'entity/error',store: NAME},cb);
if( 'ECONNREFUSED' === err.code || 'notConnected' === err.message || 'Error: no open connections' === err ) {
minwait = opts.minwait;
if (minwait) {
//collmap = {};
reconnect(args);
}
}
return true;
}
return false;
}
/**
* attemp to reconnect to the store
*/
//TODO: this is a function of the fw / subsystem NOT the store driver
// drivers should be dumb!
function reconnect(args) {
configure(connectSpec, function(err, me) {
if (err) {
seneca.log(null, 'db reconnect (wait ' + waitmillis + 'ms) failed: ' + err);
waitmillis = Math.min(2 * waitmillis, MAX_WAIT);
setTimeout(
function(){
reconnect(args);
}, waitmillis);
}
else {
waitmillis = MIN_WAIT;
seneca.log(null, 'reconnect ok');
}
});
}
/**
* configure the store - create a new store specific connection object
*
* params:
* spec - store specific configuration
* cb - callback
*/
function configure(spec, cb) {
assert(spec);
assert(cb);
var conf = spec;
connectSpec = spec;
if (_.isString(spec)) {
conf = {};
var urlM = /^redis:\/\/((.*?)@)?(.*?)(:?(\d+))$/.exec(spec);
conf.host = urlM[3];
conf.password = urlM[2];
conf.port = urlM[5];
conf.port = conf.port ? parseInt(conf.port,10) : null;
}
dbConn = redis.createClient(conf.port, conf.host);
dbConn.on('error', function(err){
seneca.fail({code: "seneca-redis/configure", message: err.message});
});
if(_.has(conf, 'auth') && !_.isEmpty(conf.auth)){
dbConn.auth(conf.auth, function(err, message){
seneca.log({tag$:'init'}, 'authed to ' + conf.host);
});
}
if(_.has(conf, 'db')){
dbConn.select(conf.db, function(err){
seneca.log({tag$:'selected db'}, 'selected db ' + conf.db);
});
}
seneca.log({tag$:'init'}, 'db '+conf.host+' opened.');
seneca.log.debug('init', 'db open', spec);
cb(null);
}
/**
* the simple db store interface returned to seneca
*/
var store = {
name: NAME,
/**
* close the connection
*
* params
* cmd - optional close command parameters
* cb - callback
*/
close: function(cmd, cb) {
assert(cb);
if (dbConn) {
// close the connection
dbConn.quit();
dbConn = null;
}
cb(null);
},
/**
* save the data as specified in the entitiy block on the arguments object
* params
* args - of the form { ent: { id: , ..entitiy data..} }
* cb - callback
*/
save: function(args, cb) {
assert(args);
assert(cb);
assert(args.ent);
var ent = args.ent;
var q = args.q;
var table = tablename(ent);
var entp = {};
if (!ent.id) {
if( ent.id$ ) {
ent.id = ent.id$;
}
else {
ent.id = uuid();
}
}
entp = makeentp(ent);
var objectMap = determineObjectMap(ent);
dbConn.hset(table, ent.id, entp, function(err, result) {
if (!error(args, err, cb)) {
saveMap(dbConn, objectMap, function(err, result) {
if (!error(args, err, cb)) {
seneca.log(args.tag$,'save', result);
cb(null, ent);
}
});
}
});
},
/**
* load first matching item based on id
* params
* args - of the form { ent: { id: , ..entitiy data..} }
* cb - callback
*/
load: function(args, cb) {
assert(args);
assert(cb);
assert(args.qent);
assert(args.q);
var qent = args.qent;
var q = _.clone(args.q);
var table = tablename(qent);
q.limit$ = 1;
if (!q.id) {
store.list(args, function(err, list) {
if (!error(args, err, cb)) {
var ent = list[0] || null;
seneca.log(args.tag$, 'load', ent);
cb(err, ent ? ent : null )
}
});
}
else {
loadMap(dbConn, table, function(err, objMap) {
if (!error(args, err, cb)) {
dbConn.hget(table, q.id, function(err, row) {
if (!error(args, err, cb)) {
if (!row) {
cb(null, null);
}
else {
var ent = makeent(qent, row, objMap);
seneca.log(args.tag$, 'load', ent);
cb(null, ent);
}
}
});
}
});
}
},
/**
* return a list of object based on the supplied query, if no query is supplied
* then all items are selected
*
* Notes: trivial implementation and unlikely to perform well due to list copy
* also only takes the first page of results from simple DB should in fact
* follow paging model
*
* params
* args - of the form { ent: { id: , ..entitiy data..} }
* cb - callback
* a=1, b=2 simple
* next paging is optional in simpledb
* limit$ ->
* use native$
*/
list: function(args, cb) {
assert(args);
assert(cb);
assert(args.qent);
assert(args.q);
var qent = args.qent;
var q = args.q;
var table = tablename(qent);
loadMap(dbConn, table, function(err, objMap) {
if (!error(args, err, cb)) {
dbConn.hgetall(table, function(err, results) {
if (!error(args, err, cb)) {
var list = [];
_.each(results, function(value, key) {
var ent = makeent(qent, value, objMap);
list.push(ent);
});
if (!_.isEmpty(q)) {
list = _.filter(list, function(elem, b, c) {
var match = true;
_.each(q, function(value, key) {
var computed = (elem[key] === value);
match = match && computed;
});
return match;
});
}
cb(null, list);
}
});
}
});
},
/**
* delete an item - fix this
*
* params
* args - of the form { ent: { id: , ..entitiy data..} }
* cb - callback
* { 'all$': true }
*/
remove: function(args, cb) {
assert(args);
assert(cb);
assert(args.qent);
assert(args.q);
var qent = args.qent;
var q = args.q;
var table = tablename(qent);
if (q.all$) {
dbConn.del(table, function(err, result) {
if (!error(args, err, cb)) {
cb(null, result);
}
});
}
else if(!_.isEmpty(q)) {
store.list(args, function(err, elements) {
var redisArgs = _.pluck(elements, 'id');
redisArgs.unshift(table);
dbConn.hdel(redisArgs, function(err, result) {
if (!error(args, err, cb)) {
cb(null, result);
}
});
});
}
else {
cb(null, null);
}
},
/**
* return the underlying native connection object
*/
native: function(args, cb) {
assert(args);
assert(cb);
assert(args.ent);
var ent = args.ent;
cb(null, dbConn);
}
};
/**
* initialization
*/
var meta = seneca.store.init(seneca, opts, store);
desc = meta.desc;
seneca.add({init:store.name,tag:meta.tag}, function(args,done) {
configure(opts, function(err) {
if (err) {
return seneca.fail({code:'entity/configure', store:store.name, error:err, desc:desc}, done);
}
else done();
});
});
return { name:store.name, tag:meta.tag };
};
/* ----------------------------------------------------------------------------
* supporting boilerplate */
var tablename = function (entity) {
var canon = entity.canon$({object:true});
return (canon.base?canon.base+'_':'')+canon.name;
};
var makeentp = function(ent) {
var entp = {};
var fields = ent.fields$();
fields.forEach(function(field){
if(_.isDate(ent[field]) || _.isObject(ent[field])) {
entp[field] = JSON.stringify(ent[field]);
}
else {
entp[field] = ent[field];
}
});
return JSON.stringify(entp);
};
var makeent = function(ent, row, objMap) {
var entp;
var fields;
row = JSON.parse(row);
fields = _.keys(row);
if (!_.isUndefined(ent) && !_.isUndefined(row)) {
entp = {};
fields.forEach(function(field) {
if (!_.isUndefined(row[field]) && !_.isUndefined(objMap.map[field])) {
if (objMap.map[field] === OBJECT_TYPE_STATIC) {
entp[field] = row[field];
}
else if (objMap.map[field] === OBJECT_TYPE_OBJECT) {
entp[field] = JSON.parse(row[field]);
}
else if (objMap.map[field] === OBJECT_TYPE_DATE) {
entp[field] = new Date(JSON.parse(row[field]));
}
}
});
}
return ent.make$(entp);
};
var determineObjectMap = function(ent){
var fields = ent.fields$();
var objectName = tablename(ent);
var objectMap = {};
var map = {};
fields.forEach(function(field){
if (_.isDate(ent[field])) {
map[field] = OBJECT_TYPE_DATE;
}
else if (_.isObject(ent[field])) {
map[field] = OBJECT_TYPE_OBJECT;
}
else {
map[field] = OBJECT_TYPE_STATIC;
}
});
objectMap = {id:objectName, map:map};
if(!_.isUndefined(globalObjectMap[objectName]) && _.size(objectMap.map) < _.size(globalObjectMap[objectName].map)) {
objectMap = globalObjectMap[objectName];
}
else {
globalObjectMap[objectName] = objectMap;
}
return objectMap;
};
var loadMap = function(dbConn, key, cb){
var table = 'seneca_object_map';
dbConn.hget(table, key, function(err, result){
if (!err) {
var objectMap = JSON.parse(result);
cb(null, objectMap);
}
else {
cb(err, null);
}
});
};
var saveMap = function(dbConn, newObjectMap, cb) {
var table = 'seneca_object_map';
var key = newObjectMap.id;
loadMap(dbConn, key, function(err, existingObjMap) {
if(err) { return cb(err, undefined); }
var mergedObjectMap = newObjectMap;
if(existingObjMap && existingObjMap.map) {
mergedObjectMap = existingObjMap;
for(var attr in newObjectMap.map) {
if(newObjectMap.map.hasOwnProperty(attr)) {
mergedObjectMap.map[attr] = newObjectMap.map[attr]
}
}
}
var savedObject = JSON.stringify(mergedObjectMap);
dbConn.hset(table, key, savedObject, cb);
});
};