-
Notifications
You must be signed in to change notification settings - Fork 49
/
stan.js
1112 lines (984 loc) · 33.1 KB
/
stan.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 2016-2018 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint esversion: 6 */
/* jshint node: true */
'use strict';
/**
* Module Dependencies
*/
const util = require('util'),
nats = require('nats'),
timers = require('timers'),
events = require('events'),
nuid = require('nuid'),
url = require('url'),
proto = require('./pb');
/**
* Constants
*/
const VERSION = '0.2.6',
DEFAULT_PORT = 4222,
DEFAULT_PRE = 'nats://localhost:',
DEFAULT_URI = DEFAULT_PRE + DEFAULT_PORT,
DEFAULT_DISCOVER_PREFIX = '_STAN.discover',
DEFAULT_ACK_PREFIX = '_STAN.acks',
DEFAULT_CONNECT_WAIT = 1000 * 2,
DEFAULT_MAX_IN_FLIGHT = 16384,
DEFAULT_ACK_WAIT = 30 * 1000,
BAD_SUBJECT = 'stan: subject must be supplied',
BAD_CLUSTER_ID = 'stan: cluster ID must be supplied',
BAD_CLIENT_ID = 'stan: client ID must be supplied',
MAX_FLIGHT_LIMIT_REACHED = 'stan: max in flight reached.',
CONN_CLOSED = 'stan: Connection closed',
BAD_SUBSCRIPTION = 'stan: invalid subscription',
BINARY_ENCODING_REQUIRED = 'stan: NATS connection encoding must be \'binary\'.',
NO_SERVER_SUPPORT = 'stan: not supported by server',
ACK_TIMEOUT = 'stan: publish ack timeout',
CONNECT_REQ_TIMEOUT = 'stan: connect request timeout',
CLOSE_REQ_TIMEOUT = 'stan: close request timeout',
SUB_REQ_TIMEOUT = 'stan: subscribe request timeout',
UNSUB_REQ_TIMEOUT = 'stan: unsubscribe request timeout',
PROTOCOL_ONE = 1,
DEFAULT_PING_INTERVAL = 5 * 1000,
DEFAULT_PING_MAXOUT = 3,
MAX_PINGS_EXCEEDED = 'stan: connection lost due to PING failure';
/**
* Library Version
* @type {string}
*/
exports.version = VERSION;
function Stan(clusterID, clientID, opts) {
events.EventEmitter.call(this);
if (typeof clusterID !== 'string' || clusterID.length < 1) {
throw new Error(BAD_CLUSTER_ID);
}
if (typeof clientID !== 'string' || clientID.length < 1) {
throw new Error(BAD_CLIENT_ID);
}
this.clusterID = clusterID;
this.clientID = clientID;
this.ackSubject = DEFAULT_ACK_PREFIX + "." + nuid.next(); // publish acks
// these are set by stan
this.pubPrefix = null; // publish prefix appended to subject
this.subRequests = null; // subject for subscription requests
this.unsubRequests = null; // subject for unsubscribe requests
this.subCloseRequests = null; // subject for subscription close requests
this.closeRequests = null; // subject for close requests
this.parseOptions(opts);
this.initState();
this.createConnection();
return this;
}
util.inherits(Stan, events.EventEmitter);
/**
* Connect to a nats-streaming-server and return the client.
* @param {string} clusterID
* @param {string} [clientID] - must be unique
* @param {object} [opts] - object with NATS/STAN options
* @return {Stan}
* @public
*/
exports.connect = function(clusterID, clientID, opts) {
return new Stan(clusterID, clientID, opts);
};
/**
* Returns true if the connection to NATS is closed.
* @returns {boolean}
* @private
*/
Stan.prototype.isClosed = function() {
return this.nc === undefined;
};
/**
* Parses the provided options
* @param {number|string|object} opts
* @private
*/
Stan.prototype.parseOptions = function(opts) {
const options = this.options = {
url: DEFAULT_URI,
connectTimeout: DEFAULT_CONNECT_WAIT,
ackTimeout: DEFAULT_ACK_WAIT,
discoverPrefix: DEFAULT_DISCOVER_PREFIX,
maxPubAcksInflight: DEFAULT_MAX_IN_FLIGHT,
stanEncoding: 'utf8',
stanPingInterval: DEFAULT_PING_INTERVAL,
stanMaxPingOut: DEFAULT_PING_MAXOUT,
maxReconnectAttempts: -1
};
if (opts === undefined) {
options.url = DEFAULT_URI;
} else if ('number' === typeof opts) {
options.url = DEFAULT_PRE + opts;
} else if ('string' === typeof opts) {
options.url = sanitizeUrl(opts);
} else if ('object' === typeof opts) {
if (opts.port !== undefined) {
options.url = DEFAULT_PRE + opts.port;
}
this.assignOption(opts, 'discoverPrefix');
this.assignOption(opts, 'nc');
this.assignOption(opts, 'connectTimeout');
this.assignOption(opts, 'ackTimeout');
this.assignOption(opts, 'maxPubAcksInflight');
this.assignOption(opts, 'stanEncoding');
this.assignOption(opts, 'stanPingInterval');
this.assignOption(opts, 'stanMaxPingOut');
// node-nats does takes a bunch of other options
// we simply forward them, as node-nats is used
// underneath.
this.assignOption(opts, 'url');
this.assignOption(opts, 'uri', 'url');
this.assignOption(opts, 'user');
this.assignOption(opts, 'pass');
this.assignOption(opts, 'token');
this.assignOption(opts, 'tokenHandler');
this.assignOption(opts, 'password', 'pass');
this.assignOption(opts, 'verbose');
this.assignOption(opts, 'pedantic');
this.assignOption(opts, 'reconnect');
this.assignOption(opts, 'maxReconnectAttempts');
this.assignOption(opts, 'reconnectTimeWait');
this.assignOption(opts, 'servers');
this.assignOption(opts, 'urls', 'servers');
this.assignOption(opts, 'noRandomize');
this.assignOption(opts, 'NoRandomize', 'noRandomize');
this.assignOption(opts, 'dontRandomize', 'noRandomize');
this.assignOption(opts, 'encoding');
this.assignOption(opts, 'tls');
this.assignOption(opts, 'secure', 'tls');
this.assignOption(opts, 'name');
this.assignOption(opts, 'client', 'name');
this.assignOption(opts, 'yieldTime');
this.assignOption(opts, 'waitOnFirstConnect');
this.assignOption(opts, 'preserveBuffers');
this.assignOption(opts, 'pingInterval');
this.assignOption(opts, 'maxPingOut');
this.assignOption(opts, 'useOldRequestStyle');
}
};
function sanitizeUrl(host) {
if ((/^.*:\/\/.*/).exec(host) === null) {
// Does not have a scheme.
host = 'nats://' + host;
}
const u = url.parse(host);
if (u.port === null || u.port == '') {
host += ":" + DEFAULT_PORT;
}
return host;
}
/**
* Updates the internal option to the value from opts.
* @param {object} opts
* @param {string} prop - the property name
* @param {string} [assign] is an alternate name for prop name in the target
*/
Stan.prototype.assignOption = function(opts, prop, assign) {
if (assign === undefined) {
assign = prop;
}
if (opts[prop] !== undefined) {
this.options[assign] = opts[prop];
}
};
/**
* Internal initializer
*/
Stan.prototype.initState = function() {
this.pubAckMap = {};
this.pubAckOutstanding = 0;
this.subMap = {};
};
/**
* Connect event - emitted when the streaming protocol connection sequence has
* completed and the client is ready to process requests.
*
* @event Stan#connect
* @type {Stan}
*/
/**
* Close event - emitted when Stan#close() is called or its underlying NATS connection
* closes
*
* @event Stan#close
*/
/**
* Reconnecting event - emitted with the underlying NATS connection emits reconnecting
*
* @Event Stan#reconnecting
*/
/**
* Error event - emitted when there's an error
* @type {Error|object}
*
* Stan#error
*/
/**
* Connect to a NATS Streaming subsystem
* @fires Stan#connect, Stan#close, Stan#reconnecting, Stan#error
*/
Stan.prototype.createConnection = function() {
if (typeof this.options.nc === 'object') {
if (this.options.nc.encoding !== 'binary') {
throw new Error(BINARY_ENCODING_REQUIRED);
} else {
this.nc = this.options.nc;
}
}
if (this.nc === undefined) {
const encoding = this.options.encoding;
if (encoding && encoding !== 'binary') {
throw new Error(BINARY_ENCODING_REQUIRED);
} else {
this.options.encoding = 'binary';
}
this.nc = nats.connect(this.options);
this.ncOwned = true;
}
this.nc.on('connect', () => {
// heartbeat processing
const hbInbox = nats.createInbox();
this.hbSubscription = this.nc.subscribe(hbInbox, (msg, reply) => {
this.nc.publish(reply);
});
this.pingInbox = nats.createInbox();
this.pingSubscription = this.nc.subscribe(this.pingInbox, (msg) => {
if (msg) {
const pingResponse = proto.pb.PingResponse.deserializeBinary(Buffer.from(msg, 'binary'));
const err = pingResponse.getError();
if (err) {
this.closeWithError('connection_lost', err);
return;
}
}
this.pingOut = 0;
});
this.ackSubscription = this.nc.subscribe(this.ackSubject, this.processAck());
const discoverSubject = this.options.discoverPrefix + '.' + this.clusterID;
//noinspection JSUnresolvedFunction
this.connId = Buffer.from(nuid.next(), "utf8");
const req = new proto.pb.ConnectRequest();
req.setClientId(this.clientID);
req.setHeartbeatInbox(hbInbox);
req.setProtocol(PROTOCOL_ONE);
req.setConnId(this.connId);
req.setPingInterval(Math.ceil(this.options.stanPingInterval / 1000));
req.setPingMaxOut(this.options.stanMaxPingOut);
this.nc.requestOne(discoverSubject, Buffer.from(req.serializeBinary()), this.options.connectTimeout, (msg) => {
if (msg instanceof nats.NatsError) {
let err = msg;
if (msg.code === nats.REQ_TIMEOUT) {
err = new nats.NatsError(CONNECT_REQ_TIMEOUT, CONNECT_REQ_TIMEOUT, err);
}
this.closeWithError('error', err);
return;
}
const cr = proto.pb.ConnectResponse.deserializeBinary(Buffer.from(msg, 'binary'));
if (cr.getError() !== "") {
this.closeWithError('error', cr.getError());
return;
}
this.pubPrefix = cr.getPubPrefix();
this.subRequests = cr.getSubRequests();
this.unsubRequests = cr.getUnsubRequests();
this.subCloseRequests = cr.getSubCloseRequests();
this.closeRequests = cr.getCloseRequests();
let unsubPingSub = true;
if (cr.getProtocol() >= PROTOCOL_ONE) {
if (cr.getPingInterval() !== 0) {
unsubPingSub = false;
this.pingRequests = cr.getPingRequests();
this.stanPingInterval = cr.getPingInterval() * 1000;
this.stanMaxPingOut = cr.getPingMaxOut();
const ping = new proto.pb.Ping();
ping.setConnId(this.connId);
this.pingBytes = Buffer.from(ping.serializeBinary());
this.pingOut = 0;
const that = this;
this.pingTimer = setTimeout(function pingFun() {
that.pingOut++;
if (that.pingOut > that.stanMaxPingOut) {
that.closeWithError('connection_lost', new Error(MAX_PINGS_EXCEEDED));
return;
}
that.nc.publish(that.pingRequests, that.pingBytes, that.pingInbox);
that.pingTimer = setTimeout(pingFun, that.stanPingInterval);
}, this.stanPingInterval);
}
}
if (unsubPingSub) {
this.nc.unsubscribe(this.pingSubscription);
this.pingSubscription = null;
}
this.emit('connect', this);
});
});
this.nc.on('close', () => {
// insure we cleaned up
this.cleanupOnClose();
this.emit('close');
});
this.nc.on('disconnect', () => {
this.emit('disconnect');
});
this.nc.on('reconnect', () => {
this.emit('reconnect', this);
});
this.nc.on('reconnecting', () => {
this.emit('reconnecting');
});
this.nc.on('error', (msg) => {
this.emit('error', msg);
});
};
/**
* Close stan invoking the event notification with the
* specified error, followed by a close notification.
* @param event
* @param error
* @private
*/
Stan.prototype.closeWithError = function(event, error) {
if (this.nc === undefined || this.clientID === undefined) {
return;
}
this.cleanupOnClose(error);
if (this.ncOwned) {
this.nc.close();
}
this.emit(event, error);
this.emit('close');
};
/**
* Cleanup stan protocol subscriptions, pings and pending acks
* @param err
* @private
*/
Stan.prototype.cleanupOnClose = function(err) {
// remove the ping timer
if (this.pingTimer) {
timers.clearTimeout(this.pingTimer);
delete this.pingTimer;
}
// if we don't own the connection, we unsub to insure
// that a subsequent reconnect will properly clean up.
// Otherwise the close() will take care of it.
if (!this.ncOwned && this.nc) {
if (this.ackSubscription) {
this.nc.unsubscribe(this.ackSubscription);
this.ackSubscription = null;
}
if (this.pingSubscription) {
this.nc.unsubscribe(this.pingSubscription);
this.pingSubscription = null;
}
if (this.hbSubscription) {
this.nc.unsubscribe(this.hbSubscription);
this.hbSubscription = null;
}
}
for (const guid in this.pubAckMap) {
if (this.pubAckMap.hasOwnProperty(guid)) {
const a = this.removeAck(guid);
if (a && a.ah && typeof a.ah === 'function') {
a.ah(err, guid);
}
}
}
};
/**
* Closes the NATS streaming server connection, or returns if already closed.
* @fire Stan.close, Stan.error
*
*/
Stan.prototype.close = function() {
if (this.nc === undefined || this.clientID === undefined) {
return;
}
this.cleanupOnClose(new Error(CONN_CLOSED));
//noinspection JSUnresolvedFunction
if (this.nc && this.closeRequests) {
const req = new proto.pb.CloseRequest();
req.setClientId(this.clientID);
this.nc.requestOne(this.closeRequests, Buffer.from(req.serializeBinary()), {}, this.options.connectTimeout, (msgOrError) => {
const nc = this.nc;
delete this.nc;
let closeError = null;
//noinspection JSUnresolvedVariable
if (msgOrError instanceof nats.NatsError) {
// if we get an error here, we simply show it in the close notification as there's not much we can do here.
closeError = msgOrError;
} else {
const cr = proto.pb.CloseResponse.deserializeBinary(Buffer.from(msgOrError, 'binary'));
const err = cr.getError();
if (err && err.length > 0) {
// if the protocol returned an error there's nothing for us to handle, pass it as an arg to close notification.
closeError = new Error(err);
}
}
if (nc && this.ncOwned) {
nc.close();
}
this.emit('close', closeError);
});
} else {
if (this.nc && this.ncOwned) {
this.nc.close();
delete this.nc;
}
this.emit('close');
}
};
/**
* @return {Function} for processing acks associated with the protocol
* @protected
*/
Stan.prototype.processAck = function() {
return (msg) => {
//noinspection JSUnresolvedVariable
const pa = proto.pb.PubAck.deserializeBinary(Buffer.from(msg, 'binary'));
const guid = pa.getGuid();
const a = this.removeAck(guid);
if (a && a.ah) {
const err = pa.getError();
a.ah(err === '' ? undefined : err, guid);
}
};
};
/**
* Removes Ack for the specified guid from the outstanding ack list
* @param {string} guid
* @return {object}
* @protected
*/
Stan.prototype.removeAck = function(guid) {
const a = this.pubAckMap[guid];
if (a !== undefined) {
delete this.pubAckMap[guid];
this.pubAckOutstanding--;
if (a.t !== undefined) {
//noinspection JSUnresolvedFunction
timers.clearTimeout(a.t);
}
}
return a;
};
/**
* Publishes a message to the streaming server with the specified subject and data.
* Data can be {Uint8Array|string|Buffer}. The ackHandler is called with any errors or
* empty string, and the guid for the published message.
*
* Note that if the maxPubAcksInflight option is exceeded, the ackHandler will be called
* with an error. If no ackHandler was provided, an exception is thrown.
* @param subject
* @param data {Uint8Array|string|Buffer}
* @param ackHandler(err,guid)
*/
Stan.prototype.publish = function(subject, data, ackHandler) {
if (this.nc === undefined) {
if (util.isFunction(ackHandler)) {
ackHandler(new Error(CONN_CLOSED));
return;
} else {
throw new Error(CONN_CLOSED);
}
}
if (this.pubAckOutstanding > this.options.maxPubAcksInflight) {
// we have many pending publish messages, fail it.
if (util.isFunction(ackHandler)) {
ackHandler(new Error(MAX_FLIGHT_LIMIT_REACHED));
} else {
throw new Error(MAX_FLIGHT_LIMIT_REACHED);
}
}
const subj = this.pubPrefix + '.' + subject;
const peGUID = nuid.next();
//noinspection JSUnresolvedFunction
const pe = new proto.pb.PubMsg();
pe.setClientId(this.clientID);
pe.setConnId(this.connId);
pe.setGuid(peGUID);
pe.setSubject(subject);
let buf;
if (typeof data === 'string') {
buf = Buffer.from(data, 'utf8');
data = new Uint8Array(buf);
} else if (Buffer.prototype.isPrototypeOf(data)) {
buf = Buffer.from(data, 'utf8');
data = new Uint8Array(buf);
} else if (Buffer.prototype.isPrototypeOf(Uint8Array)) {
// we already handle this
}
pe.setData(data);
const ack = {};
ack.ah = ackHandler;
this.pubAckMap[peGUID] = ack;
const bytes = Buffer.from(pe.serializeBinary());
this.nc.publish(subj, bytes, this.ackSubject);
this.pubAckOutstanding++;
// all acks are received in ackSubject, so not possible to reuse nats.timeout
//noinspection JSUnresolvedFunction
ack.t = timers.setTimeout(() => {
const a = this.removeAck(peGUID);
if (a && a.ah !== undefined) {
a.ah(new Error(ACK_TIMEOUT), peGUID);
}
}, this.options.ackTimeout);
return peGUID;
};
/**
* Creates a NATS streaming server subscription on the specified subject. If qGroup
* is provided, the subscription will be distributed between all subscribers using
* the same qGroup name.
* @param {String} subject
* @param {String} [qGroup]
* @param {SubscriptionOptions} [options]
* @throws err if the subject is not provided
* @fires Stan#error({Error})
* @returns Subscription
*/
Stan.prototype.subscribe = function(subject, qGroup, options) {
const args = {};
if (typeof qGroup === 'string') {
args.qGroup = qGroup;
} else if (typeof qGroup === 'object') {
args.options = qGroup;
}
if (typeof options === 'object') {
args.options = options;
}
if (!args.options) {
args.options = new SubscriptionOptions();
}
// in node-nats there's no Subscription object...
const retVal = new Subscription(this, subject, args.qGroup, nats.createInbox(), args.options, args.callback);
if (typeof subject !== 'string' || subject.length === 0) {
process.nextTick(() => {
retVal.emit('error', new Error(BAD_SUBJECT));
});
return retVal;
}
if (this.isClosed()) {
process.nextTick(() => {
retVal.emit('error', new Error(CONN_CLOSED));
});
return retVal;
}
this.subMap[retVal.inbox] = retVal;
retVal.inboxSub = this.nc.subscribe(retVal.inbox, this.processMsg());
const sr = new proto.pb.SubscriptionRequest();
sr.setClientId(this.clientID);
sr.setSubject(subject);
sr.setQGroup(retVal.qGroup || '');
sr.setInbox(retVal.inbox);
sr.setMaxInFlight(retVal.opts.maxInFlight);
sr.setAckWaitInSecs(retVal.opts.ackWait / 1000);
sr.setStartPosition(retVal.opts.startPosition);
sr.setDurableName(retVal.opts.durableName || '');
switch (sr.getStartPosition()) {
case proto.pb.StartPosition.TIME_DELTA_START:
sr.setStartTimeDelta(retVal.opts.startTime);
break;
case proto.pb.StartPosition.SEQUENCE_START:
sr.setStartSequence(retVal.opts.startSequence);
break;
}
this.nc.requestOne(this.subRequests, Buffer.from(sr.serializeBinary()), this.options.connectTimeout, (msg) => {
if (msg instanceof nats.NatsError) {
if (msg.code === nats.REQ_TIMEOUT) {
const err = new nats.NatsError(SUB_REQ_TIMEOUT, SUB_REQ_TIMEOUT, msg);
retVal.emit('timeout', err);
} else {
retVal.emit('error', msg);
}
return;
}
//noinspection JSUnresolvedVariable
const r = proto.pb.SubscriptionResponse.deserializeBinary(Buffer.from(msg, 'binary'));
const err = r.getError();
if (err && err.length !== 0) {
retVal.emit('error', new Error(err));
this.nc.unsubscribe(retVal.inboxSub);
retVal.emit('unsubscribed');
return;
}
retVal.ackInbox = r.getAckInbox();
retVal.emit('ready');
});
return retVal;
};
/**
* A NATS streaming subscription is an {event.EventEmitter} representing a subscription to the
* server. The subscription will be ready to receive messages after the Subscription#ready notification.
* fires. Messages are delivered on the Subscription#message(msg) notificatication.
* @param stanConnection
* @param subject
* @param qGroup
* @param inbox
* @param opts
* @constructor
* @fires Subscription#error({Error}), Subscription#unsubscribed, Subscription#ready, Subscription#timeout({Error})
* Subscription#message({Message})
*/
function Subscription(stanConnection, subject, qGroup, inbox, opts) {
this.stanConnection = stanConnection;
this.subject = subject;
this.qGroup = qGroup;
this.inbox = inbox;
this.opts = opts;
this.ackInbox = undefined;
this.inboxSub = undefined;
}
/**
* Error event - if there's an error with setting up the subscription, such
* as the connection is closed or the server returns an error.
*
* @event Subscription#Error
* @type Error
*/
/**
* Timeout event - An error notification indicating that the operation timeout.
*
* @event Subscription#Timeout
* @type Error
*/
/**
* Unsubscribed event - notification that the unsubscribe request was processed by the server
*
* @event Subscription#unsubscribed
*/
/**
* Ready event - notification that the subscription request was processed by the server
*
* @event Subscription#ready
*/
/**
* Message event - notification that the subscription received a message from the server
* @event Subscription#message
* @type {Message}
*/
util.inherits(Subscription, events.EventEmitter);
/**
* Returns true if the subscription has been closed or unsubscribed from.
* @returns {boolean}
*/
Subscription.prototype.isClosed = function() {
return this.stanConnection === undefined;
};
/**
* Unregisters the subscription from the streaming server. You cannot unsubscribe
* from the server unless the Subscription#ready notification has already fired.
* @fires Subscription#error({Error}, Subscription#unsubscribed, Subscription#timeout({Error}
*/
Subscription.prototype.unsubscribe = function() {
this.closeOrUnsubscribe(false);
};
/**
* Close removes the subscriber from the server, but unlike the Subscription#unsubscribe(),
* the durable interest is not removed. If the client has connected to a server
* for which this feature is not available, Subscription#Close() will emit a
* Subscription#error(NO_SERVER_SUPPORT) error. Note that this affects durable clients only.
* If called on a non-durable subscriber, this is equivalent to Subscription#close()
*
* @fires Subscription#error({Error}, Subscription#closed
*/
Subscription.prototype.close = function() {
this.closeOrUnsubscribe(true);
};
/**
* @param doClose
* @private
*/
Subscription.prototype.closeOrUnsubscribe = function(doClose) {
if (this.isClosed()) {
this.emit('error', new Error(BAD_SUBSCRIPTION));
return;
}
const sc = this.stanConnection;
delete this.stanConnection;
delete sc.subMap[this.inbox];
if (sc.isClosed()) {
this.emit('error', new Error(CONN_CLOSED));
return;
}
let reqSubject = sc.unsubRequests;
if (doClose) {
reqSubject = sc.subCloseRequests;
if (!reqSubject) {
this.emit('error', new Error(NO_SERVER_SUPPORT));
}
}
sc.nc.unsubscribe(this.inboxSub);
//noinspection JSUnresolvedFunction
const ur = new proto.pb.UnsubscribeRequest();
ur.setClientId(sc.clientID);
ur.setSubject(this.subject);
ur.setInbox(this.ackInbox);
sc.nc.requestOne(reqSubject, Buffer.from(ur.serializeBinary()), sc.options.connectTimeout, (msg) => {
let err;
if (msg instanceof nats.NatsError) {
const type = doClose ? CLOSE_REQ_TIMEOUT : UNSUB_REQ_TIMEOUT;
err = new nats.NatsError(type, type, msg);
if (msg.code === nats.REQ_TIMEOUT) {
this.emit('timeout', err);
} else {
this.emit('error', err);
}
return;
}
//noinspection JSUnresolvedVariable
const r = proto.pb.SubscriptionResponse.deserializeBinary(Buffer.from(msg, 'binary'));
err = r.getError();
if (err && err.length > 0) {
this.emit('error', new Error(r.getError()));
} else {
this.emit(doClose ? 'closed' : 'unsubscribed');
}
});
};
/**
* Internal function to process in-bound messages.
* @return {Function}
* @private
*/
Stan.prototype.processMsg = function() {
// curry
return (rawMsg, reply, subject, sid) => {
const sub = this.subMap[subject];
try {
//noinspection JSUnresolvedVariable
const m = proto.pb.MsgProto.deserializeBinary(Buffer.from(rawMsg, 'binary'));
if (sub === undefined || !this.nc) {
return;
}
const msg = new Message(this, m, sub);
sub.emit('message', msg);
msg.maybeAutoAck();
} catch (error) {
sub.emit('error', error);
}
};
};
/**
* Represents a message received from the streaming server.
* @param stanClient
* @param msg
* @param subscription
* @constructor
*/
function Message(stanClient, msg, subscription) {
this.stanClient = stanClient;
this.msg = msg;
this.subscription = subscription;
}
/**
* Returns the sequence number of the message.
* @returns {number}
*/
Message.prototype.getSequence = function() {
return this.msg.getSequence();
};
/**
* Returns the subject the message was published on
* @returns {string}
*/
Message.prototype.getSubject = function() {
return this.msg.getSubject();
};
/**
* Returns a Buffer object with the raw message payload.
* @returns {Buffer}
*/
Message.prototype.getRawData = function() {
return Buffer.from(this.msg.getData(), 'binary');
};
/**
* Convenience API to convert the results of Message#getRawData to
* a string with the specified 'stanEncoding'. Note that if the encoding
* is set to binary, this method returns Message#getRawData.
* @returns {!(string|Uint8Array)|string}
*/
Message.prototype.getData = function() {
let bytes = this.msg.getData();
const encoding = this.stanClient.options.stanEncoding;
if (encoding !== 'binary') {
bytes = bytes.length > 0 ? Buffer.from(bytes, encoding).toString() : '';
}
return bytes;
};
/**
* Returns the raw timestamp. The NATS streaming server returns a 64bit nanosecond resolution
* timestamp that is not quite useful in JavaScript. Use Message#getTimestamp to read
* a timestamp as a Date.
* @returns {number}
*/
Message.prototype.getTimestampRaw = function() {
return this.msg.getTimestamp();
};
/**
* Returns Message#getTimestampRaw as a JavaScript Date.
* @returns {Date}
*/
Message.prototype.getTimestamp = function() {
return new Date(this.getTimestampRaw() / 1000000);
};
/**
* Returns true if this message is being redelivered.
* @returns {boolean}
*/
Message.prototype.isRedelivered = function() {
return this.msg.getRedelivered();
};
/**
* Returns the CRC32 of the message if provided.
* @returns {number}
*/
Message.prototype.getCrc32 = function() {
return this.msg.getCrc32();
};
/**
* Calls Message.ack if the subscription was specified to
* use manualAcks.
* @type {Message.ack}
* @protected
*/
Message.prototype.maybeAutoAck = function() {
if (!this.subscription.opts.manualAcks) {
this.ack();
}
};
/**
* Acks the message, note this method shouldn't be called unless
* the manualAcks option was set on the subscription.
*/
Message.prototype.ack = function() {
if (!this.subscription.isClosed()) {
const ack = new proto.pb.Ack();
ack.setSubject(this.getSubject());
ack.setSequence(this.getSequence());
this.stanClient.nc.publish(this.subscription.ackInbox, Buffer.from(ack.serializeBinary()));
}
};
/**
*
* @returns {!(string|Uint8Array)}
*/
Message.prototype.getClientID = function() {
return this.msg.getConnId();
};
Message.prototype.getConnectionID = function() {
return this.msg.getClientId();
};
/**
* Returns an object with various constants for StartPosition (NEW_ONLY,
* LAST_RECEIVED, TIME_DELTA_START, SEQUENCE_START, FIRST)
* @type {StartPosition}
*/