-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
3143 lines (2735 loc) · 87.5 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
/* Copyright 2012-2013 Sam Elsamman
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
RemoteObjectTemplate extends ObjectTemplate to provide a synchronization mechanism for
objects created with it's templates. The synchronization
*/
(function(root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['q', 'underscore', '@havenlife/supertype'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('q'), require('underscore'), require('@havenlife/supertype'));
} else {
root.RemoteObjectTemplate = factory(root.Q, root._, root.ObjectTemplate);
}
})(this, function(Q, _, SupertypeModule) {
'use strict';
var ObjectTemplate = SupertypeModule.default;
const RemoteObjectTemplate = ObjectTemplate._createObject();
RemoteObjectTemplate._useGettersSetters = typeof window === 'undefined';
RemoteObjectTemplate.role = 'client';
if (typeof window === 'undefined') {
RemoteObjectTemplate.role = 'server';
}
RemoteObjectTemplate.__changeTracking__ = true; // Set __changed__ when setter fires
RemoteObjectTemplate.__conflictMode__ = 'hard';
/**************************** Public Interface **********************************/
RemoteObjectTemplate.logLevel = 0;
RemoteObjectTemplate.maxClientSequence = 1;
RemoteObjectTemplate.nextObjId = 1;
/**
* Purpose unknown
*
* @param {unknown} level unknown
* @param {unknown} data unknown
*/
RemoteObjectTemplate.log = function log(level, data) {
// OBSOLETE
if (level > this.logLevel) {
return;
}
let extraID = '';
if (this.reqSession && this.reqSession.loggingID) {
extraID = '-' + this.reqSession.loggingID;
}
const t = new Date();
const time =
t.getFullYear() +
'-' +
(t.getMonth() + 1) +
'-' +
t.getDate() +
' ' +
t.toTimeString().replace(/ .*/, '') +
':' +
t.getMilliseconds();
const message = time + '(' + this.currentSession + extraID + ') ' + 'RemoteObjectTemplate:' + data;
this.logger.info(message);
};
/**
* Obtain a session for tracking subscriptions
*
* @param {unknown} role unknown
* @param {unknown} sendMessage unknown
* @param {unknown} sessionId unknown
*
* @returns {*} unknown
*/
RemoteObjectTemplate.createSession = function createSession(role, sendMessage, sessionId) {
if (!this.sessions) {
this.nextSubscriptionId = 0;
this.nextSessionId = 1;
this.sessions = {};
}
if (!sessionId) {
sessionId = this.nextSessionId++;
}
this.setSession(sessionId);
this.sessions[sessionId] = {
subscriptions: {}, // Change listeners
sendMessage: sendMessage, // Send message callback
sendMessageEnabled: !!sendMessage,
remoteCalls: [], // Remote calls queued to go out
pendingRemoteCalls: {}, // Remote calls waiting for response
nextPendingRemoteCallId: 1,
nextSaveSessionId: 1,
savedSessionId: 0,
nextSubscriptionId: 0,
objects: {},
nextObjId: 1,
dispenseNextId: null // Force next object Id
};
if (role instanceof Array) {
for (var ix = 0; ix < role.length; ++ix) {
this.subscribe(role[ix]);
}
this.role = role[1];
} else {
this.subscribe(role);
this.role = role;
}
return sessionId;
};
/**
* Remove the session from the sessions map, rejecting any outstanding promises
*
* @param {unknown} sessionId unknown
*/
RemoteObjectTemplate.deleteSession = function deleteSession(sessionId) {
let session = this._getSession(sessionId);
for (var calls in session.remoteCalls) {
session.remoteCalls[calls].deferred.reject({ code: 'reset', text: 'Session resynchronized' });
}
if (this.sessions[sessionId]) {
delete this.sessions[sessionId];
}
};
/**
* After resynchronizing sessions we need to set a new sequence number to be used in
* new objects to avoid conflicts with any existing ones the remote session may have
*
* @param {unknown} nextObjId unknown
*/
RemoteObjectTemplate.setMinimumSequence = function setMinimumSequence(nextObjId) {
this._getSession().nextObjId = Math.max(nextObjId, this._getSession().nextObjId);
};
/**
* Save the session data in a way that can be serialized/de-serialized
*
* @param {unknown} sessionId unknown
*
* @returns {Object} unknown
*/
RemoteObjectTemplate.saveSession = function saveSession(sessionId) {
const session = this._getSession(sessionId);
session.nextSaveSessionId = session.nextSaveSessionId + 1;
session.savedSessionId = session.nextSaveSessionId;
const objects = session.objects;
session.objects = {};
const str = {
callCount: this.getPendingCallCount(sessionId), // Can't just restore on another server and carry on
revision: session.savedSessionId, // Used to see if our memory copy good enough
referenced: new Date().getTime(), // Used for reaping old sessions
data: JSON.stringify(session) // All the session data
};
session.objects = objects;
this.logger.debug({ component: 'semotus', module: 'saveSession', activity: 'save' });
return str;
};
/**
* A public function to determine whether there are remote calls in progress
*
* @param {String} sessionId Unique identifier from which the session is fetched.
*
* @returns {Number} The number of remote calls pending in the session.
*/
RemoteObjectTemplate.getPendingCallCount = function getPendingCallCount(sessionId) {
const session = this._getSession(sessionId);
return Object.keys(session.pendingRemoteCalls).length;
};
/**
* Restore session that was potentially serialized/de-searialized
*
* A revision number is used to determine whether the in-memory copy is good
*
* @param {unknown} sessionId - the id under which it was created with createSession
* @param {unknown} savedSession - the POJO version of the sesion data
* @param {unknown} sendMessage - new message function to be in effect
*
* @returns {Boolean} false means that messages were in flight and a reset is needed
*/
RemoteObjectTemplate.restoreSession = function restoreSession(sessionId, savedSession, sendMessage) {
this.setSession(sessionId);
const session = this.sessions[sessionId];
this.logger.debug({ component: 'semotus', module: 'restoreSession', activity: 'save' });
if (session) {
if (session.savedSessionId == savedSession.revision) {
return true;
} else {
delete this.sessions[sessionId];
}
}
this.sessions[sessionId] = JSON.parse(savedSession.data);
this.sessions[sessionId].sendMessage = sendMessage;
return savedSession.callCount > 0;
};
/**
* Indicate that all changes have been accepted outside of the message
* mechanism as would usually happen when a session is starting up
*
* @param {unknown} sessionId unknown
*/
RemoteObjectTemplate.syncSession = function syncSession(sessionId) {
this._getSession(sessionId);
this.getChanges();
this._deleteChanges();
};
/**
* Set the current session to a session id returned from createSession()
* Relies on a single threaded model such as node.js
*
* @param {unknown} sessionId unknown
*/
RemoteObjectTemplate.setSession = function setSession(sessionId) {
this.currentSession = sessionId;
};
/**
* Enable/Disable sending of messages and optionally provide a new callback
*
* @param {unknown} value boolean to enable/disable
* @param {unknown} messageCallback optional call back function
* @param {unknown} sessionId optional session id
*/
RemoteObjectTemplate.enableSendMessage = function enableSendMessage(value, messageCallback, sessionId) {
const session = this._getSession(sessionId);
session.sendMessageEnabled = value;
if (messageCallback) {
session.sendMessage = messageCallback;
}
};
/**
* Subscribe to changes and optionally establish subscription as the
* sole recipient of remote call messages. Change tracking is then managed
* by the functions that follow.
*
* @param {unknown} role unknown
* @param {unknown} sendMessage and optional call back for sending messages
*
* @returns {*} unknown
*/
RemoteObjectTemplate.subscribe = function subscribe(role) {
const subscriptionId = this._getSession().nextSubscriptionId++;
this._getSession().subscriptions[subscriptionId] = {
role: role,
log: {
array: {},
change: {},
arrayDirty: {}
}
};
return subscriptionId;
};
/**
* Process a remote call message that was created and passed to the sendMessage callback
*
* @param {unknown} remoteCall - key/value set containing the remote call details and pending sync chnages
* @param {unknown} subscriptionId - unknown
* @param {unknown} restoreSessionCallback - unknown
*
* @returns {unknown} unknown
*/
RemoteObjectTemplate.processMessage = function processMessage(remoteCall, subscriptionId, restoreSessionCallback) {
if (!remoteCall) {
return;
}
let callContext;
let hadChanges = 0;
const session = this._getSession();
const remoteCallId = remoteCall.remoteCallId;
switch (remoteCall.type) {
case 'ping':
this.logger.info({
component: 'semotus',
module: 'processMessage',
activity: 'ping'
});
session.sendMessage({ type: 'pinged', sync: true, value: null, name: null, changes: null });
break;
case 'sync':
this.logger.info({ component: 'semotus', module: 'processMessage', activity: 'sync' });
// Apply any pending changes passed along as part of the call and then either
// Call the method, sending back the result in a response message
// or return an error response so the caller will roll back
if (!this._applyChanges(JSON.parse(remoteCall.changes), this.role == 'client', subscriptionId)) {
this.logger.error(
{
component: 'semotus',
module: 'processMessage',
activity: 'syncError'
},
'Could not apply changes on sync message'
);
this._convertArrayReferencesToChanges();
this._deleteChanges();
this._processQueue();
}
break;
case 'call':
if (this.memSession && this.memSession.semotus) {
if (!this.memSession.semotus.callStartTime) {
this.memSession.semotus.callStartTime = new Date().getTime();
} else {
//TODO: Why is this not an else if clause?
if (this.memSession.semotus.callStartTime + this.maxCallTime > new Date().getTime()) {
Q.delay(5000).then(
function a() {
this.logger.warn(
{
component: 'semotus',
module: 'processMessage',
activity: 'blockingCall',
data: {
call: remoteCall.name,
sequence: remoteCall.sequence
}
},
remoteCall.name
);
session.sendMessage({
type: 'response',
sync: false,
changes: '',
remoteCallId: remoteCallId
});
this._deleteChanges();
this._processQueue();
}.bind(this)
);
break;
}
}
}
callContext = { retries: 0, startTime: new Date() };
return processCall.call(this);
case 'response':
case 'error':
let doProcessQueue = true;
this.logger.info({
component: 'semotus',
module: 'processMessage',
activity: remoteCall.type,
data: { call: remoteCall.name, sequence: remoteCall.sequence }
});
// If we are out of sync queue up a set Root if on server. This could occur
// if a session is restored but their are pending calls
if (!session.pendingRemoteCalls[remoteCallId]) {
this.logger.error(
{
component: 'semotus',
module: 'processMessage',
activity: remoteCall.type,
data: { call: remoteCall.name, sequence: remoteCall.sequence }
},
'No remote call pending'
);
} else {
if (typeof remoteCall.sync !== 'undefined') {
if (remoteCall.sync) {
if (session.pendingRemoteCalls[remoteCallId].deferred.resolve) {
hadChanges = this._applyChanges(JSON.parse(remoteCall.changes), true, subscriptionId);
if (remoteCall.type == 'error') {
session.pendingRemoteCalls[remoteCallId].deferred.reject(remoteCall.value);
} else {
session.pendingRemoteCalls[remoteCallId].deferred.resolve(
this._fromTransport(JSON.parse(remoteCall.value))
);
}
}
} else {
this._rollbackChanges();
session.pendingRemoteCalls[remoteCallId].deferred.reject({
code: 'internal_error_rollback',
text: 'An internal error occured'
});
if (this.role == 'client') {
// client.js in amorphic will take care of this
doProcessQueue = false;
}
}
}
delete session.pendingRemoteCalls[remoteCallId];
}
if (doProcessQueue) {
this._processQueue();
}
return hadChanges == 2;
}
function logTime() {
return new Date().getTime() - callContext.startTime.getTime();
}
/**
* We process the call the remote method in stages starting by letting the controller examine the
* changes (preCallHook) and giving it a chance to refresh data if it needs to. Then we apply any
* changes in the messages and give the object owning the method a chance to validate that the
* call is valid and take care of any authorization concerns. Finally we let the controller perform
* any post-call processing such as commiting data and then we deal with a failure or success.
*
* @param {unknown} forceupdate unknown
*
* @returns {unknown} unknown
*/
function processCall(forceupdate) {
return Q(forceupdate)
.then(preCallHook.bind(this))
.then(applyChangesAndValidateCall.bind(this))
.then(customValidation.bind(this))
.then(callIfValid.bind(this))
.then(postCallHook.bind(this))
.then(postCallSuccess.bind(this))
.fail(postCallFailure.bind(this));
}
/**
* If there is an update conflict we want to retry after restoring the session
*
* @returns {*} unknown
*/
function retryCall() {
if (restoreSessionCallback) {
restoreSessionCallback();
}
return processCall.call(this, true);
}
/**
* Determine what objects changed and pass this to the preServerCall method on the controller
*
* @param {unknown} forceupdate unknown
*
* @returns {unknown} unknown
*/
function preCallHook(forceupdate) {
this.logger.info(
{
component: 'semotus',
module: 'processCall',
activity: 'preServerCall',
data: {
call: remoteCall.name,
sequence: remoteCall.sequence
}
},
remoteCall.name
);
if (this.controller && this.controller['preServerCall']) {
let changes = {};
for (var objId in JSON.parse(remoteCall.changes)) {
changes[this.__dictionary__[objId.replace(/[^-]*-/, '').replace(/-.*/, '')].__name__] = true;
}
return this.controller['preServerCall'].call(
this.controller,
remoteCall.changes.length > 2,
changes,
callContext,
forceupdate
);
} else {
return true;
}
}
/**
* Apply changes in the message and then validate the call. Throw "Sync Error" if changes can't be applied
*
* @returns {unknown} unknown
*/
function applyChangesAndValidateCall() {
this.logger.info(
{
component: 'semotus',
module: 'processCall',
activity: 'applyChangesAndValidateCall',
data: {
call: remoteCall.name,
sequence: remoteCall.sequence,
remoteCallId: remoteCall.id
}
},
remoteCall.name
);
let changes = JSON.parse(remoteCall.changes);
if (this._applyChanges(changes, this.role === 'client', subscriptionId, callContext)) {
const obj = session.objects[remoteCall.id];
if (!obj) {
throw new Error('Cannot find object for remote call ' + remoteCall.id);
}
// check to see if this function is supposed to be called directly from client
if (obj.__proto__[remoteCall.name].__on__ !== 'server') {
throw 'Invalid Function Call; not an API function';
}
if (this.role === 'server' && obj['validateServerCall']) {
return obj['validateServerCall'].call(obj, remoteCall.name, callContext);
}
return true;
} else {
throw 'Sync Error';
}
}
/**
* Apply function specific custom serverSide validation functions
*
* @param {boolean} isValid - Result of previous validation step (applyChangesAndValidateCall)
* @returns {boolean} True if passed function
*/
function customValidation(isValid) {
let loggerObject = {
component: 'semotus',
module: 'processCall',
activity: 'customValidation',
data: {
call: remoteCall.name,
sequence: remoteCall.sequence,
remoteCallId: remoteCall.id
}
};
let remoteObject = session.objects[remoteCall.id];
this.logger.info(loggerObject, remoteCall.name);
if (!isValid) {
return false;
} else if (this.role === 'server' && remoteObject[remoteCall.name].serverValidation) {
let args = this._extractArguments(remoteCall);
args.unshift(remoteObject);
return remoteObject[remoteCall.name].serverValidation.apply(null, args);
} else {
return true;
}
}
/**
* If the changes could be applied and the validation was successful call the method
*
* @param {boolean} isValid - takes a flag if the call is valid or not, if it is then we proceed normally,
* otherwise, we throw an error and stop execution
*
* @returns {unknown} unknown
*/
function callIfValid(isValid) {
let loggerObject = {
component: 'semotus',
module: 'processCall',
activity: 'callIfValid',
data: {
call: remoteCall.name,
sequence: remoteCall.sequence,
remoteCallId: remoteCall.id
}
};
this.logger.info(loggerObject, remoteCall.name);
let obj = session.objects[remoteCall.id];
if (!obj[remoteCall.name]) {
throw new Error(remoteCall.name + ' function does not exist.');
}
if (!isValid && remoteCall && remoteCall.name) {
throw new Error(remoteCall.name + ' refused');
}
let args = this._extractArguments(remoteCall);
return obj[remoteCall.name].apply(obj, args);
}
/**
* Let the controller know that the method was completed and give it a chance to commit changes
*
* @param {unknown} returnValue unknown
*
* @returns {unknown} unknown
*/
function postCallHook(returnValue) {
if (this.controller && this.controller['postServerCall']) {
return Q(
this.controller['postServerCall'].call(
this.controller,
remoteCall.changes.length > 2,
callContext,
this.changeString
)
).then(function u() {
return returnValue;
});
} else {
return returnValue;
}
}
/**
* Package up any changes resulting from the execution and send them back in the message, clearing
* our change queue to accumulate more changes for the next call
*
* @param {unknown} ret unknown
*/
function postCallSuccess(ret) {
this.logger.info(
{
component: 'semotus',
module: 'processCall',
activity: 'postCall.success',
data: {
call: remoteCall.name,
callTime: logTime(),
sequence: remoteCall.sequence
}
},
remoteCall.name
);
packageChanges.call(this, {
type: 'response',
sync: true,
value: JSON.stringify(this._toTransport(ret)),
name: remoteCall.name,
remoteCallId: remoteCallId
});
}
/**
* Helper function to log amorphic errors.
* @param {*} logger
* @param {*} activity
* @param {*} message
* @param {*} logType
* @param {*} logString
*/
function postCallErrorLog(logger, activity, message, logType, logString) {
let logBody = {
component: 'semotus',
module: 'processCall.failure',
data: {
call: remoteCall.name,
callTime: logTime(),
sequence: remoteCall.sequence
}
};
logBody.activity = activity;
if (logger.data) {
logBody.data.message = message;
}
logger[logType](logBody, logString);
}
/**
* Helper function to identify if there's a postServerErrorHandler callback on the base controller
* If there is, we execute the handler, and if we catch an error in the handler, we propogate it up to the logger.
* @param {*} controller
*/
function resolveErrorHandler(logger, controller, type, remoteCall, remoteCallId, callContext, changeString) {
if (controller && controller['postServerErrorHandler']) {
let errorType = type;
let functionName = remoteCall.name;
let obj = undefined;
if (session.objects[remoteCall.id]) {
obj = session.objects[remoteCall.id];
}
let logBody = {
component: 'semotus',
module: 'processCall.failure',
activity: 'postCall.resolveErrorHandler',
data: {
call: remoteCall.name
}
};
return Promise.resolve()
.then(
controller['postServerErrorHandler'].bind(
controller,
errorType,
remoteCallId,
obj,
functionName,
callContext,
changeString
)
)
.then(
function() {
// no error on error handler callback
},
function(error) {
if (error.message) {
logBody.data.message = error.message;
logger.error(error.message);
} else {
logBody.data.message = JSON.stringify(error);
}
logger.error(logBody, 'User defined postServerErrorHandler threw an error');
}
);
} else {
return Promise.resolve();
}
}
/**
* Handle errors by returning an apropriate message. In all cases changes sent back though they
*
* @param {unknown} err unknown
*
* @returns {unknown} A Promise
*/
function postCallFailure(err) {
let logString = '';
let packageChangesPayload = {};
let updateConflictRetry = false;
if (err === 'Sync Error') {
postCallErrorLog(this.logger, 'postCall.syncError', undefined, 'error', remoteCall.name);
packageChangesPayload = {
type: 'response',
sync: false,
changes: ''
};
} else if (err.message == 'Update Conflict') {
// Not this may be caught in the trasport (e.g. Amorphic) and retried)
// increment callContext.retries after checking if < 3. Should retry 3 times.
if (callContext.retries++ < 3) {
postCallErrorLog(this.logger, 'postCall.updateConflict', undefined, 'warn', remoteCall.name);
updateConflictRetry = true;
// The following assignment is only used for the error handler
packageChangesPayload = {
type: 'retry'
};
} else {
postCallErrorLog(this.logger, 'postCall.updateConflict', undefined, 'error', remoteCall.name);
packageChangesPayload = {
type: 'retry',
sync: false
};
}
} else {
if (!(err instanceof Error)) {
postCallErrorLog(this.logger, 'postCall.error', JSON.stringify(err), 'info', remoteCall.name);
} else {
if (err.stack) {
logString = 'Exception in ' + remoteCall.name + ' - ' + err.message + (' ' + err.stack);
} else {
logString = 'Exception in ' + remoteCall.name + ' - ' + err.message;
}
postCallErrorLog(this.logger, 'postCall.exception', err.message, 'error', logString);
}
packageChangesPayload = {
type: 'error',
sync: true,
value: getError.call(this, err),
name: remoteCall.name
};
}
Object.assign(packageChangesPayload, { remoteCallId: remoteCallId });
const errorHandlerPromise = resolveErrorHandler(
this.logger,
this.controller,
packageChangesPayload.type,
remoteCall,
remoteCallId,
callContext,
this.changeString
);
if (updateConflictRetry) {
return errorHandlerPromise
.then(Q.delay.bind(null, callContext.retries * 1000))
.then(retryCall.bind(this));
} else {
return errorHandlerPromise.then(packageChanges.bind(this, packageChangesPayload));
}
}
/**
* Helper function to
*
* Distinquish between an actual error (will throw an Error object) and a string that the application may
* throw which is to get piped back to the caller. For an actual error we want to log the stack trace
*
* @param {unknown} err unknown
*
* @returns {*} unknown
*/
function getError(err) {
if (err instanceof Error) {
return { code: 'internal_error', text: 'An internal error occurred' };
} else {
if (typeof err === 'string') {
return { message: err };
} else {
return err;
}
}
}
/**
* Deal with changes going back to the caller
*
* @param {unknown} message unknown
*/
function packageChanges(message) {
this._convertArrayReferencesToChanges();
message.changes = JSON.stringify(this.getChanges());
if (this.memSession && this.memSession.semotus && this.memSession.semotus.callStartTime) {
this.memSession.semotus.callStartTime = 0;
}
session.sendMessage(message);
this._deleteChanges();
this._processQueue();
}
};
/**
* Create a serialized session for amorphic recreating the session object
* map along the way to release references to objects no longer in
*
* @returns {*} unknown
*/
RemoteObjectTemplate.serializeAndGarbageCollect = function serializeAndGarbageCollect() {
const session = this._getSession();
const idMap = {};
let objectKey = '';
let propKey = '';
const itemsBefore = count(session.objects);
const serial = serialize.call(this, this.controller);
session.objects = idMap;
const itemsAfter = count(idMap);
this.logger.debug({
component: 'semotus',
module: 'serializeAndGarbageCollect',
activity: 'post',
data: { objectsFreed: itemsAfter - itemsBefore, sessionSizeKB: Math.floor(serial.length / 1000) }
});
return serial;
function serialize(obj) {
try {
return JSON.stringify(obj, function y(key, value) {
if (key === '__objectTemplate__' || key === 'amorphic') {
return null;
}
if (value && value.__template__ && value.__id__) {
objectKey = key;
if (idMap[value.__id__]) {
value = { __id__: value.__id__.toString() };
} else {
idMap[value.__id__.toString()] = value;
}
} else {
propKey = key;
}
return value;
});
} catch (e) {
this.logger.error(
{
component: 'semotus',
module: 'serializeAndGarbageCollect',
activity: 'post',
data: { last_object_ref: objectKey, last_prop_ref: propKey }
},
'Error serializing session ' + e.message + e.stack
);
return null;
}
}
function count(idMap) {
let ix = 0;
_.map(idMap, function w() {
ix++;
});
return ix;
}
};
/**
* Pick up next message (alternate interface to using a callback)
*
* @param {unknown} sessionId unknown
* @param {unknown} forceMessage unknown
*
* @returns {*} the message or null
*/
RemoteObjectTemplate.getMessage = function getMessage(sessionId, forceMessage) {
const session = this._getSession(sessionId);
let message = session.remoteCalls.shift();
if (message) {
const remoteCallId = session.nextPendingRemoteCallId++;
message.remoteCallId = remoteCallId;
session.pendingRemoteCalls[remoteCallId] = message;
} else if (forceMessage) {
message = {
type: 'sync',
sync: true,
value: null,
name: null,