-
Notifications
You must be signed in to change notification settings - Fork 161
/
nats.js
2196 lines (2021 loc) · 59.5 KB
/
nats.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 2013-2020 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.
*/
/* eslint no-sync: 0 */
'use strict'
/**
* Module Dependencies
*/
const net = require('net')
const tls = require('tls')
const util = require('util')
const events = require('events')
const nuid = require('nuid')
const nkeys = require('ts-nkeys')
const fs = require('fs')
const url = require('url')
/**
* Constants
*/
const VERSION = require('../package.json').version
const DEFAULT_PORT = 4222
const DEFAULT_PRE = 'nats://localhost:'
const DEFAULT_URI = DEFAULT_PRE + DEFAULT_PORT
const MAX_CONTROL_LINE_SIZE = 1024
// Parser state
const AWAITING_CONTROL = 0
const AWAITING_MSG_PAYLOAD = 1
// Reconnect Parameters, 2 sec wait, 10 tries
const DEFAULT_RECONNECT_TIME_WAIT = 2 * 1000
const DEFAULT_MAX_RECONNECT_ATTEMPTS = 10
// Ping interval
const DEFAULT_PING_INTERVAL = 2 * 60 * 1000 // 2 minutes
const DEFAULT_MAX_PING_OUT = 2
// Protocol
const MSG = /^MSG\s+([^\s\r\n]+)\s+([^\s\r\n]+)\s+(([^\s\r\n]+)[^\S\r\n]+)?(\d+)\r\n/i
const OK = /^\+OK\s*\r\n/i
const ERR = /^-ERR\s+('.+')?\r\n/i
const PING = /^PING\r\n/i
const PONG = /^PONG\r\n/i
const INFO = /^INFO\s+([^\r\n]+)\r\n/i
const SUBRE = /^SUB\s+([^\r\n]+)\r\n/i
const CREDS = /\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))/i
const CR_LF = '\r\n'
const CR_LF_LEN = CR_LF.length
const EMPTY = ''
const SPC = ' '
// Protocol
const SUB = 'SUB'
const UNSUB = 'UNSUB'
const CONNECT = 'CONNECT'
// Responses
const PING_REQUEST = 'PING' + CR_LF
const PONG_RESPONSE = 'PONG' + CR_LF
// Errors
const BAD_AUTHENTICATION = 'BAD_AUTHENTICATION'
const BAD_CREDS = 'BAD_CREDENTIALS'
const BAD_JSON = 'BAD_JSON'
const BAD_MSG = 'BAD_MSG'
const BAD_OPTIONS = 'BAD_OPTIONS'
const BAD_REPLY = 'BAD_REPLY'
const BAD_SUBJECT = 'BAD_SUBJECT'
const CLIENT_CERT_REQ = 'CLIENT_CERT_REQ'
const CONN_CLOSED = 'CONN_CLOSED'
const CONN_DRAINING = 'CONN_DRAINING'
const CONN_ERR = 'CONN_ERR'
const CONN_TIMEOUT = 'CONN_TIMEOUT'
const INVALID_ENCODING = 'INVALID_ENCODING'
const NATS_PROTOCOL_ERR = 'NATS_PROTOCOL_ERR'
const NKEY_OR_JWT_REQ = 'NKEY_OR_JWT_REQ'
const NON_SECURE_CONN_REQ = 'NON_SECURE_CONN_REQ'
const NO_ECHO_NOT_SUPPORTED = 'NO_ECHO_NOT_SUPPORTED'
const NO_SEED_IN_CREDS = 'NO_SEED_IN_CREDS'
const NO_USER_JWT_IN_CREDS = 'NO_USER_JWT_IN_CREDS'
const OPENSSL_ERR = 'OPENSSL_ERR'
const PERMISSIONS_ERR = 'permissions violation'
const REQ_TIMEOUT = 'REQ_TIMEOUT'
const SECURE_CONN_REQ = 'SECURE_CONN_REQ'
const SIGCB_NOTFUNC = 'SIG_NOT_FUNC'
const SIGNATURE_REQUIRED = 'SIG_REQ'
const STALE_CONNECTION_ERR = 'stale connection'
const SUB_DRAINING = 'SUB_DRAINING'
const BAD_AUTHENTICATION_MSG = 'User and Token can not both be provided'
const BAD_AUTHENTICATION_TH_FAILED_MSG_PREFIX = 'tokenHandler call failed: '
const BAD_AUTHENTICATION_TH_NOT_FUNC_MSG = 'tokenHandler must be a function returning a token'
const BAD_AUTHENTICATION_T_AND_TH_MSG = 'token and tokenHandler cannot both be provided'
const BAD_CREDS_MSG = 'Bad user credentials'
const BAD_JSON_MSG = 'Message should be a non-circular JSON-serializable value'
const BAD_MSG_MSG = 'Message can\'t be a function'
const BAD_OPTIONS_MSG = 'Options should be an object as second parameter.'
const BAD_REPLY_MSG = 'Reply can\'t be a function'
const BAD_SUBJECT_MSG = 'Subject must be supplied'
const CLIENT_CERT_REQ_MSG = 'Server requires a client certificate.'
const CONN_CLOSED_MSG = 'Connection closed'
const CONN_DRAINING_MSG = 'Connection draining'
const CONN_ERR_MSG_PREFIX = 'Could not connect to server: '
const CONN_TIMEOUT_MSG = 'Connection timeout'
const INVALID_ENCODING_MSG_PREFIX = 'Invalid Encoding:'
const NKEY_OR_JWT_REQ_MSG = 'An Nkey or User JWT callback needs to be defined.'
const NON_SECURE_CONN_REQ_MSG = 'Server does not support a secure connection.'
const NO_ECHO_NOT_SUPPORTED_MSG = 'echo is not supported'
const NO_SEED_IN_CREDS_MSG = 'Can not locate signing key in credentials'
const NO_USER_JWT_IN_CREDS_MSG = 'Can not locate user jwt in credentials.'
const OPENSSL_ERR_MSG_PREFIX = 'TLS credentials verification failed: '
const REQ_TIMEOUT_MSG_PREFIX = 'The request timed out for subscription id: '
const SECURE_CONN_REQ_MSG = 'Server requires a secure connection.'
const SIGCB_NOTFUNC_MSG = 'Signature callback is not a function.'
const SIGNATURE_REQUIRED_MSG = 'Server requires an Nkey signature.'
const SUB_DRAINING_MSG = 'Subscription draining'
const FLUSH_THRESHOLD = 65536
/**
* @param {String} message
* @param {String} code
* @param {Error} [chainedError]
* @constructor
*
* @api private
*/
function NatsError (message, code, chainedError) {
Error.captureStackTrace(this, this.constructor)
this.name = this.constructor.name
this.message = message
this.code = code
// noinspection JSUnusedGlobalSymbols
this.chainedError = chainedError
}
util.inherits(NatsError, Error)
exports.NatsError = NatsError
/**
* Library Version
*/
exports.version = VERSION
/**
* Error codes
*/
exports.BAD_AUTHENTICATION = BAD_AUTHENTICATION
exports.BAD_CREDS = BAD_CREDS
exports.BAD_JSON = BAD_JSON
exports.BAD_MSG = BAD_MSG
exports.BAD_OPTIONS = BAD_OPTIONS
exports.BAD_REPLY = BAD_REPLY
exports.BAD_SUBJECT = BAD_SUBJECT
exports.CLIENT_CERT_REQ = CLIENT_CERT_REQ
exports.CONN_CLOSED = CONN_CLOSED
exports.CONN_DRAINING = CONN_DRAINING
exports.CONN_ERR = CONN_ERR
exports.CONN_TIMEOUT = CONN_TIMEOUT
exports.INVALID_ENCODING = INVALID_ENCODING
exports.NATS_PROTOCOL_ERR = NATS_PROTOCOL_ERR
exports.NKEY_OR_JWT_REQ = NKEY_OR_JWT_REQ
exports.NON_SECURE_CONN_REQ = NON_SECURE_CONN_REQ
exports.NO_ECHO_NOT_SUPPORTED = NO_ECHO_NOT_SUPPORTED
exports.NO_SEED_IN_CREDS = NO_SEED_IN_CREDS
exports.NO_USER_JWT_IN_CREDS = NO_USER_JWT_IN_CREDS
exports.OPENSSL_ERR = OPENSSL_ERR
exports.PERMISSIONS_ERR = PERMISSIONS_ERR
exports.REQ_TIMEOUT = REQ_TIMEOUT
exports.SECURE_CONN_REQ = SECURE_CONN_REQ
exports.SIGCB_NOTFUNC = SIGCB_NOTFUNC
exports.SIGNATURE_REQUIRED = SIGNATURE_REQUIRED
exports.STALE_CONNECTION_ERR = STALE_CONNECTION_ERR
exports.SUB_DRAINING = SUB_DRAINING
/**
* Create a properly formatted inbox subject.
*
* @api public
*/
const createInbox = exports.createInbox = function () {
return ('_INBOX.' + nuid.next())
}
/**
* Initialize a client with the appropriate options.
*
* @param {Object} [opts]
* @api public
*/
function Client (opts) {
events.EventEmitter.call(this)
this.parseOptions(opts)
this.initState()
this.createConnection()
}
/**
* Connect to a nats-server and return the client.
* Argument can be a url, or an object with a 'url'
* property and additional options.
*
* @params {Mixed} [url] - Url, port, or options object
* @params {Object} [opts] - Options
* @api public
*/
exports.connect = function (url, opts) {
// If we receive one parameter, parser will
// figure out intent. If we provided opts, then
// first parameter should be url, and second an
// options object.
if (opts !== undefined) {
if (typeof opts !== 'object') {
throw new NatsError(BAD_OPTIONS_MSG, BAD_OPTIONS)
}
opts.url = sanitizeUrl(url)
} else {
opts = url
}
return new Client(opts)
}
/**
* Connected clients are event emitters.
*/
util.inherits(Client, events.EventEmitter)
/**
* Allow createInbox to be called on a client.
*
* @api public
*/
Client.prototype.createInbox = createInbox
Client.prototype.assignOption = function (opts, prop, assign) {
if (assign === undefined) {
assign = prop
}
if (opts[prop] !== undefined) {
this.options[assign] = opts[prop]
}
}
function shuffle (array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
const temp = array[i]
array[i] = array[j]
array[j] = temp
}
return array
}
/**
* Parse the constructor/connect options.
*
* @param {Object} [opts]
* @api private
*/
Client.prototype.parseOptions = function (opts) {
const options = this.options = {
encoding: 'utf8',
maxPingOut: DEFAULT_MAX_PING_OUT,
maxReconnectAttempts: DEFAULT_MAX_RECONNECT_ATTEMPTS,
noEcho: false,
pedantic: false,
pingInterval: DEFAULT_PING_INTERVAL,
reconnect: true,
reconnectTimeWait: DEFAULT_RECONNECT_TIME_WAIT,
tls: false,
useOldRequestStyle: false,
verbose: false,
waitOnFirstConnect: false
}
if (undefined === opts) {
options.url = DEFAULT_URI
} else if (typeof opts === 'number') {
options.url = DEFAULT_PRE + opts
} else if (typeof opts === 'string') {
options.url = sanitizeUrl(opts)
} else if (typeof opts === 'object') {
if (opts.port !== undefined) {
options.url = DEFAULT_PRE + opts.port
}
// Pull out various options here
this.assignOption(opts, 'timeout')
this.assignOption(opts, 'encoding')
this.assignOption(opts, 'json')
this.assignOption(opts, 'maxPingOut')
this.assignOption(opts, 'maxReconnectAttempts')
this.assignOption(opts, 'name')
this.assignOption(opts, 'nkey')
this.assignOption(opts, 'noEcho')
this.assignOption(opts, 'noRandomize')
this.assignOption(opts, 'nonceSigner')
this.assignOption(opts, 'pass')
this.assignOption(opts, 'pedantic')
this.assignOption(opts, 'pingInterval')
this.assignOption(opts, 'preserveBuffers')
this.assignOption(opts, 'reconnect')
this.assignOption(opts, 'reconnectTimeWait')
this.assignOption(opts, 'servers')
this.assignOption(opts, 'tls')
this.assignOption(opts, 'token')
this.assignOption(opts, 'tokenHandler')
this.assignOption(opts, 'url')
this.assignOption(opts, 'useOldRequestStyle')
this.assignOption(opts, 'user')
this.assignOption(opts, 'userCreds')
this.assignOption(opts, 'userJWT')
this.assignOption(opts, 'verbose')
this.assignOption(opts, 'waitOnFirstConnect')
this.assignOption(opts, 'yieldTime')
// fixme: aliasing a configuration property name should be an error
this.assignOption(opts, 'client', 'name')
this.assignOption(opts, 'credentials', 'userCreds')
this.assignOption(opts, 'dontRandomize', 'noRandomize')
this.assignOption(opts, 'jwt', 'userJWT')
this.assignOption(opts, 'JWT', 'userJWT')
this.assignOption(opts, 'nkeys', 'nkey')
this.assignOption(opts, 'NoRandomize', 'noRandomize')
this.assignOption(opts, 'password', 'pass')
this.assignOption(opts, 'secure', 'tls')
this.assignOption(opts, 'sig', 'nonceSigner')
this.assignOption(opts, 'sigCB', 'nonceSigner')
this.assignOption(opts, 'sigCallback', 'nonceSigner')
this.assignOption(opts, 'sigcb', 'nonceSigner')
this.assignOption(opts, 'uri', 'url')
this.assignOption(opts, 'urls', 'servers')
this.assignOption(opts, 'usercreds', 'userCreds')
this.assignOption(opts, 'userjwt', 'userJWT')
}
// Set user/pass as needed if in options.
this.user = options.user
this.pass = options.pass
// Set token as needed if in options.
this.token = options.token
this.tokenHandler = options.tokenHandler
// Authentication - make sure authentication is valid.
if (this.user && this.token) {
throw (new NatsError(BAD_AUTHENTICATION_MSG, BAD_AUTHENTICATION))
}
if (this.tokenHandler && typeof this.tokenHandler !== 'function') {
throw (new NatsError(BAD_AUTHENTICATION_TH_NOT_FUNC_MSG, BAD_AUTHENTICATION))
}
if (this.tokenHandler && this.token) {
throw (new NatsError(BAD_AUTHENTICATION_T_AND_TH_MSG, BAD_AUTHENTICATION))
}
// Encoding - make sure its valid.
if (Buffer.isEncoding(options.encoding)) {
this.encoding = options.encoding
} else {
throw new NatsError(INVALID_ENCODING_MSG_PREFIX + options.encoding, INVALID_ENCODING)
}
// For cluster support
this.servers = []
if (Array.isArray(options.servers)) {
options.servers.forEach((server) => {
this.servers.push(new Server(new url.URL(server)))
})
// Randomize if needed
if (options.noRandomize !== true) {
shuffle(this.servers)
}
// if they gave an URL we should add it if different
if (options.url !== undefined && this.servers.indexOf(options.url) === -1) {
// Make url first element so it is attempted first
this.servers.unshift(new Server(new url.URL(options.url)))
}
} else {
if (undefined === options.url) {
options.url = DEFAULT_URI
}
this.servers.push(new Server(new url.URL(options.url)))
}
// If we are not setup for tls, but were handed a url with a tls:// prefix
// then upgrade to tls.
if (options.tls === false) {
this.servers.forEach((server) => {
if (server.url.protocol === 'tls' || server.url.protocol === 'tls:') {
options.tls = true
}
})
}
if (options.timeout && typeof options.timeout !== 'number') {
throw new NatsError('timeout should be a number', BAD_OPTIONS)
}
}
function sanitizeUrl (host) {
if ((/^.*:\/\/.*/).exec(host) === null) {
// Does not have a scheme.
host = 'nats://' + host
}
const u = new url.URL(host)
if (u.port === null || u.port === '') {
host += ':' + DEFAULT_PORT
}
return host
}
/**
* Create a new server.
*
* @api private
*/
function Server (url) {
this.url = url
this.didConnect = false
this.reconnects = 0
}
/**
* @api private
*/
Server.prototype.toString = function () {
return this.url.href
}
/**
* Properly select the next server.
* We rotate the server list as we go,
* we also pull auth from urls as needed, or
* if they were set in options use that as override.
*
* @api private
*/
Client.prototype.selectServer = function () {
const server = this.servers.shift()
// Place in client context.
this.currentServer = server
this.url = server.url
const un = server.url.username || ''
const pw = server.url.password || ''
let up = ''
if (un !== '' && pw !== '') {
up = un + ':' + pw
} else if (un !== '') {
up = un
}
if (up !== '') {
const auth = up.split(':')
if (auth.length !== 1) {
if (this.options.user === undefined) {
this.user = auth[0]
}
if (this.options.pass === undefined) {
this.pass = auth[1]
}
} else {
if (this.options.token === undefined) {
this.token = auth[0]
}
}
}
this.servers.push(server)
}
Client.prototype.checkNoEchoMismatch = function () {
if ((this.info.proto === undefined || this.info.proto < 1) && this.options.noEcho) {
this.emit('error', new NatsError(NO_ECHO_NOT_SUPPORTED_MSG, NO_ECHO_NOT_SUPPORTED))
this.closeStream()
return true
}
return false
}
/**
* Check for TLS configuration mismatch.
*
* @api private
*/
Client.prototype.checkTLSMismatch = function () {
// Switch over to TLS as needed on the fly.
if (this.info.tls_required === true ||
(this.options.tls !== false && this.stream.encrypted !== true)) {
if (undefined === this.options.tls || this.options.tls === false) {
this.options.tls = true
}
}
if (this.info.tls_required === true &&
this.options.tls === false) {
this.emit('error', new NatsError(SECURE_CONN_REQ_MSG, SECURE_CONN_REQ))
this.closeStream()
return true
}
if (!this.info.tls_required && this.options.tls !== false) {
this.emit('error', new NatsError(NON_SECURE_CONN_REQ_MSG, NON_SECURE_CONN_REQ))
this.closeStream()
return true
}
if (this.info.tls_verify === true &&
this.options.tls.cert === undefined) {
this.emit('error', new NatsError(CLIENT_CERT_REQ_MSG, CLIENT_CERT_REQ))
this.closeStream()
return true
}
return false
}
/**
* Load a user jwt from a chained credential file.
* @return {String | undefined}
* @emits NatsError if JWT couldn't be parsed
* @api private
*/
Client.prototype.loadUserJWT = function () {
const contents = fs.readFileSync(this.options.userCreds).toString()
const m = CREDS.exec(contents) // jwt
if (m === null) {
this.emit('error', new NatsError(NO_USER_JWT_IN_CREDS_MSG, NO_USER_JWT_IN_CREDS))
this.closeStream()
return
}
return m[1]
}
/**
* Load a user nkey seed from a chained credential file
* and sign nonce.
*
* @api private
*/
Client.prototype.loadKeyAndSignNonce = function (nonce) {
const contents = fs.readFileSync(this.options.userCreds).toString()
const re = new RegExp(CREDS.source, 'g')
re.exec(contents) // consume jwt
const m = re.exec(contents) // seed
if (m === null) {
this.emit('error', new NatsError(NO_SEED_IN_CREDS_MSG, NO_SEED_IN_CREDS))
this.closeStream()
return
}
const sk = nkeys.fromSeed(Buffer.from(m[1]))
return sk.sign(nonce)
}
/**
* Helper that takes a user credentials file and
* generates the proper opts object with proper handlers
* filled in. e.g nats.connect(url, nats.creds("my_creds.ttx")
*
* @params {String} [filepath]
*
* @api public
*/
exports.creds = function (filepath) {
if (undefined === filepath) {
return undefined
}
return {
userCreds: filepath
}
}
/**
* Check for Nkey mismatch.
*
* @api private
*/
Client.prototype.checkNkeyMismatch = function () {
if (undefined === this.info.nonce) {
return false
}
// If this has been specified make sure we can open the file and parse it.
if (this.options.userCreds !== undefined) {
// Treat this as a filename.
// For now we will not capture an error on file not found etc.
const contents = fs.readFileSync(this.options.userCreds).toString()
if (CREDS.exec(contents) === null) {
this.emit('error', new NatsError(BAD_CREDS_MSG, BAD_CREDS))
this.closeStream()
return true
}
// We have a valid file, set up callback handlers.
const client = this
this.options.nonceSigner = function (nonce) {
return client.loadKeyAndSignNonce(nonce)
}
this.options.userJWT = function () {
return client.loadUserJWT()
}
return false
}
if (undefined === this.options.nonceSigner) {
this.emit('error', new NatsError(SIGNATURE_REQUIRED_MSG, SIGNATURE_REQUIRED))
this.closeStream()
return true
}
if (typeof (this.options.nonceSigner) !== 'function') {
this.emit('error', new NatsError(SIGCB_NOTFUNC_MSG, SIGCB_NOTFUNC))
this.closeStream()
return true
}
if (undefined === this.options.nkey && undefined === this.options.userJWT) {
this.emit('error', new NatsError(NKEY_OR_JWT_REQ_MSG, NKEY_OR_JWT_REQ))
this.closeStream()
return true
}
return false
}
/**
* Callback for first flush/connect.
*
* @api private
*/
Client.prototype.connectCB = function () {
const wasReconnecting = this.reconnecting
const event = (wasReconnecting === true) ? 'reconnect' : 'connect'
this.reconnecting = false
this.reconnects = 0
this.wasConnected = true
this.currentServer.didConnect = true
this.emit(event, this)
this.flushPending()
}
/**
* @api private
*/
Client.prototype.cancelHeartbeat = function () {
if (this.pingTimer) {
clearTimeout(this.pingTimer)
delete this.pingTimer
}
}
/**
* @api private
*/
Client.prototype.scheduleHeartbeat = function () {
this.pingTimer = setTimeout(function (client) {
client.emit('pingtimer')
if (client.closed) {
return
}
// we could be waiting on the socket to connect
if (client.stream && !client.stream.connecting) {
client.emit('pingcount', client.pout)
client.pout++
if (client.pout > client.options.maxPingOut) {
// processErr will scheduleReconnect
client.processErr(STALE_CONNECTION_ERR)
// don't reschedule, new connection initiated
return
} else {
// send the ping
client.sendCommand(PING_REQUEST)
if (client.pongs) {
// no callback
client.pongs.push(undefined)
}
}
}
// reschedule
client.scheduleHeartbeat()
}, this.options.pingInterval, this)
}
/**
* Properly setup a stream event handlers.
*
* @api private
*/
Client.prototype.setupHandlers = function () {
const stream = this.stream
if (undefined === stream) {
return
}
if (this.options.timeout) {
this.connectionTimeoutHandler = setTimeout(() => {
stream.destroy(new NatsError(CONN_TIMEOUT_MSG, CONN_TIMEOUT))
}, this.options.timeout)
}
stream.on('connect', () => {
this.cancelHeartbeat()
this.connected = true
this.scheduleHeartbeat()
})
stream.on('close', () => {
this.closeStream()
if (stream.bytesRead > 0) {
this.emit('disconnect')
}
if (this.closed === true ||
this.options.reconnect === false ||
((this.reconnects >= this.options.maxReconnectAttempts) && this.options.maxReconnectAttempts !== -1)) {
this.cleanupTimers()
this.emit('close')
} else {
this.scheduleReconnect()
}
})
stream.on('error', (exception) => {
// If we were connected just return, close event will process
if (this.wasConnected === true && this.currentServer.didConnect === true) {
return
}
// if the current server did not connect at all, and we in
// general have not connected to any server, remove it from
// this list. Unless overridden
if (this.wasConnected === false && this.currentServer.didConnect === false) {
// We can override this behavior with waitOnFirstConnect, which will
// treat it like a reconnect scenario.
if (this.options.waitOnFirstConnect) {
// Pretend to move us into a reconnect state.
this.currentServer.didConnect = true
} else {
this.servers.splice(this.servers.length - 1, 1)
}
}
// Only bubble up error if we never had connected
// to the server and we only have one, and close
if (this.wasConnected === false && this.servers.length === 0) {
this.emit('error', new NatsError(CONN_ERR_MSG_PREFIX + exception, CONN_ERR, exception))
this.close()
return
}
// continue with reconnect
this.closeStream()
})
stream.on('data', (data) => {
// If inbound exists, concat them together. We try to avoid this for split
// messages, so this should only really happen for a split control line.
// Long term answer is hand rolled parser and not regexp.
if (this.inbound) {
this.inbound = Buffer.concat([this.inbound, data])
} else {
this.inbound = data
}
// Process the inbound queue.
this.processInbound()
})
}
/**
* Send the connect command. This needs to happen after receiving the first
* INFO message and after TLS is established if necessary.
*
* @api private
*/
Client.prototype.sendConnect = function () {
// Queue the connect command.
const cs = {
lang: 'node',
version: VERSION,
verbose: this.options.verbose,
pedantic: this.options.pedantic,
protocol: 1
}
if (this.info.nonce !== undefined && this.options.nonceSigner !== undefined) {
const sig = this.options.nonceSigner(Buffer.from(this.info.nonce))
cs.sig = sig.toString('base64')
}
if (this.options.userJWT !== undefined) {
if (typeof (this.options.userJWT) === 'function') {
cs.jwt = this.options.userJWT()
} else {
cs.jwt = this.options.userJWT
}
}
if (this.options.nkey !== undefined) {
cs.nkey = this.options.nkey
}
if (this.user !== undefined) {
cs.user = this.user
cs.pass = this.pass
}
if (this.tokenHandler !== undefined) {
let token
try {
token = this.tokenHandler()
} catch (err) {
this.emit('error', new NatsError(BAD_AUTHENTICATION_TH_FAILED_MSG_PREFIX + err, BAD_AUTHENTICATION, err))
}
cs.auth_token = token
} else if (this.token !== undefined) {
cs.auth_token = this.token
}
if (this.options.name !== undefined) {
cs.name = this.options.name
}
if (this.options.nkey !== undefined) {
cs.nkey = this.options.nkey
}
if (this.options.noEcho) {
cs.echo = false
}
// If we enqueued requests before we received INFO from the server, or we
// reconnected, there be other data pending, write this immediately instead
// of adding it to the queue.
this.stream.write(CONNECT + SPC + JSON.stringify(cs) + CR_LF)
}
/**
* Properly setup a stream connection with proper events.
*
* @api private
*/
Client.prototype.createConnection = function () {
// Commands may have been queued during reconnect. Discard everything except:
// 1) ping requests with a pong callback
// 2) publish requests
//
// Rationale: CONNECT and SUBs are written directly upon connecting, any PONG
// response is no longer relevant, and any UNSUB will be accounted for when we
// sync our SUBs. Without this, users of the client may miss state transitions
// via callbacks, would have to track the client's internal connection state,
// and may have to double buffer messages (which we are already doing) if they
// wanted to ensure their messages reach the server.
const pong = []
const pend = []
let pSize = 0
if (this.pending !== null) {
let pongIndex = 0
this.pending.forEach((cmd) => {
const cmdLen = Buffer.isBuffer(cmd) ? cmd.length : Buffer.byteLength(cmd)
if (cmd === PING_REQUEST && this.pongs !== null && pongIndex < this.pongs.length) {
// filter out any useless ping requests (no pong callback, nop flush)
const p = this.pongs[pongIndex++]
if (p !== undefined) {
pend.push(cmd)
pSize += cmdLen
pong.push(p)
}
} else if (cmd.length > 3 && cmd[0] === 'P' && cmd[1] === 'U' && cmd[2] === 'B') {
pend.push(cmd)
pSize += cmdLen
}
})
}
this.pongs = pong
this.pending = pend
this.pSize = pSize
this.pstate = AWAITING_CONTROL
// Clear info processing.
this.info = null
this.infoReceived = false
// Select a server to connect to.
this.selectServer()
// See #45 if we have a stream release the listeners otherwise in addition
// to the leaking of events, the old events will still fire.
if (this.stream) {
this.stream.removeAllListeners()
this.stream.destroy()
}
// Create the stream
this.stream = net.createConnection(this.url.port, this.url.hostname)
// this change makes it a bit faster on Linux, slightly worse on OS X
this.stream.setNoDelay(true)
// Setup the proper handlers.
this.setupHandlers()
}
/**
* Initialize client state.
*
* @api private
*/
Client.prototype.initState = function () {
this.ssid = 1
this.subs = {}
this.reconnects = 0
this.connected = false
this.wasConnected = false
this.reconnecting = false
this.server = null
this.pending = []
this.pout = 0
}
/**
* Close the connection to the server.
*
* @api public
*/
Client.prototype.close = function () {
this.cleanupTimers()
this.closed = true
this.removeAllListeners()
this.closeStream()
this.ssid = -1
this.subs = null
this.pstate = -1
this.pongs = null
this.pending = null
this.pSize = 0
}
/**
* Cancels all the timers, ping, subs, requests.
* Should only be called on a close.
* @api private
*/
Client.prototype.cleanupTimers = function () {
this.cancelHeartbeat()
if (this.respmux && this.respmux.requestMap) {
for (const p in this.respmux.requestMap) {
if (Object.hasOwnProperty.call(this.respmux.requestMap, p)) {
this.cancelMuxRequest(p)
}
}
}
if (this.subs) {
for (const p in this.subs) {
if (Object.hasOwnProperty.call(this.subs, p)) {
const sub = this.subs[p]
if (sub.timeout) {
clearTimeout(sub.timeout)
delete sub.timeout
}
}
}
}
}
/**
* Close down the stream and clear state.
*
* @api private
*/
Client.prototype.closeStream = function () {
if (this.stream !== null) {
this.stream.destroy()
this.stream = null
}
if (this.connected === true || this.closed === true) {
this.pongs = null
this.pout = 0
this.pending = null
this.pSize = 0
this.connected = false
}
this.inbound = null
}
/**
* Flush all pending data to the server.
*
* @api private
*/
Client.prototype.flushPending = function () {
if (this.connected === false ||
this.pending === null ||
this.pending.length === 0 ||
this.infoReceived !== true) {
return