-
-
Notifications
You must be signed in to change notification settings - Fork 587
/
Copy pathtransit.js
1456 lines (1260 loc) · 35.3 KB
/
transit.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
/*
* moleculer
* Copyright (c) 2020 MoleculerJS (https://github.com/moleculerjs/moleculer)
* MIT Licensed
*/
"use strict";
const P = require("./packets");
const { Packet } = require("./packets");
const E = require("./errors");
const { Transform } = require("stream");
const { METRIC } = require("./metrics");
const C = require("./constants");
/**
* Transit class
*
* @class Transit
*/
class Transit {
/**
* Create an instance of Transit.
*
* @param {ServiceBroker} Broker instance
* @param {Transporter} Transporter instance
* @param {Object?} opts
*
* @memberof Transit
*/
constructor(broker, transporter, opts) {
this.broker = broker;
this.Promise = broker.Promise;
this.logger = broker.getLogger("transit");
this.nodeID = broker.nodeID;
this.metrics = broker.metrics;
this.instanceID = broker.instanceID;
this.tx = transporter;
this.opts = opts;
this.discoverer = broker.registry.discoverer;
this.errorRegenerator = broker.errorRegenerator;
this.pendingRequests = new Map();
this.pendingReqStreams = new Map();
this.pendingResStreams = new Map();
/* deprecated */
this.stat = {
packets: {
sent: {
count: 0,
bytes: 0
},
received: {
count: 0,
bytes: 0
}
}
};
this.connected = false;
this.disconnecting = false;
this.isReady = false;
const wrappedMessageHandler = (cmd, packet) => this.messageHandler(cmd, packet);
this.publish = this.broker.wrapMethod("transitPublish", this.publish, this);
this.messageHandler = this.broker.wrapMethod(
"transitMessageHandler",
this.messageHandler,
this
);
if (this.tx) {
this.tx.init(this, wrappedMessageHandler, this.afterConnect.bind(this));
this.tx.send = this.broker.wrapMethod("transporterSend", this.tx.send, this.tx);
this.tx.receive = this.broker.wrapMethod(
"transporterReceive",
this.tx.receive,
this.tx,
{ reverse: true }
);
}
this.__connectResolve = null;
this.registerMoleculerMetrics();
}
/**
* Register Moleculer Transit Core metrics.
*/
registerMoleculerMetrics() {
if (!this.broker.isMetricsEnabled()) return;
this.metrics
.register({
name: METRIC.MOLECULER_TRANSIT_READY,
type: METRIC.TYPE_GAUGE,
description: "Transit is ready"
})
.set(0);
this.metrics
.register({
name: METRIC.MOLECULER_TRANSIT_CONNECTED,
type: METRIC.TYPE_GAUGE,
description: "Transit is connected"
})
.set(0);
this.metrics.register({
name: METRIC.MOLECULER_TRANSIT_PONG_TIME,
type: METRIC.TYPE_GAUGE,
labelNames: ["targetNodeID"],
description: "Ping time"
});
this.metrics.register({
name: METRIC.MOLECULER_TRANSIT_PONG_SYSTIME_DIFF,
type: METRIC.TYPE_GAUGE,
labelNames: ["targetNodeID"],
description: "System time difference between nodes"
});
this.metrics.register({
name: METRIC.MOLECULER_TRANSIT_ORPHAN_RESPONSE_TOTAL,
type: METRIC.TYPE_COUNTER,
description: "Number of orphan responses"
});
}
/**
* It will be called after transporter connected or reconnected.
*
* @param {any} wasReconnect
* @returns {Promise}
*
* @memberof Transit
*/
afterConnect(wasReconnect) {
return this.Promise.resolve()
.then(() => {
if (wasReconnect) {
// After reconnecting, we should send a broadcast INFO packet because there may new nodes.
// In case of disabled balancer, it triggers the `makeBalancedSubscriptions` method.
return this.discoverer.sendLocalNodeInfo();
} else {
// After connecting we should subscribe to topics
return this.makeSubscriptions();
}
})
.then(() => this.discoverer.discoverAllNodes())
.delay(500) // Waiting for incoming INFO packets
.then(() => {
this.connected = true;
this.metrics.set(METRIC.MOLECULER_TRANSIT_CONNECTED, 1);
this.broker.broadcastLocal("$transporter.connected", {
wasReconnect: !!wasReconnect
});
if (this.__connectResolve) {
this.isReady = true;
this.__connectResolve();
this.__connectResolve = null;
}
return null;
});
}
/**
* Connect with transporter. If failed, try again after 5 sec.
*
* @memberof Transit
*/
connect() {
this.logger.info("Connecting to the transporter...");
return new this.Promise(resolve => {
this.__connectResolve = resolve;
const doConnect = () => {
let reconnectStarted = false;
/* istanbul ignore next */
const errorHandler = err => {
if (this.disconnecting) return;
if (reconnectStarted) return;
this.logger.warn(
"Connection is failed.",
(err && err.message) || "Unknown error"
);
this.logger.debug(err);
if (this.opts.disableReconnect) {
return;
}
reconnectStarted = true;
setTimeout(() => {
this.logger.info("Reconnecting...");
doConnect();
}, 5 * 1000);
};
/* istanbul ignore next */
this.tx.connect(errorHandler).catch(errorHandler);
};
doConnect();
});
}
/**
* Disconnect with transporter
*
* @memberof Transit
*/
disconnect() {
this.connected = false;
this.isReady = false;
this.disconnecting = true;
this.metrics.set(METRIC.MOLECULER_TRANSIT_CONNECTED, 0);
this.broker.broadcastLocal("$transporter.disconnected", { graceFul: true });
return this.Promise.resolve()
.then(() => {
return this.tx.connected && this.discoverer.localNodeDisconnected();
})
.then(() => this.tx.disconnect())
.then(() => (this.disconnecting = false));
}
/**
* Local broker is ready (all services loaded).
* Send INFO packet to all other nodes
*/
ready() {
if (this.connected) {
this.metrics.set(METRIC.MOLECULER_TRANSIT_READY, 1);
// We do nothing here because INFO packets are sent during the starting process.
return;
}
}
/**
* Send DISCONNECT to remote nodes
*
* @returns {Promise}
*
* @memberof Transit
*/
sendDisconnectPacket() {
return this.publish(new Packet(P.PACKET_DISCONNECT)).catch(
/* istanbul ignore next */ err =>
this.logger.debug("Unable to send DISCONNECT packet.", err)
);
}
/**
* Subscribe to topics for transportation
*
* @memberof Transit
*/
makeSubscriptions() {
this.subscribing = this.tx
.makeSubscriptions([
// Subscribe to broadcast events
{ cmd: P.PACKET_EVENT, nodeID: this.nodeID },
// Subscribe to requests
{ cmd: P.PACKET_REQUEST, nodeID: this.nodeID },
// Subscribe to node responses of requests
{ cmd: P.PACKET_RESPONSE, nodeID: this.nodeID },
// Discover handler
{ cmd: P.PACKET_DISCOVER },
{ cmd: P.PACKET_DISCOVER, nodeID: this.nodeID },
// NodeInfo handler
{ cmd: P.PACKET_INFO }, // Broadcasted INFO. If a new node connected
{ cmd: P.PACKET_INFO, nodeID: this.nodeID }, // Response INFO to DISCOVER packet
// Disconnect handler
{ cmd: P.PACKET_DISCONNECT },
// Heartbeat handler
{ cmd: P.PACKET_HEARTBEAT },
// Ping handler
{ cmd: P.PACKET_PING }, // Broadcasted
{ cmd: P.PACKET_PING, nodeID: this.nodeID }, // Targeted
// Pong handler
{ cmd: P.PACKET_PONG, nodeID: this.nodeID }
])
.then(() => {
this.subscribing = null;
});
return this.subscribing;
}
/**
* Message handler for incoming packets
*
* @param {Array} topic
* @param {String} msg
* @returns {Promise<boolean>} If packet is processed resolve with `true` else `false`
*
* @memberof Transit
*/
messageHandler(cmd, packet) {
try {
const payload = packet.payload;
// Check payload
if (!payload) {
/* istanbul ignore next */
throw new E.MoleculerServerError(
"Missing response payload.",
500,
"MISSING_PAYLOAD"
);
}
// Check protocol version
if (payload.ver !== this.broker.PROTOCOL_VERSION && !this.opts.disableVersionCheck) {
throw new E.ProtocolVersionMismatchError({
nodeID: payload.sender,
actual: this.broker.PROTOCOL_VERSION,
received: payload.ver
});
}
if (payload.sender === this.nodeID) {
// Detect nodeID conflict
if (cmd === P.PACKET_INFO && payload.instanceID !== this.instanceID) {
this.broker.fatal(
"ServiceBroker has detected a nodeID conflict, use unique nodeIDs. ServiceBroker stopped."
);
return this.Promise.resolve(false);
}
// Skip own packets (if only built-in balancer disabled)
if (cmd !== P.PACKET_EVENT && cmd !== P.PACKET_REQUEST && cmd !== P.PACKET_RESPONSE)
return this.Promise.resolve(false);
}
// Request
if (cmd === P.PACKET_REQUEST) {
return this.requestHandler(payload).then(() => true);
}
// Response
else if (cmd === P.PACKET_RESPONSE) {
this.responseHandler(payload);
}
// Event
else if (cmd === P.PACKET_EVENT) {
return this.eventHandler(payload);
}
// Discover
else if (cmd === P.PACKET_DISCOVER) {
this.discoverer.sendLocalNodeInfo(payload.sender);
}
// Node info
else if (cmd === P.PACKET_INFO) {
this.discoverer.processRemoteNodeInfo(payload.sender, payload);
}
// Disconnect
else if (cmd === P.PACKET_DISCONNECT) {
this.discoverer.remoteNodeDisconnected(payload.sender, false);
}
// Heartbeat
else if (cmd === P.PACKET_HEARTBEAT) {
this.discoverer.heartbeatReceived(payload.sender, payload);
}
// Ping
else if (cmd === P.PACKET_PING) {
this.sendPong(payload);
}
// Pong
else if (cmd === P.PACKET_PONG) {
this.processPong(payload);
}
return this.Promise.resolve(true);
} catch (err) {
this.logger.error(err, cmd, packet);
this.broker.broadcastLocal("$transit.error", {
error: err,
module: "transit",
type: C.FAILED_PROCESSING_PACKET
});
}
return this.Promise.resolve(false);
}
/**
* Handle incoming event
*
* @param {any} payload
* @returns {Promise<boolean>}
* @memberof Transit
*/
eventHandler(payload) {
this.logger.debug(
`Event '${payload.event}' received from '${payload.sender}' node` +
(payload.groups ? ` in '${payload.groups.join(", ")}' group(s)` : "") +
"."
);
if (this.broker.stopping) {
this.logger.warn(
`Incoming '${payload.event}' event from '${payload.sender}' node is dropped, because broker is stopped.`
);
// return false so the transporter knows this event wasn't handled.
return this.Promise.resolve(false);
}
// Create caller context
const ctx = new this.broker.ContextFactory(this.broker);
ctx.id = payload.id;
ctx.eventName = payload.event;
ctx.setParams(payload.data, this.broker.options.contextParamsCloning);
ctx.eventGroups = payload.groups;
ctx.eventType = payload.broadcast ? "broadcast" : "emit";
ctx.meta = payload.meta || {};
ctx.level = payload.level;
ctx.tracing = !!payload.tracing;
ctx.parentID = payload.parentID;
ctx.requestID = payload.requestID;
ctx.caller = payload.caller;
ctx.nodeID = payload.sender;
// ensure the eventHandler resolves true when the event was handled successfully
return this.broker.emitLocalServices(ctx).then(() => true);
}
/**
* Handle incoming request
*
* @param {Object} payload
* @returns {Promise<any>}
* @memberof Transit
*/
requestHandler(payload) {
const requestID = payload.requestID ? "with requestID '" + payload.requestID + "' " : "";
this.logger.debug(
`<= Request '${payload.action}' ${requestID}received from '${payload.sender}' node.`
);
try {
if (this.broker.stopping) {
this.logger.warn(
`Incoming '${payload.action}' ${requestID}request from '${payload.sender}' node is dropped because broker is stopped.`
);
throw new E.ServiceNotAvailableError({
action: payload.action,
nodeID: this.nodeID
});
}
let pass;
if (payload.stream !== undefined) {
pass = this._handleIncomingRequestStream(payload);
// eslint-disable-next-line security/detect-possible-timing-attacks
if (pass === null) return this.Promise.resolve();
}
const endpoint = this.broker._getLocalActionEndpoint(payload.action);
// Recreate caller context
const ctx = new this.broker.ContextFactory(this.broker);
ctx.setEndpoint(endpoint);
ctx.id = payload.id;
ctx.setParams(pass ? pass : payload.params, this.broker.options.contextParamsCloning);
ctx.parentID = payload.parentID;
ctx.requestID = payload.requestID;
ctx.caller = payload.caller;
ctx.meta = payload.meta || {};
ctx.level = payload.level;
ctx.tracing = payload.tracing;
ctx.nodeID = payload.sender;
if (payload.timeout != null) ctx.options.timeout = payload.timeout;
const p = endpoint.action.handler(ctx);
// Pointer to Context
p.ctx = ctx;
return p
.then(res => this.sendResponse(payload.sender, payload.id, ctx.meta, res, null))
.catch(err => this.sendResponse(payload.sender, payload.id, ctx.meta, null, err));
} catch (err) {
return this.sendResponse(payload.sender, payload.id, payload.meta, null, err);
}
}
/**
* Handle incoming request stream.
*
* @param {Object} payload
* @returns {Stream}
*/
_handleIncomingRequestStream(payload) {
const reqStream = this.pendingReqStreams.get(payload.id);
let pass = reqStream ? reqStream.stream : undefined;
let isNew = false;
if (!payload.stream && !pass && !payload.seq) {
// It is not a stream data
return false;
}
if (!pass) {
isNew = true;
this.logger.debug(
`<= New stream is received from '${payload.sender}'. Seq: ${payload.seq}`
);
// Create a new pass stream
pass = new Transform({
// TODO: It's incorrect because the chunks may receive in random order, so it processes an empty meta.
// Meta is filled correctly only in the 0. chunk.
objectMode: payload.meta && payload.meta["$streamObjectMode"],
transform: function (chunk, encoding, done) {
this.push(chunk);
return done();
}
});
pass.$prevSeq = -1;
pass.$pool = new Map();
this.pendingReqStreams.set(payload.id, { sender: payload.sender, stream: pass });
}
if (payload.seq > pass.$prevSeq + 1) {
// Some chunks are late. Store these chunks.
this.logger.debug(
`Put the chunk into pool (size: ${pass.$pool.size}). Seq: ${payload.seq}`
);
pass.$pool.set(payload.seq, payload);
// TODO: start timer.
// TODO: check length of pool.
// TODO: reset seq
return null;
}
// the next stream chunk received
pass.$prevSeq = payload.seq;
if (pass.$prevSeq > 0) {
if (!payload.stream) {
// Check stream error
if (payload.meta && payload.meta["$streamError"]) {
pass.emit(
"error",
this._createErrFromPayload(payload.meta["$streamError"], payload)
);
}
this.logger.debug(
`<= Stream closing is received from '${payload.sender}'. Seq: ${payload.seq}`
);
// End of stream
pass.end();
// Remove pending request stream
this.pendingReqStreams.delete(payload.id);
return null;
} else {
this.logger.debug(
`<= Stream chunk is received from '${payload.sender}'. Seq: ${payload.seq}`
);
pass.write(
payload.params.type === "Buffer"
? Buffer.from(payload.params.data)
: payload.params
);
}
}
// Check newer chunks in the pool
if (pass.$pool.size > 0) {
this.logger.debug(`Has stored packets. Size: ${pass.$pool.size}`);
const nextSeq = pass.$prevSeq + 1;
const nextPacket = pass.$pool.get(nextSeq);
if (nextPacket) {
pass.$pool.delete(nextSeq);
setImmediate(() => this.requestHandler(nextPacket));
}
}
return pass && payload.seq == 0 ? pass : null;
}
/**
* Create an Error instance from payload ata
* @param {Object} error
* @param {Object} payload
*/
_createErrFromPayload(error, payload) {
return this.errorRegenerator.restore(error, payload);
}
/**
* Process incoming response of request
*
* @param {Object} packet
*
* @memberof Transit
*/
responseHandler(packet) {
const id = packet.id;
const req = this.pendingRequests.get(id);
// If not exists (timed out), we skip response processing
if (req == null) {
this.logger.debug(
"Orphan response is received. Maybe the request is timed out earlier. ID:",
packet.id,
", Sender:",
packet.sender
);
this.metrics.increment(METRIC.MOLECULER_TRANSIT_ORPHAN_RESPONSE_TOTAL);
return;
}
this.logger.debug(`<= Response '${req.action.name}' is received from '${packet.sender}'.`);
// Update nodeID in context (if it uses external balancer)
req.ctx.nodeID = packet.sender;
// Merge response meta with original meta
Object.assign(req.ctx.meta || {}, packet.meta || {});
// Handle stream response
if (packet.stream != null) {
if (this._handleIncomingResponseStream(packet, req)) return;
}
// Remove pending request
this.removePendingRequest(id);
if (!packet.success) {
req.reject(this._createErrFromPayload(packet.error, packet));
} else {
req.resolve(packet.data);
}
}
/**
* Handle incoming response stream.
*
* @param {Object} packet
* @param {Object} req
*/
_handleIncomingResponseStream(packet, req) {
let pass = this.pendingResStreams.get(packet.id);
if (!pass && !packet.stream && !packet.seq) return false;
if (!pass) {
this.logger.debug(
`<= New stream is received from '${packet.sender}'. Seq: ${packet.seq}`
);
pass = new Transform({
// TODO: It's incorrect because the chunks may receive in random order, so it processes an empty meta.
// Meta is filled correctly only in the 0. chunk.
objectMode: packet.meta && packet.meta["$streamObjectMode"],
transform: function (chunk, encoding, done) {
this.push(chunk);
return done();
}
});
pass.$prevSeq = -1;
pass.$pool = new Map();
this.pendingResStreams.set(packet.id, pass);
}
if (packet.seq > pass.$prevSeq + 1) {
// Some chunks are late. Store these chunks.
this.logger.debug(
`Put the chunk into pool (size: ${pass.$pool.size}). Seq: ${packet.seq}`
);
pass.$pool.set(packet.seq, packet);
// TODO: start timer.
// TODO: check length of pool.
// TODO: resetting seq.
return true;
}
// the next stream chunk received
pass.$prevSeq = packet.seq;
if (pass && packet.seq == 0) {
req.resolve(pass);
}
if (pass.$prevSeq > 0) {
if (!packet.stream) {
// Received error?
if (!packet.success)
pass.emit("error", this._createErrFromPayload(packet.error, packet));
this.logger.debug(
`<= Stream closing is received from '${packet.sender}'. Seq: ${packet.seq}`
);
// End of stream
pass.end();
// Remove pending request
this.removePendingRequest(packet.id);
return true;
} else {
// stream chunk
this.logger.debug(
`<= Stream chunk is received from '${packet.sender}'. Seq: ${packet.seq}`
);
pass.write(
packet.data.type === "Buffer" ? Buffer.from(packet.data.data) : packet.data
);
}
}
// Check newer chunks in the pool
if (pass.$pool.size > 0) {
this.logger.debug(`Has stored packets. Size: ${pass.$pool.size}`);
const nextSeq = pass.$prevSeq + 1;
const nextPacket = pass.$pool.get(nextSeq);
if (nextPacket) {
pass.$pool.delete(nextSeq);
setImmediate(() => this.responseHandler(nextPacket));
}
}
return true;
}
/**
* Send a request to a remote service. It returns a Promise
* what will be resolved when the response received.
*
* @param {<Context>} ctx Context of request
* @returns {Promise}
*
* @memberof Transit
*/
request(ctx) {
if (this.opts.maxQueueSize && this.pendingRequests.size >= this.opts.maxQueueSize)
/* istanbul ignore next */
return this.Promise.reject(
new E.QueueIsFullError({
action: ctx.action.name,
nodeID: this.nodeID,
size: this.pendingRequests.size,
limit: this.opts.maxQueueSize
})
);
// Expanded the code that v8 can optimize it. (TryCatchStatement disable optimizing)
return new this.Promise((resolve, reject) => this._sendRequest(ctx, resolve, reject));
}
/**
* Send a remote request
*
* @param {<Context>} ctx Context of request
* @param {Function} resolve Resolve of Promise
* @param {Function} reject Reject of Promise
*
* @memberof Transit
*/
_sendRequest(ctx, resolve, reject) {
const isStream =
ctx.params &&
ctx.params.readable === true &&
typeof ctx.params.on === "function" &&
typeof ctx.params.pipe === "function";
const request = {
action: ctx.action,
nodeID: ctx.nodeID,
ctx,
resolve,
reject,
stream: isStream // ???
};
const payload = {
id: ctx.id,
action: ctx.action.name,
params: isStream ? null : ctx.params,
meta: ctx.meta,
timeout: ctx.options.timeout,
level: ctx.level,
tracing: ctx.tracing,
parentID: ctx.parentID,
requestID: ctx.requestID,
caller: ctx.caller,
stream: isStream
};
if (payload.stream) {
if (
ctx.params.readableObjectMode === true ||
(ctx.params._readableState && ctx.params._readableState.objectMode === true)
) {
payload.meta = payload.meta || {};
payload.meta["$streamObjectMode"] = true;
}
payload.seq = 0;
}
const packet = new Packet(P.PACKET_REQUEST, ctx.nodeID, payload);
const nodeName = ctx.nodeID ? `'${ctx.nodeID}'` : "someone";
const requestID = ctx.requestID ? "with requestID '" + ctx.requestID + "' " : "";
this.logger.debug(`=> Send '${ctx.action.name}' request ${requestID}to ${nodeName} node.`);
const publishCatch = /* istanbul ignore next */ err => {
this.logger.error(
`Unable to send '${ctx.action.name}' request ${requestID}to ${nodeName} node.`,
err
);
this.broker.broadcastLocal("$transit.error", {
error: err,
module: "transit",
type: C.FAILED_SEND_REQUEST_PACKET
});
};
// Add to pendings
this.pendingRequests.set(ctx.id, request);
// Publish request
return this.publish(packet)
.then(() => {
if (isStream) {
// Skip to send ctx.meta with chunks because it doesn't appear on the remote side.
payload.meta = {};
// Still send information about objectMode in case of packets are received in wrong order
if (
ctx.params.readableObjectMode === true ||
(ctx.params._readableState && ctx.params._readableState.objectMode === true)
) {
payload.meta["$streamObjectMode"] = true;
}
const stream = ctx.params;
stream.on("data", chunk => {
stream.pause();
const chunks = [];
if (
chunk instanceof Buffer &&
this.opts.maxChunkSize > 0 &&
chunk.length > this.opts.maxChunkSize
) {
let len = chunk.length;
let i = 0;
while (i < len) {
chunks.push(chunk.slice(i, (i += this.opts.maxChunkSize)));
}
} else {
chunks.push(chunk);
}
return this.Promise.all(
chunks.map(ch => {
const copy = Object.assign({}, payload);
copy.seq = ++payload.seq;
copy.stream = true;
copy.params = ch;
this.logger.debug(
`=> Send stream chunk ${requestID}to ${nodeName} node. Seq: ${copy.seq}`
);
return this.publish(new Packet(P.PACKET_REQUEST, ctx.nodeID, copy));
})
)
.then(() => stream.resume())
.catch(publishCatch);
});
stream.on("end", () => {
const copy = Object.assign({}, payload);
copy.seq = ++payload.seq;
copy.params = null;
copy.stream = false;
this.logger.debug(
`=> Send stream closing ${requestID}to ${nodeName} node. Seq: ${copy.seq}`
);
return this.publish(new Packet(P.PACKET_REQUEST, ctx.nodeID, copy)).catch(
publishCatch
);
});
stream.on("error", err => {
const copy = Object.assign({}, payload);
copy.seq = ++payload.seq;
copy.stream = false;
copy.meta["$streamError"] = this._createPayloadErrorField(err, payload);
copy.params = null;
this.logger.debug(
`=> Send stream error ${requestID}to ${nodeName} node.`,
copy.meta["$streamError"]
);
return this.publish(new Packet(P.PACKET_REQUEST, ctx.nodeID, copy)).catch(
publishCatch
);
});
}
})
.catch(err => {
publishCatch(err);
reject(err);
});
}
/**
* Send an event to a remote node.
* The event is balanced by transporter
*
* @param {Context} ctx
*
* @memberof Transit
*/
sendEvent(ctx) {
const groups = ctx.eventGroups;
const requestID = ctx.requestID ? "with requestID '" + ctx.requestID + "' " : "";
if (ctx.endpoint)
this.logger.debug(
`=> Send '${ctx.eventName}' event ${requestID}to '${ctx.nodeID}' node` +
(groups ? ` in '${groups.join(", ")}' group(s)` : "") +
"."
);
else
this.logger.debug(
`=> Send '${ctx.eventName}' event ${requestID}to '${groups.join(", ")}' group(s).`
);
return this.publish(
new Packet(P.PACKET_EVENT, ctx.endpoint ? ctx.nodeID : null, {
id: ctx.id,
event: ctx.eventName,
data: ctx.params,
groups,
broadcast: ctx.eventType == "broadcast",
meta: ctx.meta,
level: ctx.level,
tracing: ctx.tracing,
parentID: ctx.parentID,
requestID: ctx.requestID,
caller: ctx.caller,
needAck: ctx.needAck
})
).catch(
/* istanbul ignore next */ err => {
this.logger.error(
`Unable to send '${ctx.eventName}' event ${requestID}to groups.`,
err
);
this.broker.broadcastLocal("$transit.error", {