forked from nats-io/nats.go
-
Notifications
You must be signed in to change notification settings - Fork 3
/
nats.go
1189 lines (1037 loc) · 28.3 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 Apcera Inc. All rights reserved.
// A Go client for the NATS messaging system (https://github.com/derekcollison/nats).
package nats
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/tls"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/url"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
)
const (
Version = "0.72"
DefaultURL = "nats://localhost:4222"
DefaultPort = 4222
DefaultMaxReconnect = 10
DefaultReconnectWait = 2 * time.Second
DefaultTimeout = 2 * time.Second
)
var (
ErrConnectionClosed = errors.New("nats: Connection closed")
ErrSecureConnRequired = errors.New("nats: Secure connection required")
ErrSecureConnWanted = errors.New("nats: Secure connection not available")
ErrBadSubscription = errors.New("nats: Invalid Subscription")
ErrSlowConsumer = errors.New("nats: Slow consumer, messages dropped")
ErrTimeout = errors.New("nats: Timeout")
)
var DefaultOptions = Options{
AllowReconnect: true,
MaxReconnect: DefaultMaxReconnect,
ReconnectWait: DefaultReconnectWait,
Timeout: DefaultTimeout,
}
type Status int
const (
DISCONNECTED = Status(iota)
CONNECTED
CLOSED
RECONNECTING
)
// 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
Verbose bool
Pedantic bool
Secure bool
AllowReconnect bool
MaxReconnect uint
ReconnectWait time.Duration
Timeout time.Duration
ClosedCB ConnHandler
DisconnectedCB ConnHandler
ReconnectedCB ConnHandler
AsyncErrorCB ErrHandler
}
const (
// The size of the buffered channel used between the socket
// Go routine and the message delivery or sync subscription.
maxChanLen = 8192
// 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
)
// A Conn represents a bare connection to a nats-server. It will send and receive
// []byte payloads.
type Conn struct {
Stats
mu sync.Mutex
Opts Options
url *url.URL
conn net.Conn
bw *bufio.Writer
// br *bufio.Reader
pending *bytes.Buffer
fch chan bool
info serverInfo
ssid int64
subs map[int64]*Subscription
mch chan *Msg
pongs []chan bool
scratch [scratchSize]byte
status Status
err error
ps parseState
}
// 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
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 Stats struct {
InMsgs uint64
OutMsgs uint64
InBytes uint64
OutBytes uint64
Reconnects uint64
}
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"`
SslRequired 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"`
}
// 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}
var err error
nc.url, err = url.Parse(o.Url)
if err != nil {
return nil, err
}
err = nc.connect()
if 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_
)
// 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() error {
// FIXME: Check for 0 Timeout
nc.conn, nc.err = net.DialTimeout("tcp", nc.url.Host, nc.Opts.Timeout)
if nc.err != nil {
return nc.err
}
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
}
// makeSecureConn will wrap an existing Conn using TLS
func (nc *Conn) makeTLSConn() {
nc.conn = tls.Client(nc.conn, &tls.Config{InsecureSkipVerify: true})
nc.bw = bufio.NewWriterSize(nc.conn, defaultBufSize)
}
// spinUpSocketWatchers will launch the Go routines
// responsible for reading and writing to the socket.
func (nc *Conn) spinUpSocketWatchers() {
go nc.readLoop()
go nc.flusher()
}
// Main connect function. Will connect to the nats-server
func (nc *Conn) connect() error {
// Create actual socket connection
if err := nc.createConn(); err != nil {
return err
}
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_)
// Make sure to process the INFO inline here.
if nc.err = nc.processExpectedInfo(); nc.err != nil {
return nc.err
}
nc.spinUpSocketWatchers()
runtime.SetFinalizer(nc, fin)
return nc.sendConnect()
}
// 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.SslRequired {
return ErrSecureConnWanted
} else if nc.info.SslRequired && !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.
func (nc *Conn) processExpectedInfo() error {
nc.conn.SetReadDeadline(time.Now().Add(200 * time.Millisecond))
defer nc.conn.SetReadDeadline(time.Time{})
c := &control{}
if err := nc.readOp(c); err != nil {
nc.processOpErr(err)
return err
}
// The nats protocol should send INFO first always.
if c.op != _INFO_OP_ {
err := errors.New("nats: Protocol exception, INFO not received")
nc.processOpErr(err)
return err
}
nc.processInfo(c.args)
return nc.checkForSecure()
}
// 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()
}
// Send a connect protocol message to the server, issuing user/password if
// applicable. This base version can be locked
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}
b, err := json.Marshal(cinfo)
if err != nil {
nc.err = errors.New("nats: Connection message, json parse failed")
return _EMPTY_, nc.err
}
return fmt.Sprintf(conProto, b), nil
}
// Send a connect protocol message to the server, issuing user/password if
// applicable. Will wait for a flush to return from the server for error
// processing.
func (nc *Conn) sendConnect() error {
cProto, err := nc.connectProto()
if err != nil {
return err
}
nc.sendProto(cProto)
if err := nc.FlushTimeout(DefaultTimeout); err != nil {
nc.err = err
return nc.err
} else if nc.isClosed() {
return nc.err
}
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 {
if nc.isClosed() {
return ErrConnectionClosed
}
br := bufio.NewReaderSize(nc.conn, defaultBufSize)
b, pre, err := br.ReadLine()
if err != nil {
return err
}
if pre {
// FIXME: Be more specific here?
return errors.New("nats: Line too long")
}
// Do straight move to string rep.
line := *(*string)(unsafe.Pointer(&b))
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.SslRequired {
nc.err = ErrSecureConnRequired
} else {
nc.err = ErrConnectionClosed
}
}
// This will process a disconnect when reconnect is allowed.
func (nc *Conn) processReconnect() {
nc.mu.Lock()
if !nc.isClosed() {
nc.status = RECONNECTING
if nc.conn != nil {
nc.bw.Flush()
nc.conn.Close()
}
nc.conn = nil
nc.kickFlusher()
// 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.
// Create a pending buffer to underpin the bufio Writer while
// we are reconnecting.
nc.pending = &bytes.Buffer{}
nc.bw = bufio.NewWriterSize(nc.pending, defaultPendingSize)
go nc.doReconnect()
}
nc.mu.Unlock()
// Perform appropriate callback if needed for a disconnect.
if nc.Opts.DisconnectedCB != nil {
nc.Opts.DisconnectedCB(nc)
}
}
// 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())
}
nc.pending = nil
}
// Try to reconnect using the option parameters.
// This function assumes we are allowed to reconnect.
func (nc *Conn) doReconnect() {
// Don't jump right on
time.Sleep(10 * time.Millisecond)
for i := 0; i < int(nc.Opts.MaxReconnect); i++ {
if nc.isClosed() {
break
}
// Try to create a new connection
nc.mu.Lock()
err := nc.createConn()
nc.err = nil
// Not yet connected, sleep and retry...
if err != nil {
nc.mu.Unlock()
time.Sleep(nc.Opts.ReconnectWait)
continue
}
// We are reconnected
nc.Stats.Reconnects += 1
// Process Connect logic
if nc.err = nc.processExpectedInfo(); nc.err == nil {
// Assume the best
nc.status = CONNECTED
// Spin up socket watchers again
nc.spinUpSocketWatchers()
// Send our connect info as normal
cProto, _ := nc.connectProto()
nc.bw.WriteString(cProto)
// Send existing subscription state
nc.resendSubscriptions()
// Now send off and clear pending buffer
nc.flushReconnectPendingItems()
}
nc.mu.Unlock()
// Make sure to flush everything
nc.Flush()
// Call reconnectedCB if appropriate
if nc.Opts.ReconnectedCB != nil {
nc.Opts.ReconnectedCB(nc)
}
return
}
}
// processOpErr handles errors from reading or parsing the protocol.
func (nc *Conn) processOpErr(err error) {
if nc.isClosed() || nc.isReconnecting() {
return
}
if nc.Opts.AllowReconnect {
nc.processReconnect()
} else {
nc.processDisconnect()
nc.err = err
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() {
b := make([]byte, defaultBufSize)
for !nc.isClosed() && !nc.isReconnecting() {
n, err := nc.conn.Read(b)
if err != nil {
nc.processOpErr(err) // FIXME.
break
}
if err := nc.parse(b[:n]); err != nil {
nc.processOpErr(err)
break
}
}
}
// deliverMsgs waits on the delivery channel shared with readLoop and processMsg.
// It is used to deliver messages to asynchronous subscribers.
func (nc *Conn) deliverMsgs(ch chan *Msg) {
for !nc.isClosed() {
m, ok := <-ch
if !ok {
break
}
s := m.Sub
// FIXME, lock?
if s.conn == nil || s.mcb == nil {
continue
}
// FIXME: race on compare?
s.delivered = atomic.AddUint64(&s.delivered, 1)
if s.max <= 0 || s.delivered <= s.max {
s.mcb(m)
}
}
}
// processMsg is called by parse and will place the msg on the
// appropriate channel for processing. All subscribers have their
// their own channel. If the channel is full, the connection is
// considered a slow subscriber.
func (nc *Conn) processMsg(msg []byte) {
// Lock from here on out.
nc.mu.Lock()
// Stats
nc.InMsgs += 1
nc.InBytes += uint64(len(msg))
sub := nc.subs[nc.ps.ma.sid]
if sub == nil {
nc.mu.Unlock()
return
}
sub.mu.Lock()
if sub.max > 0 && sub.msgs > sub.max {
sub.mu.Unlock()
nc.mu.Unlock()
return
}
// Sub internal stats
sub.msgs += 1
sub.bytes += uint64(len(msg))
// FIXME(dlc), if the callback holds onto these could be not good.
subj := *(*string)(unsafe.Pointer(&nc.ps.ma.subject))
reply := *(*string)(unsafe.Pointer(&nc.ps.ma.reply))
// FIXME(dlc): Need to copy, should/can do COW?
newMsg := make([]byte, len(msg))
copy(newMsg, msg)
// FIXME(dlc): Should we recycle these containers?
m := &Msg{Data: newMsg, Subject: subj, Reply: reply, Sub: sub}
if sub.mch != nil {
if len(sub.mch) >= maxChanLen {
nc.processSlowConsumer(sub)
} else {
// Clear always
sub.sc = false
sub.mch <- m
}
}
sub.mu.Unlock()
nc.mu.Unlock()
}
// processSlowConsumer will set SlowConsumer state and fire the
// async error handler if registered.
func (nc *Conn) processSlowConsumer(s *Subscription) {
s.sc = true
nc.err = ErrSlowConsumer
if nc.Opts.AsyncErrorCB != nil {
go nc.Opts.AsyncErrorCB(nc, s, nc.err)
}
}
// flusher is a separate Go routine that will process flush requests for the write
// bufio. This allows coalescing of writes to the underlying socket.
func (nc *Conn) flusher() {
var b int
var ok bool
for !nc.isClosed() && !nc.isReconnecting() {
_, ok = <-nc.fch
if !ok {
return
}
nc.mu.Lock()
// Check for closed or reconnecting
if !nc.isClosed() && !nc.isReconnecting() {
b = nc.bw.Buffered()
if b > 0 && nc.conn != nil {
nc.err = nc.bw.Flush()
}
}
nc.mu.Unlock()
}
}
// processPing will send an immediate pong protocol response to the
// server. The server uses this mechanism to detect dead clients.
func (nc *Conn) processPing() {
nc.sendProto(pongProto)
}
// processPong is used to process responses to the client's ping
// messages. We use pings for the flush mechanism as well.
func (nc *Conn) processPong() {
var ch chan bool
nc.mu.Lock()
if len(nc.pongs) > 0 {
ch = nc.pongs[0]
nc.pongs = nc.pongs[1:]
}
nc.mu.Unlock()
if ch != nil {
ch <- true
}
}
// processOK is a placeholder for processing OK messages.
func (nc *Conn) processOK() {
// do nothing
}
// processInfo is used to parse the info messages sent
// from the server.
func (nc *Conn) processInfo(info string) {
if info == _EMPTY_ {
return
}
nc.err = json.Unmarshal([]byte(info), &nc.info)
}
// LastError reports the last error encountered via the Connection.
func (nc *Conn) LastError() error {
return nc.err
}
// processErr processes any error messages from the server and
// sets the connection's lastError.
func (nc *Conn) processErr(e string) {
nc.err = errors.New("nats: " + e)
nc.Close()
}
// kickFlusher will send a bool on a channel to kick the
// flush Go routine to flush data to the server.
func (nc *Conn) kickFlusher() {
if len(nc.fch) == 0 && nc.bw != nil {
nc.fch <- true
}
}
// Used for handrolled itoa
const digits = "0123456789"
// publish is the internal function to publish messages to a nats-server.
// Sends a protocol data message by queueing into the bufio writer
// and kicking the flush go routine. These writes should be protected.
func (nc *Conn) publish(subj, reply string, data []byte) error {
nc.mu.Lock()
if nc.status == CLOSED {
nc.mu.Unlock()
return ErrConnectionClosed
}
if nc.err != nil {
nc.mu.Unlock()
return nc.err
}
msgh := nc.scratch[:len(_PUB_P_)]
msgh = append(msgh, subj...)
msgh = append(msgh, ' ')
if reply != "" {
msgh = append(msgh, reply...)
msgh = append(msgh, ' ')
}
// We could be smarter here, but simple loop is ok,
// just avoid strconv in fast path
var b [12]byte
var i = len(b)
for l := len(data); l > 0; l /= 10 {
i -= 1
b[i] = digits[l%10]
}
msgh = append(msgh, b[i:]...)
msgh = append(msgh, _CRLF_...)
// FIXME, do deadlines here
if _, nc.err = nc.bw.Write(msgh); nc.err != nil {
nc.mu.Unlock()
return nc.err
}
if _, nc.err = nc.bw.Write(data); nc.err != nil {
nc.mu.Unlock()
return nc.err
}
if _, nc.err = nc.bw.WriteString(_CRLF_); nc.err != nil {
nc.mu.Unlock()
return nc.err
}
nc.OutMsgs += 1
nc.OutBytes += uint64(len(data))
nc.kickFlusher()
nc.mu.Unlock()
return nil
}
// Publish publishes the data argument to the given subject. The data
// argument is left untouched and needs to be correctly interpreted on
// the receiver.
func (nc *Conn) Publish(subj string, data []byte) error {
return nc.publish(subj, _EMPTY_, data)
}
// PublishMsg publishes the Msg structure, which includes the
// Subject, an optional Reply and an optional Data field.
func (nc *Conn) PublishMsg(m *Msg) error {
return nc.publish(m.Subject, m.Reply, m.Data)
}
// PublishRequest will perform a Publish() excpecting a response on the
// reply subject. Use Request() for automatically waiting for a response
// inline.
func (nc *Conn) PublishRequest(subj, reply string, data []byte) error {
return nc.publish(subj, reply, data)
}
// Request will create an Inbox and perform a Request() call
// with the Inbox reply and return the first reply received.
// This is optimized for the case of multiple responses.
func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (m *Msg, err error) {
inbox := NewInbox()
s, err := nc.SubscribeSync(inbox)
if err != nil {
return nil, err
}
s.AutoUnsubscribe(1)
err = nc.PublishRequest(subj, inbox, data)
if err == nil {
m, err = s.NextMsg(timeout)
}
s.Unsubscribe()
return
}
const InboxPrefix = "_INBOX."
// NewInbox will return an inbox string which can be used for directed replies from
// subscribers. These are guaranteed to be unique, but can be shared and subscribed
// to by others.
func NewInbox() string {
u := make([]byte, 13)
io.ReadFull(rand.Reader, u)
return fmt.Sprintf("%s%s", InboxPrefix, hex.EncodeToString(u))
}
// subscribe is the internal subscribe function that indicates interest in a subject.
func (nc *Conn) subscribe(subj, queue string, cb MsgHandler) (*Subscription, error) {
nc.mu.Lock()
// ok here, but defer is expensive
defer nc.kickFlusher()
defer nc.mu.Unlock()
if nc.isClosed() {
return nil, ErrConnectionClosed
}
sub := &Subscription{Subject: subj, mcb: cb, conn: nc}
sub.mch = make(chan *Msg, maxChanLen)
// If we have an async callback, start up a sub specific
// Go routine to deliver the messages.
if cb != nil {
go nc.deliverMsgs(sub.mch)
}
sub.sid = atomic.AddInt64(&nc.ssid, 1)
nc.subs[sub.sid] = sub
// We will send these for all subs when we reconnect
// so that we can suppress here.
if !nc.isReconnecting() {
nc.bw.WriteString(fmt.Sprintf(subProto, subj, queue, sub.sid))
}
return sub, nil
}
// Subscribe will express interest in the given subject. The subject
// can have wildcards (partial:*, full:>). Messages will be delivered
// to the associated MsgHandler. If no MsgHandler is given, the
// subscription is a synchronous subscription and can be polled via
// Subscription.NextMsg().
func (nc *Conn) Subscribe(subj string, cb MsgHandler) (*Subscription, error) {
return nc.subscribe(subj, _EMPTY_, cb)
}
// SubscribeSync is syntactic sugar for Subscribe(subject, nil).
func (nc *Conn) SubscribeSync(subj string) (*Subscription, error) {
return nc.subscribe(subj, _EMPTY_, nil)
}
// QueueSubscribe creates an asynchronous queue subscriber on the given subject.
// All subscribers with the same queue name will form the queue group and
// only one member of the group will be selected to receive any given
// message asynchronously.
func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error) {
return nc.subscribe(subj, queue, cb)
}
// QueueSubscribeSync creates a synchronous queue subscriber on the given
// subject. All subscribers with the same queue name will form the queue
// group and only one member of the group will be selected to receive any
// given message synchronously.
func (nc *Conn) QueueSubscribeSync(subj, queue string) (*Subscription, error) {
return nc.subscribe(subj, queue, nil)
}
// unsubscribe performs the low level unsubscribe to the server.
// Use Subscription.Unsubscribe()
func (nc *Conn) unsubscribe(sub *Subscription, max int) error {
nc.mu.Lock()
// ok here, but defer is expensive
defer nc.kickFlusher()
defer nc.mu.Unlock()
if nc.isClosed() {
return ErrConnectionClosed
}
s := nc.subs[sub.sid]
// Already unsubscribed
if s == nil {
return nil
}
maxStr := _EMPTY_
if max > 0 {
s.max = uint64(max)
maxStr = strconv.Itoa(max)
} else {
delete(nc.subs, s.sid)
s.mu.Lock()
if s.mch != nil {
close(s.mch)
s.mch = nil
}
// Mark as invalid
s.conn = nil
s.mu.Unlock()
}
// We will send these for all subs when we reconnect
// so that we can suppress here.
if !nc.isReconnecting() {
nc.bw.WriteString(fmt.Sprintf(unsubProto, s.sid, maxStr))
}
return nil
}
// IsValid returns a boolean indicating whether the subscription
// is still active. This will return false if the subscription has
// already been closed.
func (s *Subscription) IsValid() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.conn != nil
}
// Unsubscribe will remove interest in the given subject.
func (s *Subscription) Unsubscribe() error {
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
return conn.unsubscribe(s, 0)
}
// AutoUnsubscribe will issue an automatic Unsubscribe that is
// processed by the server when max messages have been received.
// This can be useful when sending a request to an unknown number
// of subscribers. Request() uses this functionality.
func (s *Subscription) AutoUnsubscribe(max int) error {
s.mu.Lock()
conn := s.conn
s.mu.Unlock()
if conn == nil {
return ErrBadSubscription
}
return conn.unsubscribe(s, max)
}
// NextMsg() will return the next message available to a synchronous subscriber
// or block until one is available. A timeout can be used to return when no
// message has been delivered.
func (s *Subscription) NextMsg(timeout time.Duration) (msg *Msg, err error) {
s.mu.Lock()
if s.mch == nil {
s.mu.Unlock()
return nil, ErrConnectionClosed
}
if s.mcb != nil {
s.mu.Unlock()
return nil, errors.New("nats: Illegal call on an async Subscription")
}
if s.conn == nil {