-
Notifications
You must be signed in to change notification settings - Fork 65
/
index.js
1678 lines (1532 loc) · 53.8 KB
/
index.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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var mongodb = require('./mongodb');
var DB = require('sharedb').DB;
var OpLinkValidator = require('./op-link-validator');
var MiddlewareHandler = require('./src/middleware/middlewareHandler');
module.exports = ShareDbMongo;
function ShareDbMongo(mongo, options) {
// use without new
if (!(this instanceof ShareDbMongo)) {
return new ShareDbMongo(mongo, options);
}
if (typeof mongo === 'object') {
options = mongo;
mongo = options.mongo;
}
if (!options) options = {};
// pollDelay is a dodgy hack to work around race conditions replicating the
// data out to the polling target secondaries. If a separate db is specified
// for polling, it defaults to 300ms
this.pollDelay = (options.pollDelay != null) ? options.pollDelay :
(options.mongoPoll) ? 300 : 0;
// By default, we create indexes on any ops collection that is used
this.disableIndexCreation = options.disableIndexCreation || false;
// The getOps() method depends on a separate operations collection, and that
// collection should have an index on the operations stored there. We could
// ask people to make these indexes themselves, but by default the mongo
// driver will do it automatically. This approach will leak memory relative
// to the number of collections you have. This should be OK, as we are not
// expecting thousands of mongo collections.
// Map from collection name -> true for op collections we've ensureIndex'ed
this.opIndexes = {};
// Allow $while and $mapReduce queries. These queries let you run arbitrary
// JS on the server. If users make these queries from the browser, there's
// security issues.
this.allowJSQueries = options.allowAllQueries || options.allowJSQueries || false;
// Aggregate queries are less dangerous, but you can use them to access any
// data in the mongo database.
this.allowAggregateQueries = options.allowAllQueries || options.allowAggregateQueries || false;
// Setting this flag to true will attempt to infer a canonical op link for
// getOps rather than using the snapshot as the op link. This allows us to
// not fetch all ops to present when asking only for a subset.
// For more details on this, see the README.
this.getOpsWithoutStrictLinking = options.getOpsWithoutStrictLinking || false;
// Track whether the close method has been called
this.closed = false;
this.mongo = null;
this._mongoClient = null;
this.mongoPoll = null;
this._mongoPollClient = null;
if (typeof mongo === 'string' || typeof mongo === 'function') {
var self = this;
this._connection = this._connect(mongo, options)
.then(function(result) {
self.mongo = result.mongo;
self._mongoClient = result.mongoClient;
self.mongoPoll = result.mongoPoll;
self._mongoPollClient = result.mongoPollClient;
return result;
});
} else {
throw new Error('deprecated: pass mongo as url string or function with callback');
}
this._middleware = new MiddlewareHandler();
};
ShareDbMongo.prototype = Object.create(DB.prototype);
ShareDbMongo.prototype.projectsSnapshots = true;
ShareDbMongo.prototype.getCollection = function(collectionName, callback) {
// Check the collection name
var err = this.validateCollectionName(collectionName);
if (err) return callback(err);
// Gotcha: calls back sync if connected or async if not
this.getDbs(function(err, mongo) {
if (err) return callback(err);
var collection = mongo.collection(collectionName);
return callback(null, collection);
});
};
ShareDbMongo.prototype._getCollectionPoll = function(collectionName, callback) {
// Check the collection name
var err = this.validateCollectionName(collectionName);
if (err) return callback(err);
// Gotcha: calls back sync if connected or async if not
this.getDbs(function(err, mongo, mongoPoll) {
if (err) return callback(err);
var collection = (mongoPoll || mongo).collection(collectionName);
return callback(null, collection);
});
};
ShareDbMongo.prototype.getCollectionPoll = function(collectionName, callback) {
if (this.pollDelay) {
var self = this;
setTimeout(function() {
self._getCollectionPoll(collectionName, callback);
}, this.pollDelay);
return;
}
this._getCollectionPoll(collectionName, callback);
};
ShareDbMongo.prototype.getDbs = function(callback) {
if (this.closed) {
var err = ShareDbMongo.alreadyClosedError();
return callback(err);
}
this._connection
.then(function(result) {
callback(null, result.mongo, result.mongoPoll);
}, callback);
};
ShareDbMongo.prototype._connect = function(mongo, options) {
// Create the mongo connection client connections if needed
//
// Throw errors in this function if we fail to connect, since we aren't
// implementing a way to retry
var connections = [connect(mongo, options.mongoOptions)];
var mongoPoll = options.mongoPoll;
if (mongoPoll) connections.push(connect(mongoPoll, options.mongoPollOptions));
return Promise.all(connections).then(function(clients) {
var mongoClient = clients[0];
var mongoPollClient = clients[1];
return {
mongo: mongoClient.db(),
mongoClient: mongoClient,
mongoPoll: mongoPollClient && mongoPollClient.db(),
mongoPollClient: mongoPollClient
};
});
};
function connect(mongo, options) {
if (typeof mongo === 'function') {
return new Promise(function(resolve, reject) {
mongo(function(error, client) {
if (error) return reject(error);
resolve(client);
});
});
}
options = Object.assign({}, options);
delete options.mongo;
delete options.mongoPoll;
delete options.mongoPollOptions;
delete options.pollDelay;
delete options.disableIndexCreation;
delete options.allowAllQueries;
delete options.allowJSQueries;
delete options.allowAllQueries;
delete options.allowAggregateQueries;
delete options.getOpsWithoutStrictLinking;
if (typeof mongodb.connect === 'function') {
return mongodb.connect(mongo, options);
} else {
var client = new mongodb.MongoClient(mongo, options);
return client.connect();
}
}
ShareDbMongo.prototype.close = function(callback) {
if (!callback) {
callback = function(err) {
if (err) throw err;
};
}
var self = this;
this.getDbs(function(err) {
// Ignore "already closed"
if (err && err.code === 5101) return callback();
if (err) return callback(err);
self.closed = true;
self._mongoClient.close()
.then(function() {
return self._mongoPollClient && self._mongoPollClient.close();
})
.then(function() {
callback(null);
}, callback);
});
};
// **** Commit methods
ShareDbMongo.prototype.commit = function(collectionName, id, op, snapshot, options, callback) {
var self = this;
var request = createRequestForMiddleware(options, collectionName, op);
this._writeOp(collectionName, id, op, snapshot, function(err, result) {
if (err) return callback(err);
var opId = result.insertedId;
self._writeSnapshot(request, id, snapshot, opId, function(err, succeeded) {
if (succeeded) return callback(err, succeeded);
// Cleanup unsuccessful op if snapshot write failed. This is not
// necessary for data correctness, but it gets rid of clutter
self._deleteOp(request.collectionName, opId, function(removeErr) {
callback(err || removeErr, succeeded);
});
});
});
};
function createRequestForMiddleware(options, collectionName, op, fields) {
// Create a new request object which will be passed to helper functions and middleware
var request = {
options: options,
collectionName: collectionName
};
if (op) request.op = op;
// When we're creating a request for submitting an op, let downstream middleware know.
if (fields && fields.$submit === true) {
/**
* TODO What if sharedb populated this? We could use MIDDLEWARE_ACTIONS.
*/
request.triggeredBy = 'submitRequest';
}
return request;
}
ShareDbMongo.prototype._writeOp = function(collectionName, id, op, snapshot, callback) {
if (typeof op.v !== 'number') {
var err = ShareDbMongo.invalidOpVersionError(collectionName, id, op.v);
return callback(err);
}
this.getOpCollection(collectionName, function(err, opCollection) {
if (err) return callback(err);
var doc = shallowClone(op);
doc.d = id;
doc.o = snapshot._opLink;
opCollection.insertOne(doc)
.then(function(result) {
callback(null, result);
}, callback);
});
};
ShareDbMongo.prototype._deleteOp = function(collectionName, opId, callback) {
this.getOpCollection(collectionName, function(err, opCollection) {
if (err) return callback(err);
opCollection.deleteOne({_id: opId})
.then(function(result) {
callback(null, result);
}, callback);
});
};
ShareDbMongo.prototype._writeSnapshot = function(request, id, snapshot, opId, callback) {
var self = this;
this.getCollection(request.collectionName, function(err, collection) {
if (err) return callback(err);
request.documentToWrite = castToDoc(id, snapshot, opId);
if (request.documentToWrite._v === 1) {
self._middleware.trigger(MiddlewareHandler.Actions.beforeCreate, request, function(middlewareErr) {
if (middlewareErr) {
return callback(middlewareErr);
}
collection.insertOne(request.documentToWrite)
.then(
function() {
callback(null, true);
},
function(err) {
// Return non-success instead of duplicate key error, since this is
// expected to occur during simultaneous creates on the same id
if (err.code === 11000 && /\b_id_\b/.test(err.message)) {
return callback(null, false);
}
return callback(err);
}
);
});
} else {
request.query = {_id: id, _v: request.documentToWrite._v - 1};
self._middleware.trigger(MiddlewareHandler.Actions.beforeOverwrite, request, function(middlewareErr) {
if (middlewareErr) {
return callback(middlewareErr);
}
collection.replaceOne(request.query, request.documentToWrite)
.then(function(result) {
var succeeded = !!result.modifiedCount;
callback(null, succeeded);
}, callback);
});
}
});
};
// **** Snapshot methods
ShareDbMongo.prototype.getSnapshot = function(collectionName, id, fields, options, callback) {
var self = this;
this.getCollection(collectionName, function(err, collection) {
if (err) return callback(err);
var query = {_id: id};
var projection = getProjection(fields, options);
var request = createRequestForMiddleware(options, collectionName, null, fields);
request.query = query;
self._middleware.trigger(MiddlewareHandler.Actions.beforeSnapshotLookup, request, function(middlewareErr) {
if (middlewareErr) return callback(middlewareErr);
collection.find(request.query, request.findOptions).limit(1).project(projection).next()
.then(function(doc) {
var snapshot = (doc) ? castToSnapshot(doc) : new MongoSnapshot(id, 0, null, undefined);
callback(null, snapshot);
}, callback);
});
});
};
ShareDbMongo.prototype.getSnapshotBulk = function(collectionName, ids, fields, options, callback) {
var self = this;
this.getCollection(collectionName, function(err, collection) {
if (err) return callback(err);
var query = {_id: {$in: ids}};
var projection = getProjection(fields, options);
var request = createRequestForMiddleware(options, collectionName, null, fields);
request.query = query;
self._middleware.trigger(MiddlewareHandler.Actions.beforeSnapshotLookup, request, function(middlewareErr) {
if (middlewareErr) return callback(middlewareErr);
collection.find(request.query, request.findOptions).project(projection).toArray()
.then(function(docs) {
var snapshotMap = {};
for (var i = 0; i < docs.length; i++) {
var snapshot = castToSnapshot(docs[i]);
snapshotMap[snapshot.id] = snapshot;
}
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
if (snapshotMap[id]) continue;
snapshotMap[id] = new MongoSnapshot(id, 0, null, undefined);
}
callback(null, snapshotMap);
}, callback);
});
});
};
// **** Oplog methods
// Overwrite me if you want to change this behaviour.
ShareDbMongo.prototype.getOplogCollectionName = function(collectionName) {
return 'o_' + collectionName;
};
ShareDbMongo.prototype.validateCollectionName = function(collectionName) {
if (
collectionName === 'system' || (
collectionName[0] === 'o' &&
collectionName[1] === '_'
)
) {
return ShareDbMongo.invalidCollectionError(collectionName);
}
};
// Get and return the op collection from mongo, ensuring it has the op index.
ShareDbMongo.prototype.getOpCollection = function(collectionName, callback) {
var self = this;
this.getDbs(function(err, mongo) {
if (err) return callback(err);
var name = self.getOplogCollectionName(collectionName);
var collection = mongo.collection(name);
// Given the potential problems with creating indexes on the fly, it might
// be preferrable to disable automatic creation
if (self.disableIndexCreation === true) {
return callback(null, collection);
}
if (self.opIndexes[collectionName]) {
return callback(null, collection);
}
// WARNING: Creating indexes automatically like this is quite dangerous in
// production if we are starting with a lot of data and no indexes
// already. If new indexes were added or definition of these indexes were
// changed, users upgrading this module could unsuspectingly lock up their
// databases. If indexes are created as the first ops are added to a
// collection this won't be a problem, but this is a dangerous mechanism.
// Perhaps we should only warn instead of creating the indexes, especially
// when there is a lot of data in the collection.
var disabledIndexes = self.disableIndexCreation || {};
var promises = [
collection.createIndex({d: 1, v: 1}, {background: true}),
!disabledIndexes.src_seq_v && collection.createIndex({src: 1, seq: 1, v: 1}, {background: true})
];
Promise.all(promises)
.then(function() {
self.opIndexes[collectionName] = true;
callback(null, collection);
}, callback);
});
};
ShareDbMongo.prototype.getOpsToSnapshot = function(collectionName, id, from, snapshot, options, callback) {
if (snapshot._opLink == null) {
var err = ShareDbMongo.missingLastOperationError(collectionName, id);
return callback(err);
}
var options = Object.assign({}, options);
var to = null;
this._getOps(collectionName, id, from, to, options, function(err, ops) {
if (err) return callback(err);
var filtered = getLinkedOps(ops, null, snapshot._opLink);
var err = null;
if (!options.ignoreMissingOps) {
err = checkOpsFrom(collectionName, id, filtered, from);
}
if (err) return callback(err);
callback(null, filtered);
});
};
ShareDbMongo.prototype.getOps = function(collectionName, id, from, to, options, callback) {
var self = this;
var options = Object.assign({}, options);
this._getOpLink(collectionName, id, to, options, function(err, opLink) {
if (err) return callback(err);
// We need to fetch slightly more ops than requested in order to work backwards along
// linked ops to provide only valid ops
var fetchOpsTo = null;
if (opLink) {
if (isCurrentVersion(opLink, from)) {
return callback(null, []);
}
var err = opLink && checkDocHasOp(collectionName, id, opLink);
if (err) return callback(err);
if (self.getOpsWithoutStrictLinking) fetchOpsTo = opLink._v;
}
self._getOps(collectionName, id, from, fetchOpsTo, options, function(err, ops) {
if (err) return callback(err);
var filtered = filterOps(ops, opLink, to);
var err = null;
if (!options.ignoreMissingOps) {
err = checkOpsFrom(collectionName, id, filtered, from);
}
if (err) return callback(err);
callback(null, filtered);
});
});
};
ShareDbMongo.prototype.getOpsBulk = function(collectionName, fromMap, toMap, options, callback) {
var self = this;
var ids = Object.keys(fromMap);
this._getSnapshotOpLinkBulk(collectionName, ids, options, function(err, docs) {
if (err) return callback(err);
var docMap = getDocMap(docs);
// Add empty array for snapshot versions that are up to date and create
// the query conditions for ops that we need to get
var conditions = [];
var opsMap = {};
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var doc = docMap[id];
var from = fromMap[id];
if (doc) {
if (isCurrentVersion(doc, from)) {
opsMap[id] = [];
continue;
}
var err = checkDocHasOp(collectionName, id, doc);
if (err) return callback(err);
}
var condition = getOpsQuery(id, from);
conditions.push(condition);
}
// Return right away if none of the snapshot versions are newer than the
// requested versions
if (!conditions.length) return callback(null, opsMap);
// Otherwise, get all of the ops that are newer
self._getOpsBulk(collectionName, conditions, options, function(err, opsBulk) {
if (err) return callback(err);
for (var i = 0; i < conditions.length; i++) {
var id = conditions[i].d;
var ops = opsBulk[id];
var doc = docMap[id];
var from = fromMap[id];
var to = toMap && toMap[id];
var filtered = filterOps(ops, doc, to);
var err = checkOpsFrom(collectionName, id, filtered, from);
if (err) return callback(err);
opsMap[id] = filtered;
}
callback(null, opsMap);
});
});
};
ShareDbMongo.prototype.getCommittedOpVersion = function(collectionName, id, snapshot, op, options, callback) {
var self = this;
this.getOpCollection(collectionName, function(err, opCollection) {
if (err) return callback(err);
var query = {
src: op.src,
seq: op.seq
};
var projection = {v: 1, _id: 0};
var sort = {v: 1};
// Find the earliest version at which the op may have been committed.
// Since ops are optimistically written prior to writing the snapshot, the
// op could end up being written multiple times or have been written but
// not count as committed if not backreferenced from the snapshot
opCollection.find(query).project(projection).sort(sort).limit(1).next()
.then(function(doc) {
// If we find no op with the same src and seq, we definitely don't have
// any match. This should prevent us from accidentally querying a huge
// history of ops
if (!doc) return callback();
// If we do find an op with the same src and seq, we still have to get
// the ops from the snapshot to figure out if the op was actually
// committed already, and at what version in case of multiple matches
var from = doc.v;
self.getOpsToSnapshot(collectionName, id, from, snapshot, options, function(err, ops) {
if (err) return callback(err);
for (var i = ops.length; i--;) {
var item = ops[i];
if (op.src === item.src && op.seq === item.seq) {
return callback(null, item.v);
}
}
callback();
});
}, callback);
});
};
function checkOpsFrom(collectionName, id, ops, from) {
if (ops.length === 0) return;
if (ops[0] && ops[0].v === from) return;
if (from == null) return;
return ShareDbMongo.missingOpsError(collectionName, id, from);
};
function checkDocHasOp(collectionName, id, doc) {
if (doc._o) return;
return ShareDbMongo.missingLastOperationError(collectionName, id);
}
function isCurrentVersion(doc, version) {
return doc._v === version;
}
function getDocMap(docs) {
var docMap = {};
for (var i = 0; i < docs.length; i++) {
var doc = docs[i];
docMap[doc._id] = doc;
}
return docMap;
}
function filterOps(ops, doc, to) {
// Always return in the case of no ops found whether or not consistent with
// the snapshot
if (!ops) return [];
if (!ops.length) return ops;
if (!doc) {
// There is no snapshot currently. We already returned if there are no
// ops, so this could happen if:
// 1. The doc was deleted
// 2. The doc create op is written but not the doc snapshot
// 3. Same as 3 for a recreate
// 4. We are in an inconsistent state because of an error
//
// We treat the snapshot as the canonical version, so if the snapshot
// doesn't exist, the doc should be considered deleted. Thus, a delete op
// should be in the last version if no commits are inflight or second to
// last version if commit(s) are inflight. Rather than trying to detect
// ops inconsistent with a deleted state, we are simply returning ops from
// the last delete. Inconsistent states will ultimately cause write
// failures on attempt to commit.
//
// Different delete ops must be identical and must link back to the same
// prior version in order to be inserted, so if there are multiple delete
// ops at the same version, we can grab any of them for this method.
// However, the _id of the delete op might not ultimately match the delete
// op that gets maintained if two are written as a result of two
// simultanous delete commits. Thus, the _id of the op should *not* be
// assumed to be consistent in the future.
var deleteOp = getLatestDeleteOp(ops);
// Don't return any ops if we don't find a delete operation, which is the
// correct thing to do if the doc was just created and the op has been
// written but not the snapshot. Note that this will simply return no ops
// if there are ops but the snapshot doesn't exist.
if (!deleteOp) return [];
return getLinkedOps(ops, to, deleteOp._id);
}
return getLinkedOps(ops, to, doc._o);
}
function getLatestDeleteOp(ops) {
for (var i = ops.length; i--;) {
var op = ops[i];
if (op.del) return op;
}
}
function getLinkedOps(ops, to, link) {
var linkedOps = [];
for (var i = ops.length; i-- && link;) {
var op = ops[i];
if (link.equals ? !link.equals(op._id) : link !== op._id) continue;
link = op.o;
if (to == null || op.v < to) {
delete op._id;
delete op.o;
linkedOps.push(op);
}
}
return linkedOps.reverse();
}
function getOpsQuery(id, from, to) {
from = from == null ? 0 : from;
var query = {
d: id,
v: {$gte: from}
};
if (to != null) {
query.v.$lt = to;
}
return query;
}
ShareDbMongo.prototype._getOps = function(collectionName, id, from, to, options, callback) {
this.getOpCollection(collectionName, function(err, opCollection) {
if (err) return callback(err);
var query = getOpsQuery(id, from, to);
// Exclude the `d` field, which is only for use internal to livedb-mongo.
// Also exclude the `m` field, which can be used to store metadata on ops
// for tracking purposes
var projection = (options && options.metadata) ? {d: 0} : {d: 0, m: 0};
var sort = {v: 1};
opCollection.find(query).project(projection).sort(sort).toArray()
.then(function(result) {
callback(null, result);
}, callback);
});
};
ShareDbMongo.prototype._getOpsBulk = function(collectionName, conditions, options, callback) {
this.getOpCollection(collectionName, function(err, opCollection) {
if (err) return callback(err);
var query = {$or: conditions};
// Exclude the `m` field, which can be used to store metadata on ops for
// tracking purposes
var projection = (options && options.metadata) ? null : {m: 0};
var stream = opCollection.find(query).project(projection).stream();
readOpsBulk(stream, callback);
});
};
function readOpsBulk(stream, callback) {
var opsMap = {};
var errored;
stream.on('error', function(err) {
errored = true;
return callback(err);
});
stream.on('end', function() {
if (errored) return;
// Sort ops for each doc in ascending order by version
for (var id in opsMap) {
opsMap[id].sort(function(a, b) {
return a.v - b.v;
});
}
callback(null, opsMap);
});
// Read each op and push onto a list for the appropriate doc
stream.on('data', function(op) {
var id = op.d;
if (opsMap[id]) {
opsMap[id].push(op);
} else {
opsMap[id] = [op];
}
delete op.d;
});
}
ShareDbMongo.prototype._getOpLink = function(collectionName, id, to, options, callback) {
if (!this.getOpsWithoutStrictLinking) return this._getSnapshotOpLink(collectionName, id, options, callback);
var db = this;
this.getOpCollection(collectionName, function(error, collection) {
if (error) return callback(error);
// If to is null, we want the most recent version, so just return the
// snapshot link, which is more efficient than cursoring
if (to == null) {
return db._getSnapshotOpLink(collectionName, id, options, callback);
}
var query = {
d: id,
v: {$gte: to}
};
var projection = {
_id: 0,
v: 1,
o: 1
};
var cursor = collection.find(query).sort({v: 1}).project(projection);
getFirstOpWithUniqueVersion(cursor, null, function(error, op) {
if (error) return callback(error);
if (op) return callback(null, {_o: op.o, _v: op.v});
// If we couldn't find an op to link back from, then fall back to using the current
// snapshot, which is guaranteed to have a link to a valid op.
db._getSnapshotOpLink(collectionName, id, options, callback);
});
});
};
// When getting ops, we need to consider the case where an op is committed to the database,
// but its application to the snapshot is subsequently rejected. This can leave multiple ops
// with the same values for 'd' and 'v', and means that we may return multiple ops for a single
// version if we just perform a naive 'find' operation.
// To avoid this, we try to fetch the first op from 'to' which has a unique 'v', and then we
// work backwards from that op using the linked op 'o' field to get a valid chain of ops.
// See the README for more details.
function getFirstOpWithUniqueVersion(cursor, opLinkValidator, callback) {
opLinkValidator = opLinkValidator || new OpLinkValidator();
var opWithUniqueVersion = opLinkValidator.opWithUniqueVersion();
if (opWithUniqueVersion || opLinkValidator.isAtEndOfList()) {
var error = null;
return closeCursor(cursor, callback, error, opWithUniqueVersion);
}
cursor.next()
.then(
function(op) {
opLinkValidator.push(op);
getFirstOpWithUniqueVersion(cursor, opLinkValidator, callback);
},
function(error) {
closeCursor(cursor, callback, error);
}
);
}
function closeCursor(cursor, callback, error, returnValue) {
cursor.close()
.then(function() {
callback(error, returnValue);
}, callback);
}
ShareDbMongo.prototype._getSnapshotOpLink = function(collectionName, id, options, callback) {
var self = this;
this.getCollection(collectionName, function(err, collection) {
if (err) return callback(err);
var query = {_id: id};
var projection = {_id: 0, _o: 1, _v: 1};
var request = createRequestForMiddleware(options, collectionName);
request.query = query;
self._middleware.trigger(MiddlewareHandler.Actions.beforeSnapshotLookup, request, function(middlewareErr) {
if (middlewareErr) return callback(middlewareErr);
collection.find(query, request.findOptions).limit(1).project(projection).next()
.then(function(result) {
callback(null, result);
}, callback);
});
});
};
ShareDbMongo.prototype._getSnapshotOpLinkBulk = function(collectionName, ids, options, callback) {
var self = this;
this.getCollection(collectionName, function(err, collection) {
if (err) return callback(err);
var query = {_id: {$in: ids}};
var projection = {_o: 1, _v: 1};
var request = createRequestForMiddleware(options, collectionName);
request.query = query;
self._middleware.trigger(MiddlewareHandler.Actions.beforeSnapshotLookup, request, function(middlewareErr) {
if (middlewareErr) return callback(middlewareErr);
collection.find(query, request.findOptions).project(projection).toArray()
.then(function(result) {
callback(null, result);
}, callback);
});
});
};
// **** Query methods
ShareDbMongo.prototype._query = function(collection, inputQuery, projection, callback) {
var parsed = this._getSafeParsedQuery(inputQuery, callback);
if (!parsed) return;
// Collection operations such as $aggregate run on the whole
// collection. Only one operation is run. The result goes in the
// "extra" argument in the callback.
if (parsed.collectionOperationKey) {
collectionOperationsMap[parsed.collectionOperationKey](
collection,
parsed.query,
parsed.collectionOperationValue,
function(err, extra) {
if (err) return callback(err);
callback(null, [], extra);
}
);
return;
}
// No collection operations were used. Create an initial cursor for
// the query, that can be transformed later.
var cursor = collection.find(parsed.query).project(projection);
// Cursor transforms such as $skip transform the cursor into a new
// one. If multiple transforms are specified on inputQuery, they all
// run.
for (var key in parsed.cursorTransforms) {
var transform = cursorTransformsMap[key];
cursor = transform(cursor, parsed.cursorTransforms[key]);
if (!cursor) {
var err = ShareDbMongo.malformedQueryOperatorError(key);
return callback(err);
}
}
// Cursor operations such as $count run on the cursor, after all
// transforms. Only one operation is run. The result goes in the
// "extra" argument in the callback.
if (parsed.cursorOperationKey) {
cursorOperationsMap[parsed.cursorOperationKey](
cursor,
parsed.cursorOperationValue,
function(err, extra) {
if (err) return callback(err);
callback(null, [], extra);
}
);
return;
}
// If no collection operation or cursor operations were used, return
// an array of snapshots that are passed in the "results" argument
// in the callback
cursor.toArray()
.then(function(result) {
callback(null, result);
}, callback);
};
ShareDbMongo.prototype.query = function(collectionName, inputQuery, fields, options, callback) {
var self = this;
this.getCollection(collectionName, function(err, collection) {
if (err) return callback(err);
var projection = getProjection(fields, options);
self._query(collection, inputQuery, projection, function(err, results, extra) {
if (err) return callback(err);
var snapshots = [];
for (var i = 0; i < results.length; i++) {
var snapshot = castToSnapshot(results[i]);
snapshots.push(snapshot);
}
callback(null, snapshots, extra);
});
});
};
ShareDbMongo.prototype.queryPoll = function(collectionName, inputQuery, options, callback) {
var self = this;
this.getCollectionPoll(collectionName, function(err, collection) {
if (err) return callback(err);
var projection = {_id: 1};
self._query(collection, inputQuery, projection, function(err, results, extra) {
if (err) return callback(err);
var ids = [];
for (var i = 0; i < results.length; i++) {
ids.push(results[i]._id);
}
callback(null, ids, extra);
});
});
};
ShareDbMongo.prototype.queryPollDoc = function(collectionName, id, inputQuery, options, callback) {
var self = this;
self.getCollectionPoll(collectionName, function(err, collection) {
if (err) return callback(err);
var parsed = self._getSafeParsedQuery(inputQuery, callback);
if (!parsed) return;
// Run the query against a particular mongo document by adding an _id filter
var queryId = parsed.query._id;
if (queryId && typeof queryId === 'object') {
// Check if the query contains the id directly in the common pattern of
// a query for a specific list of ids, such as {_id: {$in: [1, 2, 3]}}
if (Array.isArray(queryId.$in) && Object.keys(queryId).length === 1) {
if (queryId.$in.indexOf(id) === -1) {
// If the id isn't in the list of ids, then there is no way this
// can be a match
return callback(null, false);
} else {
// If the id is in the list, then it is equivalent to restrict to our
// particular id and override the current value
parsed.query._id = id;
}
} else {
delete parsed.query._id;
parsed.query.$and = (parsed.query.$and) ?
parsed.query.$and.concat({_id: id}, {_id: queryId}) :
[{_id: id}, {_id: queryId}];
}
} else if (queryId && queryId !== id) {
// If queryId is a primative value such as a string or number and it
// isn't equal to the id, then there is no way this can be a match
return callback(null, false);
} else {
// Restrict the query to this particular document
parsed.query._id = id;
}
collection.find(parsed.query).limit(1).project({_id: 1}).next()
.then(function(doc) {
callback(null, !!doc);
}, callback);
});
};
// **** Polling optimization
// Can we poll by checking the query limited to the particular doc only?
ShareDbMongo.prototype.canPollDoc = function(collectionName, query) {
for (var operation in collectionOperationsMap) {
if (query.hasOwnProperty(operation)) return false;
}
for (var operation in cursorOperationsMap) {
if (query.hasOwnProperty(operation)) return false;
}
if (
query.hasOwnProperty('$sort') ||
query.hasOwnProperty('$orderby') ||
query.hasOwnProperty('$limit') ||
query.hasOwnProperty('$skip') ||
query.hasOwnProperty('$max') ||
query.hasOwnProperty('$min') ||
query.hasOwnProperty('$returnKey')
) {
return false;
}
return true;
};
// Return true to avoid polling if there is no possibility that an op could
// affect a query's results
ShareDbMongo.prototype.skipPoll = function(collectionName, id, op, query) {
// ShareDB is in charge of doing the validation of ops, so at this point we
// should be able to assume that the op is structured validly
if (op.create || op.del) return false;
if (!op.op) return true;
// Right now, always re-poll if using a collection operation such as
// $distinct or a cursor operation such as $count. This could be
// optimized further in some cases.
for (var operation in collectionOperationsMap) {
if (query.hasOwnProperty(operation)) return false;
}
for (var operation in cursorOperationsMap) {
if (query.hasOwnProperty(operation)) return false;
}