-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy patheventstore.js
630 lines (532 loc) · 18.2 KB
/
eventstore.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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
var debug = require('debug')('eventstore'),
util = require('util'),
EventEmitter = require('events').EventEmitter,
_ = require('lodash'),
async = require('async'),
tolerate = require('tolerance'),
EventDispatcher = require('./eventDispatcher'),
EventStream = require('./eventStream'),
Snapshot = require('./snapshot');
/**
* Eventstore constructor
* @param {Object} options The options.
* @param {Store} store The db implementation.
* @constructor
*/
function Eventstore(options, store) {
this.options = options || {};
this.store = store;
this.eventMappings = {};
EventEmitter.call(this);
}
util.inherits(Eventstore, EventEmitter);
_.extend(Eventstore.prototype, {
/**
* Inject function for event publishing.
* @param {Function} fn the function to be injected
* @returns {Eventstore} to be able to chain...
*/
useEventPublisher: function (fn) {
if (fn.length === 1) {
fn = _.wrap(fn, function(func, evt, callback) {
func(evt);
callback(null);
});
}
this.publisher = fn;
return this;
},
/**
* Define which values should be mapped/copied to the payload event. [optional]
* @param {Object} mappings the mappings in dotty notation
* {
* id: 'id',
* commitId: 'commitId',
* commitSequence: 'commitSequence',
* commitStamp: 'commitStamp',
* streamRevision: 'streamRevision'
* }
* @returns {Eventstore} to be able to chain...
*/
defineEventMappings: function (mappings) {
if (!mappings || !_.isObject(mappings)) {
var err = new Error('Please pass a valid mapping values!');
debug(err);
throw err;
}
this.eventMappings = mappings;
return this;
},
/**
* Call this function to initialize the eventstore.
* If an event publisher function was injected it will additionally initialize an event dispatcher.
* @param {Function} callback the function that will be called when this action has finished [optional]
*/
init: function (callback) {
var self = this;
function initDispatcher() {
debug('init event dispatcher');
self.dispatcher = new EventDispatcher(self.publisher, self);
self.dispatcher.start(callback);
}
this.store.on('connect', function () {
self.emit('connect');
});
this.store.on('disconnect', function () {
self.emit('disconnect');
});
process.nextTick(function() {
tolerate(function(callback) {
self.store.connect(callback);
}, self.options.timeout || 0, function (err) {
if (err) {
debug(err);
if (callback) callback(err);
return;
}
if (!self.publisher) {
debug('no publisher defined');
if (callback) callback(null);
return;
}
initDispatcher();
});
});
},
// streaming api
/**
* streams the events
* @param {Object || String} query the query object [optional]
* @param {Number} skip how many events should be skipped? [optional]
* @param {Number} limit how many events do you want in the result? [optional]
* @returns {Stream} a stream with the events
*/
streamEvents: function (query, skip, limit) {
if (!this.store.streamEvents) {
throw new Error('Streaming API is not suppoted by '+(this.options.type || 'inmemory') +' db implementation.');
}
if (typeof query === 'number') {
limit = skip;
skip = query;
query = {};
};
if (typeof query === 'string') {
query = { aggregateId: query };
}
return this.store.streamEvents(query, skip, limit);
},
/**
* streams all the events since passed commitStamp
* @param {Date} commitStamp the date object
* @param {Number} skip how many events should be skipped? [optional]
* @param {Number} limit how many events do you want in the result? [optional]
* @returns {Stream} a stream with the events
*/
streamEventsSince: function (commitStamp, skip, limit) {
if (!this.store.streamEvents) {
throw new Error('Streaming API is not suppoted by '+(this.options.type || 'inmemory') +' db implementation.');
}
if (!commitStamp) {
var err = new Error('Please pass in a date object!');
debug(err);
throw err;
}
var self = this;
commitStamp = new Date(commitStamp);
return this.store.streamEventsSince(commitStamp, skip, limit);
},
/**
* stream events by revision
* @param {Object || String} query the query object
* @param {Number} revMin revision start point [optional]
* @param {Number} revMax revision end point (hint: -1 = to end) [optional]
* @returns {Stream} a stream with the events
*/
streamEventsByRevision: function (query, revMin, revMax) {
if (typeof query === 'string') {
query = { aggregateId: query };
}
if (!query.aggregateId) {
var err = new Error('An aggregateId should be passed!');
debug(err);
if (callback) callback(err);
return;
}
return this.store.streamEventsByRevision(query, revMin, revMax);
},
/**
* loads the events
* @param {Object || String} query the query object [optional]
* @param {Number} skip how many events should be skipped? [optional]
* @param {Number} limit how many events do you want in the result? [optional]
* @param {Function} callback the function that will be called when this action has finished
* `function(err, events){}`
*/
getEvents: function (query, skip, limit, callback) {
if (typeof query === 'function') {
callback = query;
skip = 0;
limit = -1;
query = {};
} else if (typeof skip === 'function') {
callback = skip;
skip = 0;
limit = -1;
if (typeof query === 'number') {
skip = query;
query = {};
}
} else if (typeof limit === 'function') {
callback = limit;
limit = -1;
if (typeof query === 'number') {
limit = skip;
skip = query;
query = {};
}
}
if (typeof query === 'string') {
query = { aggregateId: query };
}
var self = this;
function nextFn(callback) {
if (limit < 0) {
var resEvts = [];
resEvts.next = nextFn;
return process.nextTick(function () { callback(null, resEvts) });
}
skip += limit;
_getEvents(query, skip, limit, callback);
}
function _getEvents(query, skip, limit, callback) {
self.store.getEvents(query, skip, limit, function (err, evts) {
if (err) return callback(err);
evts.next = nextFn;
callback(null, evts);
});
}
_getEvents(query, skip, limit, callback);
},
/**
* loads all the events since passed commitStamp
* @param {Date} commitStamp the date object
* @param {Number} skip how many events should be skipped? [optional]
* @param {Number} limit how many events do you want in the result? [optional]
* @param {Function} callback the function that will be called when this action has finished
* `function(err, events){}`
*/
getEventsSince: function (commitStamp, skip, limit, callback) {
if (!commitStamp) {
var err = new Error('Please pass in a date object!');
debug(err);
throw err;
}
if (typeof skip === 'function') {
callback = skip;
skip = 0;
limit = -1;
} else if (typeof limit === 'function') {
callback = limit;
limit = -1;
}
var self = this;
function nextFn(callback) {
if (limit < 0) {
var resEvts = [];
resEvts.next = nextFn;
return process.nextTick(function () { callback(null, resEvts) });
}
skip += limit;
_getEventsSince(commitStamp, skip, limit, callback);
}
commitStamp = new Date(commitStamp);
function _getEventsSince(commitStamp, skip, limit, callback) {
self.store.getEventsSince(commitStamp, skip, limit, function (err, evts) {
if (err) return callback(err);
evts.next = nextFn;
callback(null, evts);
});
}
_getEventsSince(commitStamp, skip, limit, callback);
},
/**
* loads the events
* @param {Object || String} query the query object
* @param {Number} revMin revision start point [optional]
* @param {Number} revMax revision end point (hint: -1 = to end) [optional]
* @param {Function} callback the function that will be called when this action has finished
* `function(err, events){}`
*/
getEventsByRevision: function (query, revMin, revMax, callback) {
if (typeof revMin === 'function') {
callback = revMin;
revMin = 0;
revMax = -1;
} else if (typeof revMax === 'function') {
callback = revMax;
revMax = -1;
}
if (typeof query === 'string') {
query = { aggregateId: query };
}
if (!query.aggregateId) {
var err = new Error('An aggregateId should be passed!');
debug(err);
if (callback) callback(err);
return;
}
this.store.getEventsByRevision(query, revMin, revMax, callback);
},
/**
* loads the event stream
* @param {Object || String} query the query object
* @param {Number} revMin revision start point [optional]
* @param {Number} revMax revision end point (hint: -1 = to end) [optional]
* @param {Function} callback the function that will be called when this action has finished
* `function(err, eventstream){}`
*/
getEventStream: function (query, revMin, revMax, callback) {
if (typeof revMin === 'function') {
callback = revMin;
revMin = 0;
revMax = -1;
} else if (typeof revMax === 'function') {
callback = revMax;
revMax = -1;
}
if (typeof query === 'string') {
query = { aggregateId: query };
}
if (!query.aggregateId) {
var err = new Error('An aggregateId should be passed!');
debug(err);
if (callback) callback(err);
return;
}
var self = this;
this.getEventsByRevision(query, revMin, revMax, function(err, evts) {
if (err) {
return callback(err);
}
callback(null, new EventStream(self, query, evts));
});
},
/**
* loads the next snapshot back from given max revision
* @param {Object || String} query the query object
* @param {Number} revMax revision end point (hint: -1 = to end) [optional]
* @param {Function} callback the function that will be called when this action has finished
* `function(err, snapshot, eventstream){}`
*/
getFromSnapshot: function (query, revMax, callback) {
if (typeof revMax === 'function') {
callback = revMax;
revMax = -1;
}
if (typeof query === 'string') {
query = { aggregateId: query };
}
if (!query.aggregateId) {
var err = new Error('An aggregateId should be passed!');
debug(err);
if (callback) callback(err);
return;
}
var self = this;
async.waterfall([
function getSnapshot(callback) {
self.store.getSnapshot(query, revMax, callback);
},
function getEventStream(snap, callback) {
var rev = 0;
if (snap && (snap.revision !== undefined && snap.revision !== null)) {
rev = snap.revision + 1;
}
self.getEventStream(query, rev, revMax, function(err, stream) {
if (err) {
return callback(err);
}
if (rev > 0 && stream.lastRevision == -1) {
stream.lastRevision = snap.revision;
}
callback(null, snap, stream);
});
}],
callback
);
},
/**
* stores a new snapshot
* @param {Object} obj the snapshot data
* @param {Function} callback the function that will be called when this action has finished [optional]
*/
createSnapshot: function(obj, callback) {
if (obj.streamId && !obj.aggregateId) {
obj.aggregateId = obj.streamId;
}
if (!obj.aggregateId) {
var err = new Error('An aggregateId should be passed!');
debug(err);
if (callback) callback(err);
return;
}
obj.streamId = obj.aggregateId;
var self = this;
async.waterfall([
function getNewIdFromStorage(callback) {
self.getNewId(callback);
},
function commit(id, callback) {
try {
var snap = new Snapshot(id, obj);
snap.commitStamp = new Date();
} catch (err) {
return callback(err);
}
self.store.addSnapshot(snap, function(error) {
if (self.options.maxSnapshotsCount) {
self.store.cleanSnapshots(_.pick(obj, 'aggregateId', 'aggregate', 'context'), callback);
} else {
callback(error);
}
});
}],
callback
);
},
/**
* commits all uncommittedEvents in the eventstream
* @param eventstream the eventstream that should be saved (hint: directly use the commit function on eventstream)
* @param {Function} callback the function that will be called when this action has finished
* `function(err, eventstream){}` (hint: eventstream.eventsToDispatch)
*/
commit: function(eventstream, callback) {
var self = this;
var waterfallFuncs = [];
var idSet = [];
waterfallFuncs.push(function getNewId(callback) {
self.getNewId(callback);
});
// Generate an id for each uncommitted event
for (var i= 0, len = eventstream.uncommittedEvents.length; i < len; i++) {
waterfallFuncs.push(function getAnotherId(previousId, callback) {
idSet.push(previousId);
self.getNewId(callback);
});
}
waterfallFuncs.push(function commitEvents(id, callback) {
idSet.push(id);
// start committing.
var event,
currentRevision = eventstream.currentRevision(),
uncommittedEvents = [].concat(eventstream.uncommittedEvents);
eventstream.uncommittedEvents = [];
self.store.getNextPositions(uncommittedEvents.length, function(err, positions) {
if (err)
return callback(err)
for (var i = 0, len = uncommittedEvents.length; i < len; i++) {
event = uncommittedEvents[i];
event.id = idSet[i+1]; // additional ids generated by getAnotherId function
event.commitId = idSet[0]; // first id generated is for the commit
event.commitSequence = i;
event.restInCommitStream = len - 1 - i;
event.commitStamp = new Date();
currentRevision++;
event.streamRevision = currentRevision;
if (positions)
event.position = positions[i];
event.applyMappings();
}
self.store.addEvents(uncommittedEvents, function(err) {
if (err) {
// add uncommitted events back to eventstream
eventstream.uncommittedEvents = uncommittedEvents.concat(eventstream.uncommittedEvents);
return callback(err);
}
if (self.publisher && self.dispatcher) {
// push to undispatchedQueue
self.dispatcher.addUndispatchedEvents(uncommittedEvents);
} else {
eventstream.eventsToDispatch = [].concat(uncommittedEvents);
}
// move uncommitted events to events
eventstream.events = eventstream.events.concat(uncommittedEvents);
eventstream.currentRevision();
callback(null, eventstream);
});
});
});
async.waterfall(waterfallFuncs, callback);
},
/**
* loads all undispatched events
* @param {Object || String} query the query object [optional]
* @param {Function} callback the function that will be called when this action has finished
* `function(err, events){}`
*/
getUndispatchedEvents: function (query, callback) {
if (!callback) {
callback = query;
query = null;
}
if (typeof query === 'string') {
query = { aggregateId: query };
}
this.store.getUndispatchedEvents(query, callback);
},
/**
* loads the last event
* @param {Object || String} query the query object [optional]
* @param {Function} callback the function that will be called when this action has finished
* `function(err, event){}`
*/
getLastEvent: function (query, callback) {
if (!callback) {
callback = query;
query = null;
}
if (typeof query === 'string') {
query = { aggregateId: query };
}
this.store.getLastEvent(query, callback);
},
/**
* loads the last event in a stream
* @param {Object || String} query the query object [optional]
* @param {Function} callback the function that will be called when this action has finished
* `function(err, eventstream){}`
*/
getLastEventAsStream: function (query, callback) {
if (!callback) {
callback = query;
query = null;
}
if (typeof query === 'string') {
query = { aggregateId: query };
}
var self = this;
this.store.getLastEvent(query, function (err, evt) {
if (err) return callback(err);
callback(null, new EventStream(self, query, evt ? [evt] : []));
});
},
/**
* Sets the given event to dispatched.
* @param {Object || String} evtOrId the event object or its id
* @param {Function} callback the function that will be called when this action has finished [optional]
*/
setEventToDispatched: function (evtOrId, callback) {
if (typeof evtOrId === 'object') {
evtOrId = evtOrId.id;
}
this.store.setEventToDispatched(evtOrId, callback);
},
/**
* loads a new id from store
* @param {Function} callback the function that will be called when this action has finished
*/
getNewId: function (callback) {
this.store.getNewId(callback);
}
});
module.exports = Eventstore;