forked from nats-io/nats.go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nats.go
1817 lines (1565 loc) · 41.7 KB
/
nats.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2015 Apcera Inc. All rights reserved.
// A Go client for the NATS messaging system (https://nats.io).
package nats
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/tls"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
mrand "math/rand"
)
const (
Version = "1.1.4"
DefaultURL = "nats://localhost:4222"
DefaultPort = 4222
DefaultMaxReconnect = 60
DefaultReconnectWait = 2 * time.Second
DefaultTimeout = 2 * time.Second
DefaultPingInterval = 2 * time.Minute
DefaultMaxPingOut = 2
DefaultMaxChanLen = 65536
RequestChanLen = 4
LangString = "go"
)
// For detection and proper handling of a Stale Connection
const STALE_CONNECTION = "Stale Connection"
var (
ErrConnectionClosed = errors.New("nats: Connection Closed")
ErrSecureConnRequired = errors.New("nats: Secure Connection required")
ErrSecureConnWanted = errors.New("nats: Secure Connection not available")
ErrSecureConnFailed = errors.New("nats: Secure Connection failed")
ErrBadSubscription = errors.New("nats: Invalid Subscription")
ErrBadSubject = errors.New("nats: Invalid Subject")
ErrSlowConsumer = errors.New("nats: Slow Consumer, messages dropped")
ErrTimeout = errors.New("nats: Timeout")
ErrBadTimeout = errors.New("nats: Timeout Invalid")
ErrAuthorization = errors.New("nats: Authorization Failed")
ErrNoServers = errors.New("nats: No servers available for connection")
ErrJsonParse = errors.New("nats: Connect message, json parse err")
ErrChanArg = errors.New("nats: Argument needs to be a channel type")
ErrStaleConnection = errors.New("nats: " + STALE_CONNECTION)
ErrMaxPayload = errors.New("nats: Maximum Payload Exceeded")
)
var DefaultOptions = Options{
AllowReconnect: true,
MaxReconnect: DefaultMaxReconnect,
ReconnectWait: DefaultReconnectWait,
Timeout: DefaultTimeout,
PingInterval: DefaultPingInterval,
MaxPingsOut: DefaultMaxPingOut,
SubChanLen: DefaultMaxChanLen,
}
type Status int
const (
DISCONNECTED = Status(iota)
CONNECTED
CLOSED
RECONNECTING
CONNECTING
)
// ConnHandlers are used for asynchronous events such as
// disconnected and closed connections.
type ConnHandler func(*Conn)
// ErrHandlers are used to process asynchronous errors encountered
// while processing inbound messages.
type ErrHandler func(*Conn, *Subscription, error)
// Options can be used to create a customized Connection.
type Options struct {
Url string
Servers []string
NoRandomize bool
Name string
Verbose bool
Pedantic bool
Secure bool
TLSConfig *tls.Config
AllowReconnect bool
MaxReconnect int
ReconnectWait time.Duration
Timeout time.Duration
ClosedCB ConnHandler
DisconnectedCB ConnHandler
ReconnectedCB ConnHandler
AsyncErrorCB ErrHandler
PingInterval time.Duration // disabled if 0 or negative
MaxPingsOut int
// The size of the buffered channel used between the socket
// Go routine and the message delivery or sync subscription.
SubChanLen int
}
const (
// Scratch storage for assembling protocol headers
scratchSize = 512
// The size of the bufio reader/writer on top of the socket.
defaultBufSize = 32768
// The size of the bufio while we are reconnecting
defaultPendingSize = 1024 * 1024
// The buffered size of the flush "kick" channel
flushChanSize = 1024
// Default server pool size
srvPoolSize = 4
)
// A Conn represents a bare connection to a nats-server. It will send and receive
// []byte payloads.
type Conn struct {
Statistics
mu sync.Mutex
Opts Options
wg sync.WaitGroup
url *url.URL
conn net.Conn
srvPool []*srv
bw *bufio.Writer
pending *bytes.Buffer
fch chan bool
info serverInfo
_ uint32 // needed to correctly align the following ssid field on i386 systems
ssid int64
subs map[int64]*Subscription
mch chan *Msg
pongs []chan bool
scratch [scratchSize]byte
status Status
err error
ps *parseState
ptmr *time.Timer
pout int
}
// A Subscription represents interest in a given subject.
type Subscription struct {
mu sync.Mutex
sid int64
// Subject that represents this subscription. This can be different
// than the received subject inside a Msg if this is a wildcard.
Subject string
// Optional queue group name. If present, all subscriptions with the
// same name will form a distributed queue, and each message will
// only be processed by one member of the group.
Queue string
msgs uint64
delivered uint64
bytes uint64
max uint64
conn *Conn
closed bool
mcb MsgHandler
mch chan *Msg
sc bool
}
// Msg is a structure used by Subscribers and PublishMsg().
type Msg struct {
Subject string
Reply string
Data []byte
Sub *Subscription
}
// Tracks various stats received and sent on this connection,
// including counts for messages and bytes.
type Statistics struct {
InMsgs uint64
OutMsgs uint64
InBytes uint64
OutBytes uint64
Reconnects uint64
}
// Tracks individual backend servers.
type srv struct {
url *url.URL
didConnect bool
reconnects int
lastAttempt time.Time
}
type serverInfo struct {
Id string `json:"server_id"`
Host string `json:"host"`
Port uint `json:"port"`
Version string `json:"version"`
AuthRequired bool `json:"auth_required"`
TLSRequired bool `json:"ssl_required"`
MaxPayload int64 `json:"max_payload"`
}
type connectInfo struct {
Verbose bool `json:"verbose"`
Pedantic bool `json:"pedantic"`
User string `json:"user,omitempty"`
Pass string `json:"pass,omitempty"`
Ssl bool `json:"ssl_required"`
Name string `json:"name"`
Lang string `json:"lang"`
Version string `json:"version"`
}
// MsgHandler is a callback function that processes messages delivered to
// asynchronous subscribers.
type MsgHandler func(msg *Msg)
// Connect will attempt to connect to the NATS server.
// The url can contain username/password semantics.
func Connect(url string) (*Conn, error) {
opts := DefaultOptions
opts.Url = url
return opts.Connect()
}
// SecureConnect will attempt to connect to the NATS server using TLS.
// The url can contain username/password semantics.
func SecureConnect(url string) (*Conn, error) {
opts := DefaultOptions
opts.Url = url
opts.Secure = true
return opts.Connect()
}
// Connect will attempt to connect to a NATS server with multiple options.
func (o Options) Connect() (*Conn, error) {
nc := &Conn{Opts: o}
if nc.Opts.MaxPingsOut == 0 {
nc.Opts.MaxPingsOut = DefaultMaxPingOut
}
// Allow old default for channel length to work correctly.
if nc.Opts.SubChanLen == 0 {
nc.Opts.SubChanLen = DefaultMaxChanLen
}
if err := nc.setupServerPool(); err != nil {
return nil, err
}
if err := nc.connect(); err != nil {
return nil, err
}
return nc, nil
}
const (
_CRLF_ = "\r\n"
_EMPTY_ = ""
_SPC_ = " "
_PUB_P_ = "PUB "
)
const (
_OK_OP_ = "+OK"
_ERR_OP_ = "-ERR"
_MSG_OP_ = "MSG"
_PING_OP_ = "PING"
_PONG_OP_ = "PONG"
_INFO_OP_ = "INFO"
)
const (
conProto = "CONNECT %s" + _CRLF_
pingProto = "PING" + _CRLF_
pongProto = "PONG" + _CRLF_
pubProto = "PUB %s %s %d" + _CRLF_
subProto = "SUB %s %s %d" + _CRLF_
unsubProto = "UNSUB %d %s" + _CRLF_
)
func (nc *Conn) debugPool(str string) {
_, cur := nc.currentServer()
fmt.Printf("%s\n", str)
for i, s := range nc.srvPool {
if s == cur {
fmt.Printf("\t*%d: %v\n", i+1, s.url)
} else {
fmt.Printf("\t%d: %v\n", i+1, s.url)
}
}
}
// Return the currently selected server
func (nc *Conn) currentServer() (int, *srv) {
for i, s := range nc.srvPool {
if s == nil {
continue
}
if s.url == nc.url {
return i, s
}
}
return -1, nil
}
// Pop the current server and put onto the end of the list. Select head of list as long
// as number of reconnect attempts under MaxReconnect.
func (nc *Conn) selectNextServer() (*srv, error) {
i, s := nc.currentServer()
if i < 0 {
return nil, ErrNoServers
}
sp := nc.srvPool
num := len(sp)
copy(sp[i:num-1], sp[i+1:num])
max_reconnect := nc.Opts.MaxReconnect
if max_reconnect < 0 || s.reconnects < max_reconnect {
nc.srvPool[num-1] = s
} else {
nc.srvPool = sp[0 : num-1]
}
if len(nc.srvPool) <= 0 {
nc.url = nil
return nil, ErrNoServers
}
nc.url = nc.srvPool[0].url
return nc.srvPool[0], nil
}
// Will assign the correct server to the nc.Url
func (nc *Conn) pickServer() error {
nc.url = nil
if len(nc.srvPool) <= 0 {
return ErrNoServers
}
for _, s := range nc.srvPool {
if s != nil {
nc.url = s.url
return nil
}
}
return ErrNoServers
}
// Create the server pool using the options given.
// We will place a Url option first, followed by any
// Server Options. We will randomize the server pool unlesss
// the NoRandomize flag is set.
func (nc *Conn) setupServerPool() error {
nc.srvPool = make([]*srv, 0, srvPoolSize)
if nc.Opts.Url != _EMPTY_ {
u, err := url.Parse(nc.Opts.Url)
if err != nil {
return err
}
s := &srv{url: u}
nc.srvPool = append(nc.srvPool, s)
}
var srvrs []string
source := mrand.NewSource(time.Now().UnixNano())
r := mrand.New(source)
if nc.Opts.NoRandomize {
srvrs = nc.Opts.Servers
} else {
in := r.Perm(len(nc.Opts.Servers))
for _, i := range in {
srvrs = append(srvrs, nc.Opts.Servers[i])
}
}
for _, urlString := range srvrs {
u, err := url.Parse(urlString)
if err != nil {
return err
}
s := &srv{url: u}
nc.srvPool = append(nc.srvPool, s)
}
// Place default URL if pool is empty.
if len(nc.srvPool) <= 0 {
u, err := url.Parse(DefaultURL)
if err != nil {
return err
}
s := &srv{url: u}
nc.srvPool = append(nc.srvPool, s)
}
return nc.pickServer()
}
// createConn will connect to the server and wrap the appropriate
// bufio structures. It will do the right thing when an existing
// connection is in place.
func (nc *Conn) createConn() (err error) {
if nc.Opts.Timeout < 0 {
return ErrBadTimeout
}
if _, cur := nc.currentServer(); cur == nil {
return ErrNoServers
} else {
cur.lastAttempt = time.Now()
}
nc.conn, err = net.DialTimeout("tcp", nc.url.Host, nc.Opts.Timeout)
if err != nil {
return err
}
// No clue why, but this stalls and kills performance on Mac (Mavericks).
// https://code.google.com/p/go/issues/detail?id=6930
//if ip, ok := nc.conn.(*net.TCPConn); ok {
// ip.SetReadBuffer(defaultBufSize)
//}
if nc.pending != nil && nc.bw != nil {
// Move to pending buffer.
nc.bw.Flush()
}
nc.bw = bufio.NewWriterSize(nc.conn, defaultBufSize)
return nil
}
// makeTLSConn will wrap an existing Conn using TLS
func (nc *Conn) makeTLSConn() {
// Allow the user to configure their own tls.Config structure, otherwise
// default to InsecureSkipVerify.
// TODO(dlc) - We should make the more secure version the default.
if nc.Opts.TLSConfig != nil {
nc.conn = tls.Client(nc.conn, nc.Opts.TLSConfig)
} else {
nc.conn = tls.Client(nc.conn, &tls.Config{InsecureSkipVerify: true})
}
nc.bw = bufio.NewWriterSize(nc.conn, defaultBufSize)
}
// waitForExits will wait for all socket watcher Go routines to
// be shutdown before proceeding.
func (nc *Conn) waitForExits() {
// Kick old flusher forcefully.
select {
case nc.fch <- true:
default:
}
// Wait for any previous go routines.
nc.wg.Wait()
}
// spinUpSocketWatchers will launch the Go routines responsible for
// reading and writing to the socket. This will be launched via a
// go routine itself to release any locks that may be held.
// We also use a WaitGroup to make sure we only start them on a
// reconnect when the previous ones have exited.
func (nc *Conn) spinUpSocketWatchers() {
// Make sure everything has exited.
nc.waitForExits()
// We will wait on both going forward.
nc.wg.Add(2)
// Spin up the readLoop and the socket flusher.
go nc.readLoop()
go nc.flusher()
nc.mu.Lock()
if nc.Opts.PingInterval > 0 {
if nc.ptmr == nil {
nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer)
} else {
nc.ptmr.Reset(nc.Opts.PingInterval)
}
}
nc.mu.Unlock()
}
// Report the connected server's Url
func (nc *Conn) ConnectedUrl() string {
nc.mu.Lock()
defer nc.mu.Unlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.url.String()
}
// Report the connected server's Id
func (nc *Conn) ConnectedServerId() string {
nc.mu.Lock()
defer nc.mu.Unlock()
if nc.status != CONNECTED {
return _EMPTY_
}
return nc.info.Id
}
// Low level setup for structs, etc
func (nc *Conn) setup() {
nc.subs = make(map[int64]*Subscription)
nc.pongs = make([]chan bool, 0, 8)
nc.fch = make(chan bool, flushChanSize)
// Setup scratch outbound buffer for PUB
pub := nc.scratch[:len(_PUB_P_)]
copy(pub, _PUB_P_)
}
// Process a connected connection and initialize properly.
func (nc *Conn) processConnectInit() error {
// Set out deadline for the whole connect process
nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout))
defer nc.conn.SetDeadline(time.Time{})
// Set our status to connecting.
nc.status = CONNECTING
// Process the INFO protocol received from the server
err := nc.processExpectedInfo()
if err != nil {
return err
}
// Send the CONNECT protocol along with the initial PING protocol.
// Wait for the PONG response (or any error that we get from the server).
err = nc.sendConnect()
if err != nil {
return err
}
// Reset the number of PING sent out
nc.pout = 0
go nc.spinUpSocketWatchers()
return nil
}
// Main connect function. Will connect to the nats-server
func (nc *Conn) connect() error {
// Create actual socket connection
// For first connect we walk all servers in the pool and try
// to connect immediately.
nc.mu.Lock()
for i := range nc.srvPool {
nc.url = nc.srvPool[i].url
if err := nc.createConn(); err == nil {
// This was moved out of processConnectInit() because
// that function is now invoked from doReconnect() too.
nc.setup()
err = nc.processConnectInit()
if err == nil {
nc.srvPool[i].didConnect = true
nc.srvPool[i].reconnects = 0
break
} else {
nc.err = err
nc.mu.Unlock()
nc.close(DISCONNECTED, false)
nc.mu.Lock()
nc.url = nil
}
} else {
// Cancel out default connection refused, will trigger the
// No servers error conditional
if matched, _ := regexp.Match(`connection refused`, []byte(err.Error())); matched {
nc.err = nil
}
}
}
defer nc.mu.Unlock()
if nc.err == nil && nc.status != CONNECTED {
nc.err = ErrNoServers
}
return nc.err
}
// This will check to see if the connection should be
// secure. This can be dictated from either end and should
// only be called after the INIT protocol has been received.
func (nc *Conn) checkForSecure() error {
// Check to see if we need to engage TLS
o := nc.Opts
// Check for mismatch in setups
if o.Secure && !nc.info.TLSRequired {
return ErrSecureConnWanted
} else if nc.info.TLSRequired && !o.Secure {
return ErrSecureConnRequired
}
// Need to rewrap with bufio
if o.Secure {
nc.makeTLSConn()
}
return nil
}
// processExpectedInfo will look for the expected first INFO message
// sent when a connection is established. The lock should be held entering.
func (nc *Conn) processExpectedInfo() error {
c := &control{}
// Read the protocol
err := nc.readOp(c)
if err != nil {
return err
}
// The nats protocol should send INFO first always.
if c.op != _INFO_OP_ {
return errors.New("nats: Protocol exception, INFO not received")
}
// Parse the protocol
nc.processInfo(c.args)
err = nc.checkForSecure()
if err != nil {
return err
}
return nil
}
// Sends a protocol control message by queueing into the bufio writer
// and kicking the flush Go routine. These writes are protected.
func (nc *Conn) sendProto(proto string) {
nc.mu.Lock()
nc.bw.WriteString(proto)
nc.kickFlusher()
nc.mu.Unlock()
}
// Generate a connect protocol message, issuing user/password if
// applicable. The lock is assumed to be held upon entering.
func (nc *Conn) connectProto() (string, error) {
o := nc.Opts
var user, pass string
u := nc.url.User
if u != nil {
user = u.Username()
pass, _ = u.Password()
}
cinfo := connectInfo{o.Verbose, o.Pedantic, user, pass,
o.Secure, o.Name, LangString, Version}
b, err := json.Marshal(cinfo)
if err != nil {
nc.err = ErrJsonParse
return _EMPTY_, nc.err
}
return fmt.Sprintf(conProto, b), nil
}
// Send a connect protocol message to the server, issue user/password if
// applicable. Will wait for a flush to return from the server for error
// processing.
func (nc *Conn) sendConnect() error {
// Construct the CONNECT protocol string
cProto, err := nc.connectProto()
if err != nil {
return err
}
// Write the protocol into the buffer
_, err = nc.bw.WriteString(cProto)
if err != nil {
return err
}
// Add to the buffer the PING protocol
_, err = nc.bw.WriteString(pingProto)
if err != nil {
return err
}
// Flush the buffer
err = nc.bw.Flush()
if err != nil {
return err
}
// Now read the response from the server.
br := bufio.NewReaderSize(nc.conn, defaultBufSize)
line, err := br.ReadString('\n')
if err != nil {
return err
}
// We expect a PONG
if line != pongProto {
// But it could be something else, like -ERR
if strings.HasPrefix(line, _ERR_OP_) {
return errors.New("nats: " + strings.TrimPrefix(line, _ERR_OP_))
} else if strings.HasPrefix(err.Error(), "tls: ") {
// Or a TLS error:
return ErrSecureConnFailed
}
return errors.New("nats: " + line)
}
// This is where we are truly connected.
nc.status = CONNECTED
return nil
}
// A control protocol line.
type control struct {
op, args string
}
// Read a control line and process the intended op.
func (nc *Conn) readOp(c *control) error {
br := bufio.NewReaderSize(nc.conn, defaultBufSize)
line, err := br.ReadString('\n')
if err != nil {
return err
}
parseControl(line, c)
return nil
}
// Parse a control line from the server.
func parseControl(line string, c *control) {
toks := strings.SplitN(line, _SPC_, 2)
if len(toks) == 1 {
c.op = strings.TrimSpace(toks[0])
c.args = _EMPTY_
} else if len(toks) == 2 {
c.op, c.args = strings.TrimSpace(toks[0]), strings.TrimSpace(toks[1])
} else {
c.op = _EMPTY_
}
}
func (nc *Conn) processDisconnect() {
nc.status = DISCONNECTED
if nc.err != nil {
return
}
if nc.info.TLSRequired {
nc.err = ErrSecureConnRequired
} else {
nc.err = ErrConnectionClosed
}
}
// flushReconnectPending will push the pending items that were
// gathered while we were in a RECONNECTING state to the socket.
func (nc *Conn) flushReconnectPendingItems() {
if nc.pending == nil {
return
}
if nc.pending.Len() > 0 {
nc.bw.Write(nc.pending.Bytes())
}
}
// Try to reconnect using the option parameters.
// This function assumes we are allowed to reconnect.
func (nc *Conn) doReconnect() {
// We want to make sure we have the other watchers shutdown properly
// here before we proceed past this point.
nc.waitForExits()
// FIXME(dlc) - We have an issue here if we have
// outstanding flush points (pongs) and they were not
// sent out, but are still in the pipe.
// Hold the lock manually and release where needed below,
// can't do defer here.
nc.mu.Lock()
// Create a new pending buffer to underpin the bufio Writer while
// we are reconnecting.
nc.pending = &bytes.Buffer{}
nc.bw = bufio.NewWriterSize(nc.pending, defaultPendingSize)
// Clear any errors.
nc.err = nil
// Perform appropriate callback if needed for a disconnect.
dcb := nc.Opts.DisconnectedCB
if dcb != nil {
nc.mu.Unlock()
dcb(nc)
nc.mu.Lock()
}
for len(nc.srvPool) > 0 {
cur, err := nc.selectNextServer()
if err != nil {
nc.err = err
break
}
// Sleep appropriate amount of time before the
// connection attempt if connecting to same server
// we just got disconnected from..
if time.Since(cur.lastAttempt) < nc.Opts.ReconnectWait {
sleepTime := nc.Opts.ReconnectWait - time.Since(cur.lastAttempt)
nc.mu.Unlock()
time.Sleep(sleepTime)
nc.mu.Lock()
}
// Check if we have been closed first.
if nc.isClosed() {
break
}
// Mark that we tried a reconnect
cur.reconnects += 1
// Try to create a new connection
err = nc.createConn()
// Not yet connected, retry...
// Continue to hold the lock
if err != nil {
nc.err = nil
continue
}
// We are reconnected
nc.Reconnects += 1
// Clear out server stats for the server we connected to..
cur.didConnect = true
cur.reconnects = 0
// Process connect logic
if nc.err = nc.processConnectInit(); nc.err != nil {
nc.status = RECONNECTING
continue
}
// Send existing subscription state
nc.resendSubscriptions()
// Now send off and clear pending buffer
nc.flushReconnectPendingItems()
// Flush the buffer
nc.err = nc.bw.Flush()
if nc.err != nil {
nc.status = RECONNECTING
continue
}
// Done with the pending buffer
nc.pending = nil
// This is where we are truly connected.
nc.status = CONNECTED
// snapshot the reconnect callback while lock is held.
rcb := nc.Opts.ReconnectedCB
// Release lock here, we will return below.
nc.mu.Unlock()
// Make sure to flush everything
nc.Flush()
// Call reconnectedCB if appropriate. We are already in a
// separate Go routine here, so ok to call direct.
if rcb != nil {
rcb(nc)
}
return
}
// Call into close.. We have no servers left..
if nc.err == nil {
nc.err = ErrNoServers
}
nc.mu.Unlock()
nc.Close()
}
// processOpErr handles errors from reading or parsing the protocol.
// The lock should not be held entering this function.
func (nc *Conn) processOpErr(err error) {
nc.mu.Lock()
if nc.isConnecting() || nc.isClosed() || nc.isReconnecting() {
nc.mu.Unlock()
return
}
if nc.Opts.AllowReconnect && nc.status == CONNECTED {
// Set our new status
nc.status = RECONNECTING
if nc.ptmr != nil {
nc.ptmr.Stop()
}
if nc.conn != nil {
nc.bw.Flush()
nc.conn.Close()
nc.conn = nil
}
go nc.doReconnect()
nc.mu.Unlock()
return
} else {
nc.processDisconnect()
nc.err = err
nc.mu.Unlock()
nc.Close()
}
}
// readLoop() will sit on the socket reading and processing the
// protocol from the server. It will dispatch appropriately based
// on the op type.
func (nc *Conn) readLoop() {
// Release the wait group on exit
defer nc.wg.Done()
// Create a parseState if needed.
nc.mu.Lock()
if nc.ps == nil {
nc.ps = &parseState{}
}
nc.mu.Unlock()
// Stack based buffer.
b := make([]byte, defaultBufSize)
for {
// FIXME(dlc): RWLock here?
nc.mu.Lock()
sb := nc.isClosed() || nc.isReconnecting()
if sb {
nc.ps = &parseState{}
}
conn := nc.conn
nc.mu.Unlock()
if sb || conn == nil {
break
}
n, err := conn.Read(b)
if err != nil {
nc.processOpErr(err)
break
}
if err := nc.parse(b[:n]); err != nil {
nc.processOpErr(err)
break
}
}
// Clear the parseState here..
nc.mu.Lock()
nc.ps = nil
nc.mu.Unlock()
}
// deliverMsgs waits on the delivery channel shared with readLoop and processMsg.
// It is used to deliver messages to asynchronous subscribers.
func (nc *Conn) deliverMsgs(s *Subscription) {
var closed bool
var delivered uint64
var max uint64
s.mu.Lock()
mcb := s.mcb