-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathComponentCommunications.js
1401 lines (1173 loc) · 57.3 KB
/
ComponentCommunications.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
/**
* This file defines the bottom layer of the component stack: The communication layer.
*/
"use strict";
var url = require('url');
var ComponentDef = require('./ComponentDef');
var process = require('process');
var _ = require('lodash');
/**
* This interface sets the rules and structure for transport layer implementations.
*
* @interface
*/
var ComponentTransportImpl = {
ImplName: "<short name describing implementation type>",
Host: ComponentDef.defHost(function(SharedTools, Shared, SharedContext) { return {
initHost: function(app, cfg) {},
bootstrap: function(app, cfg) {},
Private: {
}
}}),
/**
* This code will only execute on the client side of a component.
*/
Client: ComponentDef.defClient(function(Tools, Instance, Context) { return {
/**
* This client-side function tells the host to execute the given command of the given component.
*/
sendRequestToHost: function(clientMsg) {},
Public: {
refresh: function() {},
redirect: function(newLocation, inOldContext) {}
}
}})
};
// ####################################################################################################################################
// ComponentCommunications
/**
* This is the NoGap communication layer and manager of actual transport implementation.
*/
var ComponentCommunications = ComponentDef.lib({
Base: ComponentDef.defBase(function(SharedTools, Shared, SharedContext) { return {
/**
* PacketBuffer is used to keep track of all data while a
* request or response is being compiled.
* @see http://jsfiddle.net/h5Luk/15/
*/
PacketBuffer: squishy.createClass(function() {
this._resetBuffer();
}, {
// methods
/**
* Buffers the given command request.
* Will be sent at the end of the current (or next) client request.
* @return Index of command in command buffer
*/
bufferCommand: function(compNameOrCommand, cmdName, args) {
var command;
if (_.isString(compNameOrCommand)) {
// arguments are command content
command = {
comp: compNameOrCommand,
cmd: cmdName,
args: args
};
}
else {
// first argument is complete command
command = compNameOrCommand;
}
// if buffering, just keep accumulating and send commands back later
this._buffer.commands.push(command);
// return packet index
return this._buffer.commands.length-1;
},
/**
* Add an array of commands to the buffer.
*/
bufferClientCommands: function(commands) {
this._buffer.commands.push.apply(this._buffer.commands, commands);
},
/**
* Compile request or response data.
* Includes all buffered commands, as well as given commandExecutionResults and errors.
* Resets the current command buffer.
*/
compilePacket: function(commandExecutionResults) {
var packetData = this._buffer;
packetData.commandExecutionResults = commandExecutionResults;
this._resetBuffer();
return packetData;
},
_resetBuffer: function() {
this._buffer = {
commands: [],
commandExecutionResults: null
};
},
}),
__ctor: function() {
console.assert(this.PacketBuffer);
},
/**
* Sets the charset for all transport operations.
* The default transport implementation bootstraps NoGap to the browser and
* uses this charset to populate the corresponding META tag.
*/
setCharset: function(charset) {
this.charset = charset;
},
_getComponentTransportImplName: function(name) {
//return 'ComponentTransportImpl_' + name;
return '_ComponentTransportImpl';
},
/**
* The current transport layer implementation
*/
getComponentTransportImpl: function() {
var transportImpl = Shared.Libs[this._getComponentTransportImplName()];
console.assert(transportImpl, 'Could not lookup the Host endpoint of the transport layer implementation.');
return transportImpl;
},
/**
* Creates a response packet, containing a single command
*/
createSingleCommandPacket: function(compName, cmdName, args) {
return {
commands: [{
comp: compName,
cmd: cmdName,
args: args
}]
};
},
Private: {
/**
* This user's connection implementation state object
*/
getDefaultConnection: function() {
return this.Instance.Libs[this.ComponentCommunications._getComponentTransportImplName()];
},
/**
* Get an identifier for the current user.
* For network transport layers (such as HTTP or WebSocket), this is usually the IP address.
* For WebWorkers and other kinds of environments that can be a custom name, assigned during
* initialization.
*/
getUserIdentifier: function() {
return this.getDefaultConnection().getUserIdentifier();
},
refresh: function() {
var connection = this.getDefaultConnection();
if (connection.client) {
connection.client.refresh();
}
else {
connection.refresh();
}
},
redirect: function(newLocation, inOldContext) {
var connection = this.getDefaultConnection();
if (connection.client) {
connection.client.redirect(newLocation, inOldContext);
}
else {
connection.redirect(newLocation, inOldContext);
}
}
}
}}),
Host: ComponentDef.defHost(function(SharedTools, Shared, SharedContext) {
var onNewConnection = function(conn) {
// do nothing for now
};
var currentVersionToken;
var Promise;
var crypto;
return {
implementations: {},
__ctor: function() {
Promise = Shared.Libs.ComponentDef.Promise;
crypto = require('crypto');
this.events = {
connectionError: squishy.createEvent(this)
};
},
generateRandomToken: function(len, symbols) {
len = len || this.options.defaultLen;
symbols = symbols || '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var nSymbols = symbols.length;
var buf = crypto.randomBytes(len);
var res = '';
// only get `len` characters
for (var i = 0; i < len; ++i) {
var nextByte = buf[i];
res += symbols[nextByte%nSymbols]; // map bytes to our given set of symbols
}
return res;
},
/**
* Register a new endpoint implementation (e.g. using http-get, http-post, websockets, webworkers, or anything else...).
*/
registerImplType: function(implType) {
squishy.assert(typeof(implType) === 'object',
'ComponentTransportImpl definition must implement the `ComponentTransportImpl` interface.');
squishy.assert(implType.ImplName, 'Unnamed ComponentTransportImpl is illegal. Make sure to set the `ImplName` property.');
// store it in implementations
this.implementations[implType.ImplName] = implType;
},
/**
* Initializes the host endpoint for the given hostComponents and registers the client endpoint.
*/
setupCommunications: function(app, cfg) {
// get implementation (HttpPost is the default)
var implName = cfg.name || 'HttpPost';
currentVersionToken = cfg.currentVersionToken || this.generateRandomToken(32);
squishy.assert(this.implementations.hasOwnProperty(implName),
'ComponentTransportImpl of type "' + implName +
'" does not exist. Available types are: ' + Object.keys(this.implementations));
var implType = this.implementations[implName];
// register implementation as lib (so we also get access to it on the client side)
implType.Name = this._getComponentTransportImplName();
ComponentDef.lib(implType);
},
/**
* This should be called if there was any connection error.
*/
reportConnectionError: function(req, res, err) {
this.events.connectionError.fire(req, res, err);
},
getClientVersion: function(requestMetadata) {
return requestMetadata['x-nogap-v'];
},
/**
* An instance that has already been established sent a request.
* Check if version matches.
*/
isCurrentVersion: function(requestMetadata) {
return this.getClientVersion(requestMetadata) === currentVersionToken;
},
Private: {
/**
* Currently pending/executing Promise chain
*/
pendingResponsePromise: null,
hostResponse: null,
__ctor: function() {
this.hostResponse = new this.Shared.PacketBuffer();
this.pendingResponsePromise = Promise.resolve();
},
onNewClient: function() {
// a bit of security
this.updateClientIdentity(true, true);
},
/**
* CSRF prevention
* @see https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#General_Recommendation:_Synchronizer_Token_Pattern
*/
updateClientIdentity: function(dontSend, dontForce) {
if (!dontForce || !this.Context.session._identifierName) {
this.Context.session._identifierName = 'X-Nogap-Identity-' + this.Shared.generateRandomToken(16);
this.Context.session._identifierToken = this.Shared.generateRandomToken(32);
if (!dontSend) {
this.client.updateClientIdentityPublic({
identifierName: this.Context.session._identifierName,
identifierToken: this.Context.session._identifierToken,
v: currentVersionToken
});
}
}
},
getClientCtorArguments: function() {
return [{
identifierName: this.Context.session._identifierName,
identifierToken: this.Context.session._identifierToken,
v: currentVersionToken
}];
},
// ##############################################################################################################
// Handle requests
/**
* Whether this instance is currently running/has pending promises
*/
isExecutingRequest: function() {
return this.pendingResponsePromise.isPending();
},
/**
* CSRF prevention
* @see https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#General_Recommendation:_Synchronizer_Token_Pattern
*/
verifyRPCRequestMetadata: function(requestMetadata) {
// check CSRF token
if (!this.Context.session._identifierName || !this.Context.session._identifierToken) {
return Promise.reject(makeError('error.internal',
'Session client identifier was not properly initialized during client request'));
}
var sentToken = requestMetadata[this.Context.session._identifierName.toLowerCase()];
//console.error(this.Context.session._identifierName + ': ' + requestMetadata[this.Context.session._identifierName]);
if (sentToken === this.Context.session._identifierToken) {
return Promise.resolve();
}
return Promise.reject('Unverified client request (hasToken: ' + !!sentToken + ')');
},
/**
* Used by endpoint implementations to execute and/or put commands.
* @return A promise that will return the Host's response to the given clientMsg.
*/
handleClientRPCMsg: function(clientMsg) {
return this.executeCommandRequest(clientMsg.commands);
},
/**
* Used by endpoint implementations to execute and/or put commands.
* @return A promise that will return a (potentially empty) return value for each of the requested commands.
*/
executeCommandRequest: function(commands) {
// start (or enqueue) command request
var next = function() {
return this.Instance.Libs.CommandProxy.executeClientCommands(commands);
}.bind(this);
return this.executeInOrderWithReturnValue(next);
},
/**
* Execute the given function or promise once all pending requests have been served.
* Adds resulting client code to packet being compiled.
* Assumes that the code has no return value(s) to be sent to client.
* Given an HTTP implementation, this allows to buffer multiple sets of command executions.
* @return Promise for compiled hostResponse packet to be sent to client.
*/
executeInOrder: function(code) {
if (!this.pendingResponsePromise.isPending()) {
// queue is empty -> Start right away
// create new chain, so we don't keep all previous results until the end of time
this.pendingResponsePromise = Promise.resolve();
}
// if there is still other stuff pending -> Wait until it's finished
this.pendingResponsePromise = this.pendingResponsePromise
.then(code);
return this.pendingResponsePromise;
},
/**
* Execute the given function or promise once all pending requests have been served.
* @return Promise for final hostResponse packet to be sent to client.
*/
executeInOrderWithReturnValue: function(code) {
if (!this.pendingResponsePromise.isPending()) {
// queue is empty -> Start right away
// create new chain, so we don't keep all previous results until the end of time
this.pendingResponsePromise = Promise.resolve();
}
// if there is still other stuff pending -> Wait until it's finished
this.pendingResponsePromise = this.pendingResponsePromise
.then(code);
return this.pendingResponsePromise
// return client response, including commandExecutionResults
.then(this.hostResponse.compilePacket.bind(this.hostResponse));
},
/**
* Execute a piece of user code, wrapped in safety measures.
* Returns a promise, yielding the serialized result of the code execution.
*/
executeUserCodeAndSerializeResult: function(code) {
return Promise.resolve()
.bind(this)
.then(code)
.then(this.serializeRPCReturnValue.bind(this))
.catch(this.serializeRPCError.bind(this));
},
serializeRPCReturnValue: function(returnValue) {
// wrap return value
return {
value: returnValue,
err: null
};
},
serializeRPCError: function(err) {
// wrap error
this.Tools.handleError(err);
var isException = !!(err && err.stack);
return {
value: null,
// only send back error message if error has no stack (i.e. it was not raised locally)
err: isException && 'error.internal' || err
};
},
/**
* Return and reset current hostResponse buffer.
*/
compileHostResponse: function(returnValues) {
return this.hostResponse.compilePacket(returnValues);
}
// /**
// * Skip the queue and run given code right away, while buffering
// * all resulting commands to be sent back to client.
// */
// executeCommandRaisingCodeNow: function(commandRaisingCode) {
// // override response buffer
// var originalBuffer = this.hostResponse;
// var newBuffer = this.hostResponse = new PacketBuffer();
// return Promise.resolve(commandRaisingCode)
// .bind(this)
// .then(function(commandExecutionResults) {
// // reset buffer
// this.hostResponse = originalBuffer;
// // give back response data to be sent to client
// return newBuffer.compilePacket(commandExecutionResults);
// });
// },
}
};
}),
Client: ComponentDef.defClient(function(Tools, Instance, Context) {
var Promise; // Promise library
return {
_requestPromise: null,
_requestPacket: null,
__ctor: function(clientIdentity) {
this.updateClientIdentity(clientIdentity);
Promise = Instance.Libs.ComponentDef.Promise;
this._requestPacket = new this.PacketBuffer();
this.events = {
refreshRequested: squishy.createEvent()
};
},
updateClientIdentity: function(clientIdentity) {
this._identity = clientIdentity;
},
initClient: function() {
// add send method to Tools
Tools.sendRequestToHost = function() {
var connection = this.getDefaultConnection();
var args = arguments;
return Promise.resolve()
.bind(this)
// first, send custom request to host
.then(function() {
return connection.sendRequestToHost.apply(connection, args);
})
// then handle response
.then(this.handleHostResponse)
// and interpret results
.then(function(results) {
return this.interpretHostResult(results);
});
}.bind(this);
},
_getNogapComponentIds: function() {
var componentIds = [];
Instance.forEach(function(component) {
componentIds.push(component.Def.ComponentId);
}.bind(this));
return componentIds;
},
prepareRequestMetadata: function(metadata) {
if (!this._identity.identifierName || !this._identity.identifierToken) {
throw new Error('error.internal: session client identifier was not initialized before client request');
}
metadata[this._identity.identifierName] = this._identity.identifierToken;
metadata['x-nogap-v'] = this._identity.v;
metadata['x-nogap-components'] = JSON.stringify(this._getNogapComponentIds());
},
/**
* Add command to host, and send out very soon as part of a (small) batch.
*/
sendCommandToHost: function(compName, cmdName, args) {
// add command to buffer
var returnIndex = this._requestPacket.bufferCommand(compName, cmdName, args);
// do not send out every command on its own;
// instead, always wait a minimal amount of time and then send
// a batch of all commands together
if (!this._requestPromise) {
this._requestPromise = Promise.delay(1)
.bind(this)
.then(this._sendClientRequestBufferToHost);
}
// send the corresponding return value back to caller
return this._requestPromise
.then(function(commandExecutionResults) {
var result = commandExecutionResults && commandExecutionResults[returnIndex];
return this.interpretHostResult(result);
}.bind(this));
},
/**
* Actually send Client request to Host.
* Compile response packet for client; includes all buffered commands.
* Resets the current commandBuffer.
*/
_sendClientRequestBufferToHost: function() {
this._requestPromise = null; // reset promise
// compile and send out data
var clientMsg = this._requestPacket.compilePacket();
return this.getDefaultConnection().sendRequestToHost(clientMsg)
// once received, handle reply sent back by Host
.then(this.handleHostResponse);
},
interpretHostResult: function(result) {
if (!result) {
// nothing to return
return null;
}
else if (!result.err) {
// return result value
return result.value;
}
else {
// reject
return Promise.reject(result.err);
}
},
/**
* Host sent stuff. Run commands and return the set of returnValues.
*/
handleHostResponse: function(hostReply) {
if (hostReply.commands) {
// execute commands sent back by Host
Instance.Libs.CommandProxy.executeHostCommands(hostReply.commands);
}
// send return values sent by host back to callers
return hostReply && hostReply.commandExecutionResults;
},
hasRefreshBeenRequested: function() {
return this._refreshRequested;
},
Public: {
updateClientIdentityPublic: function(clientIdentity) {
this.updateClientIdentity(clientIdentity);
},
/**
* Ask user if they want to refresh
*/
requestRefresh: function() {
this._refreshRequested = true;
this.events.refreshRequested.fire()
.bind(this)
.then(function() {
this.refresh();
})
.catch(function() {
// do nothing upon rejection
});
}
}
};
})
});
// ####################################################################################################################################
// HttpPost endpoint implementation
/**
* Uses express + Ajax for transporting POST all NoGap data and requests.
*/
var HttpPostImpl = {
ImplName: "HttpPost",
Base: ComponentDef.defBase(function(SharedTools, Shared, SharedContext) {
return {
/**
* Default serializer implementation, uses JSON.
*/
Serializer: {
/**
* Convert an object into a string.
* TODO: Consider using ArrayBuffer instead.
*/
serialize: function(obj) {
return squishy.objToString(obj, true);
},
/**
* Reconstruct object from string.
* TODO: Consider using ArrayBuffer instead.
*/
deserialize: function(objString, evaluateWithCode) {
if (evaluateWithCode) {
return eval('(' + objString + ')');
}
return JSON.parse(objString);
}
},
/**
* Asset handlers are given to the Assets library for initializing assets.
*/
assetHandlers: {
/**
* Functions to fix asset filenames of given types.
*/
autoIncludeResolvers: {
js: function(fname) {
if (!fname.endsWith('.js')) fname += '.js';
return fname;
},
css: function(fname) {
if (!fname.endsWith('.css')) fname += '.css';
return fname;
}
},
/**
* Functions to generate code for including external file assets.
* Also need to fix tag brackets because this string will be part of a script
* that actually writes the asset code to the HTML document.
*
* @see http://stackoverflow.com/a/236106/2228771
*/
autoIncludeCodeFactories: {
js: function(fname) {
return '\x3Cscript type="text/javascript" src="' + fname + '">\x3C/script>';
},
css: function(fname) {
return '\x3Clink href="' + fname + '" rel="stylesheet" type="text/css">\x3C/link>';
},
/**
* Unsupported format: Provide the include string as-is.
*/
raw: function(fname) {
return fname;
}
}
},
Private: {
getUserIdentifier: function() {
if (SharedContext.IsHost) {
// host
var req = this._lastReq;
return this.Shared.getIpAddress(req);
}
else {
// Not Yet Implemented on Client
return null;
}
},
getCurrentConnectionState: function() {
return this._currentConnectionState;
}
}
};
}),
Host: ComponentDef.defHost(function(SharedTools, Shared, SharedContext) {
var express;
var ExpressRouters = {};
var serializer;
return {
__ctor: function() {
express = require('express');
serializer = this.Serializer;
// add a tool to add custom route handler for other HTTP requests
SharedTools.ExpressRouters = ExpressRouters = {
// handle routes before NoGap
before: express.Router(),
// handle routes after NoGap
after: express.Router()
};
},
initHost: function(app, cfg) {
// set charset
this.charset = cfg.charset;
// pre-build <script> & <link> includes
this.includeCode = Shared.Libs.ComponentAssets.getAutoIncludeAssets(this.assetHandlers);
},
/**
* After all components have been initialized,
* this will be called by ComponentBootstrap to register the NoGap HTTP middleware.
*/
setupCommunications: function(app, cfg) {
// Order of request handlers:
// 1. patchConnectionState
// 2. ExpressRouters.before
// 3. Bootstrap handler
// 4. RPC request handler
// 5. ExpressRouters.after
squishy.assert(app.use && app.get && app.post, 'Invalid argument for initHost: `app` is not an express or express router object. ' +
'Make sure to pass an express application object to `ComponentLoader.start` when using ' +
'NoGap\'s default HttpPost implementation.');
// add custom methods to request
this._registerConnectionPatcher(app, cfg);
// register Instance initialization handler for bootstrap requests
this._registerBootstrapRequestInitializer(app, cfg);
// register Instance initialization handler for RPC requests
this._registerRPCRequestInitializer(app, cfg);
// handle "before" routes
app.use(ExpressRouters.before);
// handle bootstrap requests
this._registerBootstrapRequestHandler(app, cfg);
// handle RPC requests
this._registerRPCRequestHandler(app, cfg);
// handle "after" routes
app.use(ExpressRouters.after);
},
getIpAddress: function(req) {
// host
var ipStr = null;
if (req) {
// try to get IP
ipStr =
(req.socket && req.socket.remoteAddress) ||
(req.connection &&
(req.connection.remoteAddress ||
(req.connection.socket && req.connection.socket.remoteAddress))) ||
req.headers['x-forwarded-for'];
}
else {
// no connection -> The call comes from inside the house (possibly via CommandPrompt)
ipStr = '<local>';
}
return ipStr;
},
_getOrCreateInstanceForSession: function(req, forceCreate) {
var session = req.session;
var sessionId = req.sessionID;
console.assert(session,
'req.session was not set. Make sure to use a session manager before the components library, when using the default Get bootstrapping method.');
console.assert(sessionId,
'req.sessionID was not set. Make sure to use a compatible session manager before the components library, when using the default Get bootstrapping method.');
// get or create Instance map
var Instance = Shared.Libs.ComponentInstance.activateSession(
session, sessionId, forceCreate);
// console.assert(Shared.Libs.ComponentInstance.activateSession(session, sessionId),
// 'Session activation failed.');
return Instance;
},
_registerConnectionPatcher: function(app, cfg) {
// patch general connection state
app.use(function _patchConnectionState(req, res, next) {
// register error handler
var onError = function(err) {
Shared.Libs.ComponentCommunications.reportConnectionError(req, res, err);
next(err);
};
req.on('error', onError);
// patch req object
req.getInstance = function() {
var Instance = req.Instance;
if (!Instance) {
Instance = req.Instance = this._getOrCreateInstanceForSession(req, false);
}
return Instance;
}.bind(this);
req.runInContext = function(_userCode) {
var Instance = req.getInstance();
if (!Instance) {
// getInstance already took care of error handling
onError(new Error('runInContext failed - Instance not initialized'));
return;
}
var userCode = function() {
return _userCode(Instance);
};
return Instance.Libs.ComponentCommunications.executeInOrderWithReturnValue(function() {
// run user code and serialize error or return value
return Instance.Libs.ComponentCommunications.executeUserCodeAndSerializeResult(userCode);
})
// then send it back
.then(function(hostResponseData) {
var connection = Instance.Libs.ComponentCommunications.getDefaultConnection();
connection.sendRPCResponseToClient(hostResponseData, res);
});
};
// run next
next();
}.bind(this));
},
_registerBootstrapRequestInitializer: function(router, cfg) {
this._registerGetHandler(router, cfg, function(req, res, next) {
req.Instance = this._getOrCreateInstanceForSession(req, true);
next();
}.bind(this));
},
_registerRPCRequestInitializer: function(router, cfg) {
// register Instance initialization handler for RPC requests
this._registerPostHandler(router, cfg, function(req, res, next) {
var requestMetadata = req.headers || {};
if (!Shared.Libs.ComponentCommunications.isCurrentVersion(requestMetadata)) {
// wrong version -> request Client refresh
var ipAddr = this.getIpAddress(req);
console.warn('[' + ipAddr + '] sent RPC request with outdated client version. Sending refresh.');
// Tell Client to refresh (assuming the client's currently running Bootstrapper implementation supports it):
var responsePacket = Shared.Libs.ComponentCommunications.createSingleCommandPacket(
'ComponentCommunications', 'requestRefresh');
this.Def.InstanceProto.sendRPCResponseToClient(responsePacket, res);
return null;
}
// first, try to get existing cached Instance
var Instance = req.Instance = this._getOrCreateInstanceForSession(req, false);
var notCached = !Instance;
if (notCached) {
// Instance not cached
console.error('reactivating instance for: ' + req.sessionID);
// create new Instance
Instance = req.Instance = this._getOrCreateInstanceForSession(req, true);
}
// verify Client integrity
var promise =
Instance.Libs.ComponentCommunications.verifyRPCRequestMetadata(requestMetadata);
if (notCached) {
// call re-initialization code in order
promise = promise.then(
Instance.Libs.ComponentCommunications.executeInOrder.bind(Instance.Libs.ComponentCommunications, function() {
// reactivate
var componentIdStr = requestMetadata['x-nogap-components'];
var componentIds;
try {
componentIds = JSON.parse(componentIdStr);
console.assert(componentIds instanceof Array);
}
catch (err) {
next('Could not parse `x-nogap-components` header: ' + componentIdStr);
return;
}
var ComponentBootstrapInstance = Instance.Libs.ComponentBootstrap;
return Instance.Libs.ComponentBootstrap.reactivateClientInstanceNow(componentIds)
.catch(ComponentBootstrapInstance.Tools.handleError
.bind(ComponentBootstrapInstance.Tools));
}));
}
// once its all done, execute next middleware layer
promise
.then(function() { next(); });
}.bind(this));
},
/**
* Register HTTP middleware to handle Client bootstrap requests (GET)
*/
_registerBootstrapRequestHandler: function(router, cfg) {
this._registerGetHandler(router, cfg, function(req, res, next) {
console.log('[' + this.getIpAddress(req) + '] Incoming client requesting `' + req.url + '`');
// handle the request
var Instance = req.getInstance();
var connection = Instance.Libs.ComponentCommunications.getDefaultConnection();
connection._currentConnectionState = res;
connection._lastReq = req;
var ComponentBootstrapInstance = Instance.Libs.ComponentBootstrap;
// bootstrap the new Instance
return connection._doBootstrapClientInstance(req, res, next)
.bind(this)
// send bootstrap code to Client and kick things of there
.then(function(codeString) {
connection._sendBootstrapRequestToClient(res, codeString);
})
// could not send out the response
.catch(ComponentBootstrapInstance.Tools.handleError
.bind(ComponentBootstrapInstance.Tools))
.finally(function() {
connection._currentConnectionState = null;
});
}.bind(this));