-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathtransactions-common.js
1946 lines (1750 loc) · 77.9 KB
/
transactions-common.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
// *******************************
// Transactions for Meteor + Mongo
// by Brent Abrahams
// brent_abrahams@yahoo.com
// MIT Licence 2017
// *******************************
// This package adds one new mongo collection to your app
// It is exposed to the app via `tx.Transactions`, not via `Transactions`
// In much the same way that we have `Meteor.users` rather than `Users`
Transactions = new Mongo.Collection(Meteor.settings && Meteor.settings.transactionsCollection || "transactions");
if (Meteor.isServer) {
Transactions.allow({
insert: function (userId, doc) { return (_.has(doc, "items") || doc.user_id !== userId) ? false : true; },
update: function (userId, doc, fields, modifier) {
if (userId !== doc.user_id) {
// TODO -- this condition will need to be modified to allow an admin to look through transactions and undo/redo them from the client
// That said, an admin interface shouldn't really be messing with the transactions collection from the client anyway, so ignoring this for now
return false;
}
else {
if (tx._validateModifier(modifier, doc._id)) {
return true;
}
else {
// Transactions.remove({_id:doc._id});
return false;
}
}
},
remove: function (userId, doc) {
var fullDoc = Transactions.findOne({_id: doc._id});
return fullDoc && fullDoc.user_id === userId;
}
});
}
TransactionManager = function () {
// This is instantiated as `tx` and maintains a map that points to the correct instance of `Transact`
// It also carries all of the globally configurable parts of the `tx` object, which intances of `Transact` will reference
// The per-transaction methods that this manager needs to direct to the correct `Transact` instance are:
// tx.start
// tx.insert
// tx.update
// tx.remove
// tx.commit
// tx.cancel
// tx.rollback
// tx.purgeIncomplete
// tx.undo
// tx.redo
// tx.setContext
// tx.mergeContext
// tx.setContextPathValue
// tx.getContext
// tx.transactionStarted
// *******************************************************
// THIS IS THE MAP FROM CONNECTION TO TRANSACTION INSTANCE
// *******************************************************
this._txMap = {};
// This ensures that the map contains a `Transact` instance for each connection and also for the default (when there is no connection)
this._instance = function () {
var instanceKey = 'default';
var currentInvocation = DDP._CurrentInvocation;
if (_.isFunction(currentInvocation.get)) {
var ci = currentInvocation.get();
if (ci && ci.connection && ci.connection.id) {
instanceKey = ci.connection.id;
}
}
var instance = this._txMap[instanceKey];
if (!instance) {
this._txMap[instanceKey] = new Transact();
// Let the instance know its own connection_id
this._txMap[instanceKey]._connectionId = instanceKey;
instance = this._txMap[instanceKey];
}
return instance;
}
// **********************************************************************************************************
// YOU CAN OPTIONALLY OVERWRITE tx.collectionIndex TO MAKE THE TRANSACTIONS WORK FOR CERTAIN COLLECTIONS ONLY
// **********************************************************************************************************
// e.g. in a file shared by client and server, write:
// tx.collectionIndex = {posts:Posts,comments:Comments, etc...}
// where the key is the name of the database collection (e.g. 'posts') and the value is the actual Meteor Mongo.Collection object (e.g. Posts)
// by default, all collections are added to tx.collectionIndex on startup in a "Meteor.startup(function (){ Meteor.defer(function () { ..." block
// so if you are planning to overwrite tx.collectionIndex, you'll also need to wrap your code in "Meteor.startup(function (){ Meteor.defer(function () { ..." block
// there's no real need to do this for most applications though
this.collectionIndex = {};
// ********************************************************************
// YOU CAN OPTIONALLY OVERWRITE ANY OF THESE (e.g. tx.logging = false;)
// ********************************************************************
// Recommendations about _where_ to overwrite the following attributes/methods are given as [BOTH], [SERVER], or [CLIENT]
// Turn logging on or off
// [BOTH]
this.logging = true;
// By default, messages are logged to the console
// [BOTH]
this.log = function () { if (this.logging) { _.each(arguments, function (message) { console.log(message); }) } };
// To show the connection in the logging from `Transact` instances, set `tx.showConnection = true;`
// Useful for debugging
this.showConnection = false;
// Because most/many db writes will come through the transaction manager, this is a good place to do some permission checking
// NOTE: this permission check is the only thing standing between a user and the database if a transaction is committed from a method with no surrounding permission checks of its own
// NOTE: if you're commiting transactions from the client, you'll definitely need this as writes do not go through your allow and deny rules
// [BOTH]
this.checkPermission = function (command, collection, doc, modifier) { return true; }; // commands are "insert", "update", "remove"
// For the purpose of filtering transactions later, a "context" field is added to each transaction
// By default, we don't do anything -- the context is empty, but there are probably certain fields in the document that we could record to use for filtering.
// Remember, if there are multiple document being processed by a single transaction, the values from the last document in the queue will overwrite values for fields that have taken a value from a previous document - last write wins
// OVERWRITING THIS WITH tx.makeContext = function () { ... } IS STRONGLY RECOMMENDED
// [BOTH]
this.makeContext = function (command, collection, doc, modifier) { return {}; }; // TODO -- detect routes and add the path to the context automatically (separate, per router, packages)
// If requireUser is set to false, any non-logged in user, using the `babrahams:undo-redo` package gets the undo-redo stack of any non-logged-in user
// For security purposes this should always be set to true in real apps that use the `babrahams:undo-redo` package
// [BOTH]
this.requireUser = false;
// This function is called on the client when the user tries to undo (or redo) a transaction in which some (or all) documents have been altered by a later transaction
// [CLIENT]
this.onTransactionExpired = function () { alert('Sorry. Other edits have been made, so this action can no longer be reversed.'); };
// If app code forgets to close a transaction on the server, it will autoclose after the following number of milliseconds
// If a transaction is open on the client, it just stays open indefinitely
// [BOTH]
this.idleTimeout = 5000;
// If something goes wrong and a transaction isn't closed it remains open (on the client - TODO - make the client time out the same way the server does)
// This is also a problem on the server, as a transaction will remain open until the it times out
// and meanwhile other transactions can't be started and committed
// The following can be set to true to stop this from happening, but it means you have to be strict about coding your logic
// so that only one transaction is started at any given time
// [BOTH]
this.forceCommitBeforeStart = false;
// By default, the package swallows (but logs) errors during a commit
// If you want it to rethrow the err, set this flag to false
// [BOTH]
this.rethrowCommitError = false;
// By default, documents are hard deleted and a snapshot of the document the moment before deletion is stored for retrieval in the transaction document
// This is much more prone to causing bugs and weirdness in apps, e.g. if a removed doc is restored after documents it depends on have been removed
// (and whose removal should normally have caused the restored doc to have also been removed and tagged with the same transaction_id)
// It's safer to turn softDelete on for complex apps, but having it off makes this package work out of the box better, as the user doesn't have to
// use `,deleted:{$exists:false}` in their `find` and `findOne` selectors to keep deleted docs out of the result
// [BOTH]
this.softDelete = false;
// This flag tells the package how to deal with incomplete transactions, undos and redos on startup
// The possible modes are:
// `complete` - which will try to complete any pending transactions
// `rollback` - which will try to restore db to state prior to the pending transaction
// any other value will just leave the db in the state it was left at last shutdown
// [SERVER]
this.selfRepairMode = 'complete';
// If you want to limit the volume of rubbish in the transactions collection
// you can set `tx.removeRolledBackTransactions = true`
// It is false by default because having a record in the db helps with debugging
// [BOTH]
this.removeRolledBackTransactions = false;
// Overwrite this with something like `tx.lodash = lodash` if you have a lodash package installed
// This gives you access to `tx.mergeContext` and `tx.setContextPathValue`
this.lodash = null;
// The following function `_inverseUsingSet` is necessary for `inverseOperations`
// It is not intended to be a part of the public API
// Default inverse operation that uses $set to restore original state of updated fields
this._inverseUsingSet = function (collection, existingDoc, updateMap, opt) {
var self = this, inverseCommand = '$set', formerValues = {};
_.each(_.keys(updateMap), function (keyName) {
// Given a dot delimited string as a key, and an object, find the value
var _drillDown = function (obj, key) {
return Meteor._get.apply(null, [obj].concat(key.split('.')));
// Previous implementation, which worked fine but was more LOC than necessary
/*var pieces = key.split('.');
if (pieces.length > 1) {
var newObj = obj ? obj[pieces[0]] : {};
pieces.shift();
return this._drillDown(newObj,pieces.join('.'));
}
else {
if (obj) {
return obj[key];
}
else {
return; // undefined
}
}*/
}
var formerVal = _drillDown(existingDoc || {}, keyName);
if (typeof formerVal !== 'undefined') {
// Restore former value
inverseCommand = '$set';
formerValues[keyName] = formerVal;
}
else {
// Field was already unset, so just $unset it again
inverseCommand = '$unset';
formerValues[keyName] = 1;
}
});
return {command: inverseCommand, data: formerValues};
};
// Functions to work out the inverse operation that will reverse a single collection update command.
// This default implementation attempts to reverse individual array $set and $addToSet operations with
// corresponding $pull operations, but this may not work in some cases, eg:
// 1. if a $addToSet operation does nothing because the value is already in the array, the inverse $pull will remove that value from the array, even though
// it was there before the $addToSet action
// 2. if a $addToSet operation had a $each qualifier (to add multiple values), the default inverse $pull operation will fail because $each is not suported for $pull operations
//
// You may wish to provide your own implementations that override some of these functions to address these issues if they affect your own application.
// For example, store the entire state of the array being mutated by a $set / $addToSet or $pull operation, and then restore it using a inverse $set operation.
// The tx.inverse function is called with the tx object as the `this` data context.
// [BOTH]
this.inverseOperations = {
'$set': this._inverseUsingSet,
'$addToSet': function (collection, existingDoc, updateMap, opt) {
// Inverse of $addToSet is $pull.
// TODO -- not really -- if an element is already present, this will pull it
// out after an undo, leaving the value changed
// This will not work if $addToSet uses modifiers like $each.
// In that case, you need to restore state of original array using $set
return {command: '$pull', data: updateMap};
},
'$unset': this._inverseUsingSet,
'$pull': function (collection, existingDoc, updateMap, opt) {
// Inverse of $pull is $addToSet.
// TODO -- same problem as $addToSet above, but in reverse
return {command: '$addToSet', data: updateMap};
},
'$inc': this._inverseUsingSet,
'$push': function (collection, existingDoc, updateMap, opt) {
// Inverse of $push is $pull.
// This will not work if $push uses modifiers like $each, or if pushed value has duplicates in same array (because $pull will remove all instances of that value).
// In that case, you need to restore state of original array using $set
return {command: '$pull', data: updateMap};
},
};
// ******************************************************************************************************
// THESE ARE METHODS EXTERNAL TO THE PACKAGE THAT ARE CALLED OUTSIDE THE CONTEXT OF A `Transact` INSTANCE
// ******************************************************************************************************
this.apiFunctions = [
'start',
'insert',
'update',
'remove',
'cancel',
'commit',
'rollback',
'purgeIncomplete',
'undo',
'redo',
'setContext',
'mergeContext',
'setContextPathValue',
'getContext',
'transactionStarted'
]
// *****************************************************************************************************
// THESE ARE METHODS INTERNAL TO THE PACKAGE BUT ARE CALLED OUTSIDE THE CONTEXT OF A `Transact` INSTANCE
// *****************************************************************************************************
this.internalFunctions = [
'_validateModifier',
'_repairAllIncomplete',
'_userOrNull',
'_processTransaction',
'_checkTransactionFields',
'_unpackageForUpdate',
'_changeItemState',
'_repairIncomplete'
];
var self = this;
_.each(this.apiFunctions.concat(this.internalFunctions), function (fnName) {
self[fnName] = function () {
var instance = self._instance();
return instance[fnName].apply(instance, arguments);
}
});
}
// ******************************
// Instantiation of the tx object
// ******************************
// This (tx) is the object that gets exported for the app to interact with
if (typeof tx === 'undefined') {
tx = new TransactionManager();
tx.Transactions = Transactions; // Expose the Transactions collection via tx
}
else {
throw new Meteor.Error('`tx` is already defined in the global scope. The babrahams:transactions package won\'t work.');
}
// On the server, instances of `Transact` need to be deleted when the connection closes
// Keep an eye on server memory -- this may not be enough to prevent a memory leak
// , in which case we can take stronger action
if (Meteor.isServer) {
Meteor.onConnection(function (connection) {
if (connection.id) {
connection.onClose(function () {
delete tx._txMap[connection.id];
});
}
});
}
Transact = function () {
// ***************************
// DONT OVERWRITE ANY OF THESE
// ***************************
// These are transient per-transaction properties that are used internally by the `Transact` instance that is created for the given transaction
this._connectionId = null; // Should be immediately overwritten after instantiation
this._transaction_id = null;
this._autoTransaction = false;
this._items = [];
this._startAttempts = 0;
this._rollback = false;
this._rollbackReason = '';
this._autoCancel = null;
this._lastTransactionData = null;
this._context = {};
this._description = '';
this._rethrowCommitError = false;
}
// **********
// PUBLIC API
// **********
// Either use these methods together on the client, or use them together on the server, but don't try mixing the two!
/**
* Starts a transaction
*/
Transact.prototype.start = function (description, options) {
if (description && !_.isString(description)) {
if (_.isObject(description) && !_.isArray(description) && !_.isDate(description)) {
options = description;
description = options.description || undefined;
}
else {
throw new Meteor.Error('transaction-not-started', 'Wrong data type passed to start function', 'First parameter must be a string or an object literal');
}
}
if (tx.requireUser && !Meteor.userId()) {
this.log('User must be logged in to start a transaction.');
this._cleanReset();
return;
}
if (tx.rethrowCommitError || (options && options.rethrowCommitError)) {
this._rethrowCommitError = (options && options.rethrowCommitError === false) ? false : true;
}
this._resetAutoCancel(Meteor.isClient);
if (!this._transaction_id) {
// Set transaction description
if (typeof description === 'undefined') {
description = 'last action';
}
this._description = description;
// Set any transaction options e.g. context
if (typeof options === 'object') {
if ('context' in options) {
this._setContext(options['context']);
}
}
this._transaction_id = Random.id(); // Transactions.insert({user_id:Meteor.userId(),timestamp:(ServerTime.date()).getTime(),description:description});
this.log('Started "' + description + '" with transaction_id: ' + this._transaction_id + ((this._autoTransaction) ? ' (auto started)' : ''));
return this._transaction_id;
}
else {
this.log('An attempt to start a transaction ("' + description + '") was made when a transaction was already open. Open transaction_id: ' + this._transaction_id);
if ((tx.forceCommitBeforeStart && !(options && (options.useExistingTransaction || options.forceCommitBeforeStart === false))) || (options && options.forceCommitBeforeStart)) {
// null parameter to force the commit
// last parameter starts a new transaction after the commit
tx.commit(null, undefined, undefined, {description: description, options: options});
}
else {
this._startAttempts++;
if (!(options && options.useExistingTransaction)) {
return false;
}
else {
this.log('Using existing transaction');
return this._transaction_id;
}
}
}
}
/**
* Checks whether a transaction is already started
*/
Transact.prototype.transactionStarted = function () {
return this._transaction_id || null;
}
/**
* Commits all the changes (actions) queued in the current transaction
*/
Transact.prototype.commit = function (txid, callback, newId, startNewTransaction) {
var self = this;
var rethrowCommitError = self._rethrowCommitError;
if (tx.requireUser && !Meteor.userId()) {
self.log('User must be logged in to commit a transaction.');
this._callback(txid, callback, new Meteor.Error('user-required','No user logged in.'), false, rethrowCommitError);
return;
}
this._lastTransactionData = {};
this._lastTransactionData.transaction_id = this._transaction_id;
if (!this._transaction_id) {
this._cleanReset();
self.log("Commit reset transaction to clean state");
this._callback(txid, callback, new Meteor.Error('no-transactions-open', 'No transaction open.'), false, rethrowCommitError);
return;
}
// If a transaction is committed and either null is passed or the exact transaction_id value
// then we force commit, no matter how many start attempts there have been
// otherwise, if there are startAttempts recorded (i.e. tried to start a transaction explicitly while another one was open)
// reduce the number of startAttempts by one, fire the callback with false and return
if ((_.isString(txid) && txid === this._transaction_id) || txid === null) {
// Force commit now
self.log("Forced commit");
}
else if (this._startAttempts > 0) {
this._startAttempts--;
this._callback(txid, callback, new Meteor.Error('multiple-transactions-open', 'More than one transaction open. Closing one now to leave ' + this._startAttempts + ' transactions open.'), false, rethrowCommitError);
return;
}
if (_.isEmpty(this._items)) {
// Don't record the transaction if nothing happened
// Transactions.remove({_id:this._transaction_id});
self.log('Empty transaction: ' + this._transaction_id);
}
if (this._rollback) {
// One or more permissions failed or the transaction was cancelled, don't process the execution stack
var error = this._rollbackReason;
var errorDescription = '';
switch (this._rollbackReason) {
case 'permission-denied' :
errorDescription = 'One or more permissions were denied, so transaction was rolled back.';
break;
case 'transaction-cancelled' :
errorDescription = 'The transaction was cancelled programatically, so it was rolled back.';
break;
default :
errorDescription = 'An error occurred when processing an action.';
suppressError = false;
break;
}
this.rollback();
this._callback(txid, callback, new Meteor.Error(error, errorDescription), false, rethrowCommitError);
return;
}
else {
self.log('Beginning commit with transaction_id: ' + this._transaction_id);
var doRollback = function (err) {
self.log("Rolling back changes");
self.rollback();
self._callback(txid, callback, new Meteor.Error('error', 'An error occurred, so transaction was rolled back.', err), false, rethrowCommitError);
}
try {
var runCallback = function (res) {
if (!self._lastTransactionData) {
self._lastTransactionData = {};
}
self._lastTransactionData.transaction_id = self._transaction_id;
self._lastTransactionData.writes = res.items;
var newIds = _.reduce(res.items, function (memo, item) {
if (item.action === 'insert') {
if (typeof memo[item.collection] === "undefined") {
memo[item.collection] = [];
}
memo[item.collection].push(item._id);
}
return memo;
}, {});
self._cleanReset();
self.log("Commit reset transaction manager to clean state");
self._callback(txid, callback, null, newIds || true);
if (_.isObject(startNewTransaction)) {
self.start(startNewTransaction.description, startNewTransaction.options);
}
}
// Okay, this is it -- we're really going to process the queue
// So no need to time out the transaction if the processing takes a while
// This will be async in the client and syncronous on the server
if (Meteor.isServer) {
Meteor.clearTimeout(this._autoCancel);
var cannotOverridePermissionCheck = false;
try {
var result = self._processTransaction(this._transaction_id, this._description, this._items, this._context, cannotOverridePermissionCheck);
}
catch (err) {
var err = err;
}
if (!result) {
self._callback(txid, callback, new Meteor.Error('commit-error', 'An error occurred, so transaction was rolled back.', JSON.stringify(err)), false, rethrowCommitError);
return;
}
runCallback(result);
}
else {
clearTimeout(this._autoCancel);
Meteor.call("_meteorTransactionsProcess", this._transaction_id, this._description, this._items, this._context, function (err, res) {
if (err || !res) {
if (err) {
// self.log(err);
}
self._callback(txid, callback, new Meteor.Error('commit-error', 'An error occurred, so transaction was rolled back.', JSON.stringify(err)), false, rethrowCommitError);
return;
}
else {
// Just in case Meteor.is[SomethingElse] that isn't server but isn't client either
if (Meteor.isClient) {
Tracker.flush(); // Not sure about this
}
runCallback(res);
}
});
}
/*Transactions.update({_id:this._transaction_id}, {$set:_.extend({context:this._context}, {items:this._items})});*/
}
catch (err) {
self.log(err);
doRollback(err);
self._callback(txid, callback, new Meteor.Error('commit-error', 'An error occurred, so transaction was rolled back.', JSON.stringify(err)), false, rethrowCommitError);
return;
}
}
return true; // A flag that at least the call was made
// Only the callback from the _meteorTransactionsProcess will really be able to tell us the result of this call
}
/**
* Allows programmatic call of a rollback
*/
Transact.prototype.rollback = function (rollbackAllDoneItems) {
// Need to undo all the instant stuff that's been done
// TODO -- this is pretty half-baked -- we should be checking that actions are actually completed before continuing -- not just watching for errors
// Eventually, this should be rolled into a single universal function
// that iterates over the items array and makes db writes
// TODO -- this should probably be run as a method
var self = this;
var items = self._items.reverse();
var error = false;
if (Meteor.isClient) {
// Don't let people mess with this from the client
// Only the server can call tx.rollback(true);
rollbackAllDoneItems = false;
}
_.each(items, function (obj, index) {
if (obj.action === "remove") {
if ((obj.instant || rollbackAllDoneItems) && obj.state === 'done') {
try {
if (obj.doc) {
// This was removed from the collection, we need to reinsert it
tx.collectionIndex[obj.collection].insert(obj.doc);
}
else {
// This was soft deleted, we need to remove the deleted field
tx.collectionIndex[obj.collection].update({_id: obj._id}, {$unset: {deleted: 1, transaction_id: self._transaction_id}});
}
self.log('Rolled back remove');
}
catch (err) {
self.log(err);
error = true;
}
}
}
if (obj.action === "update") {
if (((obj.instant || rollbackAllDoneItems) && obj.state === 'done') && typeof obj.inverse !== 'undefined' && obj.inverse.command && obj.inverse.data) {
var operation = {};
operation[obj.inverse.command] = self._unpackageForUpdate(obj.inverse.data); // console.log(operation);
try {
tx.collectionIndex[obj.collection].update({_id: obj._id}, operation);
self.log('Rolled back update');
}
catch (err) {
self.log(err);
error = true;
}
}
}
if (obj.action === "insert") {
if ((obj.instant || rollbackAllDoneItems) && obj.state === 'done') {
var sel = {_id: obj._id};
// This transaction_id check is in case the document has been subsequently edited -- in that case, we don't want it removed from the database completely
sel.transaction_id = self._transaction_id;
try {
tx.collectionIndex[obj.collection].remove(sel);
self.log('Rolled back insert');
}
catch (err) {
self.log(err);
error = true;
}
}
}
if (!error) {
self._changeItemState({
txid: self._transaction_id,
index: (items.length - 1) - index, // Because order was reversed for rollback
state: "rolledBack"
});
}
});
if (error) {
self.log("Rollback failed -- you'll need to check your database manually for corrupted records.");
self.log("Here is a log of the actions that were tried and their inverses:");
self.log("(it was probably one of the inverse actions that caused the problem here)");
self.log(EJSON.stringify(items, null, 2));
}
// Server only
// Client can't change the transactions collection directly anyway
if (Meteor.isServer) {
if (tx.removeRolledBackTransactions) {
if (rollbackAllDoneItems) {
Transactions.remove({_id: this._transaction_id});
}
self.log('Incomplete transaction removed: ' + this._transaction_id);
}
else {
if (!Transactions.findOne({_id: this._transaction_id})) {
if (this._transaction_id) {
var transactionRecord = {_id: this._transaction_id, user_id: tx._userOrNull(), description: this._description, items: items, context: this._context, lastModified: ServerTime.date(), state: "rolledBack"};
Transactions.insert(transactionRecord, function (err, res) {
if (err) {
self.log('No database record for transaction:', self._transaction_id);
}
});
}
}
else {
Transactions.update({_id: this._transaction_id}, {$set: {state: "rolledBack"}});
}
}
}
self._cleanReset();
self.log("Rollback reset transaction manager to clean state");
}
/**
* Queue an insert
*/
Transact.prototype.insert = function (collection, newDoc, opt, callback) {
if (this._rollback || (tx.requireUser && !Meteor.userId())) {
return;
}
// We need to pass the options object when we do the actual insert
// But also need to identify any callback functions
var callback = (_.isFunction(callback)) ? callback : ((typeof opt !== 'undefined') ? ((_.isFunction(opt)) ? opt : ((_.isFunction(opt.callback)) ? opt.callback : undefined)) : undefined);
if (opt && _.isObject(opt.tx)) {
opt = opt.tx;
}
opt = (_.isObject(opt)) ? _.omit(opt, 'tx') : undefined; // This is in case we're going to pass this options object on to, say, collection2 (tx must be gone or we'll create an infinite loop)
newDoc = _.clone(newDoc);
// NOTE: "collection" is the collection object itself, not a string
if (this._permissionCheckOverridden(opt) || this._permissionCheck("insert", collection, newDoc, {})) {
var self = this;
this._openAutoTransaction(opt && opt.description || 'add ' + collection._name.slice(0, - 1), opt);
self._setContext((opt && opt.context) || tx.makeContext('insert', collection, newDoc, {}));
if ((typeof opt !== 'undefined' && opt.instant)) { // || this._autoTransaction
try {
var newId = newDoc._id || Random.id();
_.extend(newDoc, {_id: newId, transaction_id: self._transaction_id});
var newId = self._doInsert(collection, newDoc, opt, callback); // Should give the same newId value as the one we passed
var item = self._createItem('insert', collection, newId, {doc: newDoc}, true, self._permissionCheckOverridden(opt));
this._recordTransaction(item);
self._pushToRecord("insert", collection, newId, {doc: newDoc}, true, self._permissionCheckOverridden(opt)); // true is to mark this as an instant change
this._closeAutoTransaction(opt, callback, newId);
self.log("Executed instant insert");
return newId;
}
catch(err) {
self.log(err);
self.log("Rollback initiated by instant insert command");
this._rollback = true;
this._rollbackReason = 'insert-error';
}
}
var newId = newDoc._id || Random.id();
// var newId = self._doInsert(collection,_.extend(newDoc,{transaction_id:self._transaction_id}),opt,callback);
self._pushToRecord("insert", collection, newId, {doc: _.extend(newDoc, {_id: newId, transaction_id: self._transaction_id})}, false, self._permissionCheckOverridden(opt));
self.log("Pushed insert command to stack: " + this._transaction_id); // + ' (Auto: ' + this._autoTransaction + ')'
this._closeAutoTransaction(opt, callback);
return newId;
}
else {
this._rollback = true;
this._rollbackReason = 'permission-denied';
this.log("Insufficient permissions to insert this document into " + collection._name + ':', newDoc); // Permission to insert not granted
return;
}
}
/**
* Queue a remove
*/
Transact.prototype.remove = function (collection, doc, opt, callback) {
// Remove any document with a field that has this val
// NOTE: "collection" is the collection object itself, not a string
if (this._rollback || (tx.requireUser && !Meteor.userId())) {
return;
}
// We need to pass the options object when we do the actual remove
// But also need to identify any callback functions
var callback = (_.isFunction(callback)) ? callback : ((typeof opt !== 'undefined') ? ((_.isFunction(opt)) ? opt : ((_.isFunction(opt.callback)) ? opt.callback : undefined)) : undefined);
if (opt && _.isObject(opt.tx)) {
opt = opt.tx;
}
var _id = (_.isObject(doc)) ? doc._id : doc;
var existingDoc = collection.findOne({_id: _id}); // (!_.isObject(doc)) ? collection.findOne({_id: doc}) : doc; // , {transform: null}
if (!(_id && existingDoc)) {
this.log('No document found. Make sure you provide an _id field for a document that exists. You passed: ' + JSON.stringify(doc));
}
if (this._permissionCheckOverridden(opt) || this._permissionCheck("remove", collection, existingDoc, {})) {
var self = this;
this._openAutoTransaction(opt && opt.description || 'remove ' + collection._name.slice(0, - 1), opt);
var sel = {_id: _id};
if (Meteor.isServer) {
sel.deleted = {$exists: false}; // Can only do removes on client using a simple _id selector
}
self._setContext((opt && opt.context) || tx.makeContext('remove', collection, existingDoc, {}));
if (opt && opt.instant) {
try {
self._doRemove(collection, _id, sel, true, opt, callback);
self.log("Executed instant remove");
}
catch(err) {
self.log(err);
self.log("Rollback initiated by instant remove command");
this._rollback = true;
this._rollbackReason = 'remove-error';
}
}
else {
self._doRemove(collection, _id, sel, false, opt, callback);
self.log("Pushed remove command to stack: " + this._transaction_id); // + ' (Auto: ' + this._autoTransaction + ')'
}
this._closeAutoTransaction(opt, callback);
return !this._rollback; // Remove was executed or queued for execution
}
else {
this._rollback = true;
this._rollbackReason = 'permission-denied';
this.log("Insufficient permissions to remove this document from " + collection._name + ':', existingDoc); // Permission to remove not granted
return;
}
}
/**
* Queue an update
*/
Transact.prototype.update = function (collection, doc, updates, opt, callback) {
// NOTE: "field" should be of the form {$set:{field:value}}, etc.
// NOTE: "collection" is the collection object itself, not a string
if (this._rollback || (tx.requireUser && !Meteor.userId())) {
return;
}
// We need to pass the options object when we do the actual update
// But also need to identify any callback functions
var callback = (_.isFunction(callback)) ? callback : ((typeof opt !== 'undefined') ? ((_.isFunction(opt)) ? opt : ((_.isFunction(opt.callback)) ? opt.callback : undefined)) : undefined);
// Check for upsert both places to catch
// `collection.upsert(sel, mod, {tx: {...}})`, which gets translated to
// roughly `collection.update(sel, mod, {upsert: true, tx: {...}})`.
if (opt && (opt.upsert || (_.isObject(opt.tx) && opt.tx.upsert))) {
throw new Meteor.Error('upsert-attempted-in-transaction', 'Upsert is not supported', "babrahams:transactions currently does not support upsert.");
}
if (opt && _.isObject(opt.tx)) {
opt = opt.tx;
}
var opt = (_.isObject(opt)) ? _.omit(opt, 'tx') : undefined;
var self = this;
var _id = (_.isObject(doc)) ? doc._id : doc;
var existingDoc = collection.findOne({_id: _id}); // , {transform: null}
// var existingDoc = (!_.isObject(doc)) ? collection.findOne({_id:_id}) : doc;
// the above is slightly more efficient, in that it doesn't hit the database again
// but potential buggy behaviour if a partial doc is passed and the field being updated
// isn't in it and it's a $set command and so the inverse is wrongly taken to be $unset
if (!(_id && existingDoc)) {
self.log('No document found. Make sure you provide an _id field for a document that exists (and, on the client, is published). You passed: ' + JSON.stringify(doc));
}
if (this._permissionCheckOverridden(opt) || this._permissionCheck("update", collection, existingDoc, updates)) {
this._openAutoTransaction(opt && opt.description || 'update ' + collection._name.slice(0, - 1), opt);
var actionFields = _.pairs(updates); // console.log('actionFields:', actionFields);
// If the command is $set, the update map needs to be split into individual fields in case some didn't exist before and some did
// in which case different fields will require different inverse operations
actionFields = _.reduce(actionFields, function (memo, action) {
var command = action[0]; // console.log("the command:", command);
var updateMap = action[1]; // console.log("the map:", updateMap);
if (command === '$set') {
actions = _.map(updateMap, function (val, key) {
var obj = {};
obj[key] = val;
return obj;
}); // console.log("the actions:", actions);
}
else {
actions = [updateMap];
}
_.each(actions, function (update) {
memo.push([command, update]);
});
return memo;
}, []); // console.log("actionFields:", actionFields);
var actionFieldsCount = actionFields.length;
for (var i = 0; i < actionFieldsCount; i++) {
var command = actionFields[i][0]; // console.log("command:", command);
var updateMap = actionFields[i][1]; // console.log("updateMap:", updateMap, EJSON.stringify(updateMap));
var inverse;
if (typeof opt === 'undefined' || typeof opt.inverse === 'undefined') {
// var fieldName = _.keys(actionField[0][1])[0]; // console.log(fieldName);
if (typeof opt === 'undefined') {
opt = {};
}
// console.log("inverse called with (collection, existingDoc, updateMap, opt):", collection, existingDoc, updateMap, opt);
inverse = _.isFunction(tx.inverseOperations[command]) && tx.inverseOperations[command].call(self, collection, existingDoc, updateMap, opt) || tx._inverseUsingSet(collection, existingDoc, updateMap, opt);
// console.log("inverse:", inverse);
}
else {
// This "opt.inverse" thing is only used if you need to define some tricky inverse operation, but will probably not be necessary in practice
// a custom value of opt.inverse needs to be an object of the form:
// {command: "$set", data: {fieldName: value}}
inverse = opt.inverse;
}
// console.log("inverse:", inverse);
self._setContext((opt && opt.context) || tx.makeContext('update', collection, existingDoc, updates));
var updateData = {command: command, data: updateMap};
if (opt && opt.instant) {
try {
self._doUpdate(collection, _id, updates, updateData, inverse, true, opt, callback, (i === (actionFieldsCount - 1)) ? true : false);
self.log("Executed instant update"); // true param is to record this as an instant change
}
catch(err) {
self.log(err);
self.log("Rollback initiated by instant update command");
this._rollback = true;
this._rollbackReason = 'update-error';
}
}
else {
(function (updateData, inverse, execute) { // console.log('updateData, inverse, execute:', updateData, inverse, execute);
self._doUpdate(collection, _id, updates, updateData, inverse, false, opt, callback, execute);
self.log("Pushed update command to stack: " + this._transaction_id); // + ' (Auto: ' + this._autoTransaction + ')'
}).call(this, updateData, inverse, (i === (actionFieldsCount - 1)) ? true : false);
}
}
this._closeAutoTransaction(opt, callback);
return !this._rollback; // Update was executed or queued for execution
}
else {
this._rollback = true;
this._rollbackReason = 'permission-denied';
self.log("Insufficient permissions to update this document in " + collection._name + ':', existingDoc); // Permission to update not granted
return;
}
}
/**
* Cancels a transaction, but doesn't roll back immediately
* When the transaction is committed, no queued actions will be executed
* and any instant updates, inserts or removes that were made will be rolled back
*/
Transact.prototype.cancel = function () {
this.log('Transaction cancelled');
this._rollback = true;
this._rollbackReason = 'transaction-cancelled';
}
/**
* Undo the last transaction by the user
*/
Transact.prototype.undo = function (txid, callback) {
var self = this;
var callback = (_.isFunction(txid)) ? txid : callback;
Meteor.call("_meteorTransactionsUndo", (_.isString(txid)) ? txid : null, function (err, res) {
if (Meteor.isClient && res && _.isFunction(tx.onTransactionExpired)) {
tx.onTransactionExpired.call(self, err, res);
}
if (_.isFunction(callback)) {
callback.call(self, err, !res);
}
});
}
/**
* Redo the last transaction undone by the user
*/
Transact.prototype.redo = function (txid, callback) {
var self = this;
var callback = (_.isFunction(txid)) ? txid : callback;
Meteor.call("_meteorTransactionsRedo", (_.isString(txid)) ? txid : null, function (err, res) {
if (Meteor.isClient && res && _.isFunction(tx.onTransactionExpired)) {
tx.onTransactionExpired.call();
}
if (_.isFunction(callback)) {
callback.call(self, err, !res);
}
});
}
/**
* Manually add context to current transaction using _.extend (equivalent of lodash.assign)
*/
Transact.prototype.setContext = function (context) {
this._setContext(context);
}
/**
* Manually add context to current transaction using lodash.merge
*/
Transact.prototype.mergeContext = function (context) {
tx.lodash.merge(this._context, context);
}