forked from Azure/go-amqp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
1706 lines (1490 loc) · 43.9 KB
/
client.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
package amqp
import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"math"
"math/rand"
"net"
"net/url"
"sync"
"sync/atomic"
"time"
)
var (
// ErrSessionClosed is propagated to Sender/Receivers
// when Session.Close() is called.
ErrSessionClosed = errors.New("amqp: session closed")
// ErrLinkClosed returned by send and receive operations when
// Sender.Close() or Receiver.Close() are called.
ErrLinkClosed = errors.New("amqp: link closed")
)
// Client is an AMQP client connection.
type Client struct {
conn *conn
}
// Dial connects to an AMQP server.
//
// If the addr includes a scheme, it must be "amqp" or "amqps".
// If no port is provided, 5672 will be used for "amqp" and 5671 for "amqps".
//
// If username and password information is not empty it's used as SASL PLAIN
// credentials, equal to passing ConnSASLPlain option.
func Dial(addr string, opts ...ConnOption) (*Client, error) {
u, err := url.Parse(addr)
if err != nil {
return nil, err
}
host, port, err := net.SplitHostPort(u.Host)
if err != nil {
host = u.Host
port = "5672" // use default port values if parse fails
if u.Scheme == "amqps" {
port = "5671"
}
}
// prepend SASL credentials when the user/pass segment is not empty
if u.User != nil {
pass, _ := u.User.Password()
opts = append([]ConnOption{
ConnSASLPlain(u.User.Username(), pass),
}, opts...)
}
// append default options so user specified can overwrite
opts = append([]ConnOption{
ConnServerHostname(host),
}, opts...)
c, err := newConn(nil, opts...)
if err != nil {
return nil, err
}
switch u.Scheme {
case "amqp", "":
c.net, err = net.Dial("tcp", host+":"+port)
case "amqps":
c.initTLSConfig()
c.tlsNegotiation = false
c.net, err = tls.Dial("tcp", host+":"+port, c.tlsConfig)
default:
return nil, errorErrorf("unsupported scheme %q", u.Scheme)
}
if err != nil {
return nil, err
}
err = c.start()
return &Client{conn: c}, err
}
// New establishes an AMQP client connection over conn.
func New(conn net.Conn, opts ...ConnOption) (*Client, error) {
c, err := newConn(conn, opts...)
if err != nil {
return nil, err
}
err = c.start()
return &Client{conn: c}, err
}
// Close disconnects the connection.
func (c *Client) Close() error {
return c.conn.Close()
}
// NewSession opens a new AMQP session to the server.
func (c *Client) NewSession(opts ...SessionOption) (*Session, error) {
// get a session allocated by Client.mux
var sResp newSessionResp
select {
case <-c.conn.done:
return nil, c.conn.getErr()
case sResp = <-c.conn.newSession:
}
if sResp.err != nil {
return nil, sResp.err
}
s := sResp.session
for _, opt := range opts {
err := opt(s)
if err != nil {
_ = s.Close(context.Background()) // deallocate session on error
return nil, err
}
}
// send Begin to server
begin := &performBegin{
NextOutgoingID: 0,
IncomingWindow: s.incomingWindow,
OutgoingWindow: s.outgoingWindow,
HandleMax: s.handleMax,
}
debug(1, "TX: %s", begin)
s.txFrame(begin, nil)
// wait for response
var fr frame
select {
case <-c.conn.done:
return nil, c.conn.getErr()
case fr = <-s.rx:
}
debug(1, "RX: %s", fr.body)
begin, ok := fr.body.(*performBegin)
if !ok {
_ = s.Close(context.Background()) // deallocate session on error
return nil, errorErrorf("unexpected begin response: %+v", fr.body)
}
// start Session multiplexor
go s.mux(begin)
return s, nil
}
// Default session options
const (
DefaultMaxLinks = 4294967296
DefaultWindow = 100
)
// SessionOption is an function for configuring an AMQP session.
type SessionOption func(*Session) error
// SessionIncomingWindow sets the maximum number of unacknowledged
// transfer frames the server can send.
func SessionIncomingWindow(window uint32) SessionOption {
return func(s *Session) error {
s.incomingWindow = window
return nil
}
}
// SessionOutgoingWindow sets the maximum number of unacknowledged
// transfer frames the client can send.
func SessionOutgoingWindow(window uint32) SessionOption {
return func(s *Session) error {
s.outgoingWindow = window
return nil
}
}
// SessionMaxLinks sets the maximum number of links (Senders/Receivers)
// allowed on the session.
//
// n must be in the range 1 to 4294967296.
//
// Default: 4294967296.
func SessionMaxLinks(n int) SessionOption {
return func(s *Session) error {
if n < 1 {
return errorNew("max sessions cannot be less than 1")
}
if n > 4294967296 {
return errorNew("max sessions cannot be greater than 4294967296")
}
s.handleMax = uint32(n - 1)
return nil
}
}
// Session is an AMQP session.
//
// A session multiplexes Receivers.
type Session struct {
channel uint16 // session's local channel
remoteChannel uint16 // session's remote channel, owned by conn.mux
conn *conn // underlying conn
rx chan frame // frames destined for this session are sent on this chan by conn.mux
tx chan frameBody // non-transfer frames to be sent; session must track disposition
txTransfer chan *performTransfer // transfer frames to be sent; session must track disposition
// flow control
incomingWindow uint32
outgoingWindow uint32
handleMax uint32
allocateHandle chan *link // link handles are allocated by sending a link on this channel, nil is sent on link.rx once allocated
deallocateHandle chan *link // link handles are deallocated by sending a link on this channel
nextDeliveryID uint32 // atomically accessed sequence for deliveryIDs
// used for gracefully closing link
close chan struct{}
closeOnce sync.Once
done chan struct{}
err error
}
func newSession(c *conn, channel uint16) *Session {
return &Session{
conn: c,
channel: channel,
rx: make(chan frame),
tx: make(chan frameBody),
txTransfer: make(chan *performTransfer),
incomingWindow: DefaultWindow,
outgoingWindow: DefaultWindow,
handleMax: DefaultMaxLinks - 1,
allocateHandle: make(chan *link),
deallocateHandle: make(chan *link),
close: make(chan struct{}),
done: make(chan struct{}),
}
}
// Close gracefully closes the session.
//
// If ctx expires while waiting for servers response, ctx.Err() will be returned.
// The session will continue to wait for the response until the Client is closed.
func (s *Session) Close(ctx context.Context) error {
s.closeOnce.Do(func() { close(s.close) })
select {
case <-s.done:
case <-ctx.Done():
return ctx.Err()
}
if s.err == ErrSessionClosed {
return nil
}
return s.err
}
// txFrame sends a frame to the connWriter
func (s *Session) txFrame(p frameBody, done chan deliveryState) {
s.conn.wantWriteFrame(frame{
type_: frameTypeAMQP,
channel: s.channel,
body: p,
done: done,
})
}
// randBytes returns a base64 encoded string of n bytes.
//
// A new random source is created to avoid any issues with seeding
// of the global source.
func randString(n int) string {
localRand := rand.New(rand.NewSource(time.Now().UnixNano()))
b := make([]byte, n)
localRand.Read(b)
return base64.RawURLEncoding.EncodeToString(b)
}
// NewReceiver opens a new receiver link on the session.
func (s *Session) NewReceiver(opts ...LinkOption) (*Receiver, error) {
r := &Receiver{
batching: DefaultLinkBatching,
batchMaxAge: DefaultLinkBatchMaxAge,
maxCredit: DefaultLinkCredit,
}
l, err := attachLink(s, r, opts)
if err != nil {
return nil, err
}
r.link = l
// batching is just extra overhead when maxCredits == 1
if r.maxCredit == 1 {
r.batching = false
}
// create dispositions channel and start dispositionBatcher if batching enabled
if r.batching {
// buffer dispositions chan to prevent disposition sends from blocking
r.dispositions = make(chan messageDisposition, r.maxCredit)
go r.dispositionBatcher()
}
return r, nil
}
// Sender sends messages on a single AMQP link.
type Sender struct {
link *link
mu sync.Mutex // protects buf and nextDeliveryTag
buf buffer
nextDeliveryTag uint64
}
// Send sends a Message.
//
// Blocks until the message is sent, ctx completes, or an error occurs.
//
// Send is safe for concurrent use. Since only a single message can be
// sent on a link at a time, this is most useful when settlement confirmation
// has been requested (receiver settle mode is "Second"). In this case,
// additional messages can be sent while the current goroutine is waiting
// for the confirmation.
func (s *Sender) Send(ctx context.Context, msg *Message) error {
done, err := s.send(ctx, msg)
if err != nil {
return err
}
// wait for transfer to be confirmed
select {
case state := <-done:
if state, ok := state.(*stateRejected); ok {
return state.Error
}
return nil
case <-s.link.done:
return s.link.err
case <-ctx.Done():
return errorWrapf(ctx.Err(), "awaiting send")
}
}
// send is separated from Send so that the mutex unlock can be deferred without
// locking the transfer confirmation that happens in Send.
func (s *Sender) send(ctx context.Context, msg *Message) (chan deliveryState, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.buf.reset()
err := msg.marshal(&s.buf)
if err != nil {
return nil, err
}
if s.link.maxMessageSize != 0 && uint64(s.buf.len()) > s.link.maxMessageSize {
return nil, errorErrorf("encoded message size exceeds max of %d", s.link.maxMessageSize)
}
var (
maxPayloadSize = int(s.link.session.conn.peerMaxFrameSize) - maxTransferFrameHeader
sndSettleMode = s.link.senderSettleMode
rcvSettleMode = s.link.receiverSettleMode
senderSettled = sndSettleMode != nil && *sndSettleMode == ModeSettled
deliveryID = atomic.AddUint32(&s.link.session.nextDeliveryID, 1)
)
// use uint64 encoded as []byte as deliveryTag
deliveryTag := make([]byte, 8)
binary.BigEndian.PutUint64(deliveryTag, s.nextDeliveryTag)
s.nextDeliveryTag++
fr := performTransfer{
Handle: s.link.handle,
DeliveryID: &deliveryID,
DeliveryTag: deliveryTag,
MessageFormat: &msg.Format,
More: s.buf.len() > 0,
}
for fr.More {
buf, _ := s.buf.next(maxPayloadSize)
fr.Payload = append([]byte(nil), buf...)
fr.More = s.buf.len() > 0
if !fr.More {
// mark final transfer as settled when sender mode is settled
fr.Settled = senderSettled
// set done on last frame to be closed after network transmission
//
// If confirmSettlement is true (ReceiverSettleMode == "second"),
// Session.mux will intercept the done channel and close it when the
// receiver has confirmed settlement instead of on net transmit.
fr.done = make(chan deliveryState, 1)
fr.confirmSettlement = rcvSettleMode != nil && *rcvSettleMode == ModeSecond
}
select {
case s.link.transfers <- fr:
case <-s.link.done:
return nil, s.link.err
case <-ctx.Done():
return nil, errorWrapf(ctx.Err(), "awaiting send")
}
// clear values that are only required on first message
fr.DeliveryID = nil
fr.DeliveryTag = nil
fr.MessageFormat = nil
}
return fr.done, nil
}
// Address returns the link's address.
func (s *Sender) Address() string {
if s.link.target == nil {
return ""
}
return s.link.target.Address
}
// Close closes the Sender and AMQP link.
func (s *Sender) Close(ctx context.Context) error {
return s.link.Close(ctx)
}
// NewSender opens a new sender link on the session.
func (s *Session) NewSender(opts ...LinkOption) (*Sender, error) {
l, err := attachLink(s, nil, opts)
if err != nil {
return nil, err
}
return &Sender{link: l}, nil
}
func (s *Session) mux(remoteBegin *performBegin) {
defer close(s.done)
var (
links = make(map[uint32]*link) // mapping of remote handles to links
linksByName = make(map[string]*link) // maping of names to links
handles = &bitmap{max: s.handleMax} // allocated handles
handlesByDeliveryID = make(map[uint32]uint32) // mapping of deliveryIDs to handles
deliveryIDByHandle = make(map[uint32]uint32) // mapping of handles to latest deliveryID
settlementByDeliveryID = make(map[uint32]chan deliveryState)
// flow control values
nextOutgoingID uint32
nextIncomingID = remoteBegin.NextOutgoingID
remoteIncomingWindow = remoteBegin.IncomingWindow
remoteOutgoingWindow = remoteBegin.OutgoingWindow
)
for {
txTransfer := s.txTransfer
// disable txTransfer if flow control windows have been exceeded
if remoteIncomingWindow == 0 || s.outgoingWindow == 0 {
txTransfer = nil
}
select {
// conn has completed, exit
case <-s.conn.done:
s.err = s.conn.getErr()
return
// session is being closed by user
case <-s.close:
s.txFrame(&performEnd{}, nil)
// discard frames until End is received or conn closed
EndLoop:
for {
select {
case fr := <-s.rx:
_, ok := fr.body.(*performEnd)
if ok {
break EndLoop
}
case <-s.conn.done:
s.err = s.conn.getErr()
return
}
}
// release session
select {
case s.conn.delSession <- s:
s.err = ErrSessionClosed
case <-s.conn.done:
s.err = s.conn.getErr()
}
return
// handle allocation request
case l := <-s.allocateHandle:
next, ok := handles.next()
if !ok {
l.err = errorErrorf("reached session handle max (%d)", s.handleMax)
l.rx <- nil
continue
}
l.handle = next // allocate handle to the link
linksByName[l.name] = l // add to mapping
l.rx <- nil // send nil on channel to indicate allocation complete
// handle deallocation request
case l := <-s.deallocateHandle:
delete(links, l.remoteHandle)
delete(deliveryIDByHandle, l.handle)
handles.remove(l.handle)
close(l.rx) // close channel to indicate deallocation
// incoming frame for link
case fr := <-s.rx:
debug(1, "RX(Session): %s", fr.body)
switch body := fr.body.(type) {
// Disposition frames can reference transfers from more than one
// link. Send this frame to all of them.
case *performDisposition:
start := body.First
end := start
if body.Last != nil {
end = *body.Last
}
for deliveryID := start; deliveryID <= end; deliveryID++ {
handle, ok := handlesByDeliveryID[deliveryID]
if !ok {
continue
}
delete(handlesByDeliveryID, deliveryID)
if body.Settled {
// check if settlement confirmation was requested, if so
// confirm by closing channel
if done, ok := settlementByDeliveryID[deliveryID]; ok {
delete(settlementByDeliveryID, deliveryID)
select {
case done <- body.State:
default:
}
close(done)
}
}
link, ok := links[handle]
if !ok {
continue
}
s.muxFrameToLink(link, fr.body)
}
continue
case *performFlow:
if body.NextIncomingID == nil {
// This is a protocol error:
// "[...] MUST be set if the peer has received
// the begin frame for the session"
s.txFrame(&performEnd{
Error: &Error{
Condition: ErrorNotAllowed,
Description: "next-incoming-id not set after session established",
},
}, nil)
s.err = errors.New("protocol error: received flow without next-incoming-id after session established")
return
}
// "When the endpoint receives a flow frame from its peer,
// it MUST update the next-incoming-id directly from the
// next-outgoing-id of the frame, and it MUST update the
// remote-outgoing-window directly from the outgoing-window
// of the frame."
nextIncomingID = body.NextOutgoingID
remoteOutgoingWindow = body.OutgoingWindow
// "The remote-incoming-window is computed as follows:
//
// next-incoming-id(flow) + incoming-window(flow) - next-outgoing-id(endpoint)
//
// If the next-incoming-id field of the flow frame is not set, then remote-incoming-window is computed as follows:
//
// initial-outgoing-id(endpoint) + incoming-window(flow) - next-outgoing-id(endpoint)"
remoteIncomingWindow = body.IncomingWindow - nextOutgoingID
remoteIncomingWindow += *body.NextIncomingID
// Send to link if handle is set
if body.Handle != nil {
link, ok := links[*body.Handle]
if !ok {
continue
}
s.muxFrameToLink(link, fr.body)
continue
}
if body.Echo {
niID := nextIncomingID
resp := &performFlow{
NextIncomingID: &niID,
IncomingWindow: s.incomingWindow,
NextOutgoingID: nextOutgoingID,
OutgoingWindow: s.outgoingWindow,
}
debug(1, "TX: %s", resp)
s.txFrame(resp, nil)
}
case *performAttach:
// On Attach response link should be looked up by name, then added
// to the links map with the remote's handle contained in this
// attach frame.
link, linkOk := linksByName[body.Name]
if !linkOk {
break
}
delete(linksByName, body.Name) // name no longer needed
link.remoteHandle = body.Handle
links[link.remoteHandle] = link
s.muxFrameToLink(link, fr.body)
case *performTransfer:
// "Upon receiving a transfer, the receiving endpoint will
// increment the next-incoming-id to match the implicit
// transfer-id of the incoming transfer plus one, as well
// as decrementing the remote-outgoing-window, and MAY
// (depending on policy) decrement its incoming-window."
nextIncomingID++
remoteOutgoingWindow--
link, ok := links[body.Handle]
if !ok {
continue
}
select {
case <-s.conn.done:
case link.rx <- fr.body:
}
// Update peer's outgoing window if half has been consumed.
if remoteOutgoingWindow < s.incomingWindow/2 {
nID := nextIncomingID
flow := &performFlow{
NextIncomingID: &nID,
IncomingWindow: s.incomingWindow,
NextOutgoingID: nextOutgoingID,
OutgoingWindow: s.outgoingWindow,
}
debug(1, "TX(Session): %s", flow)
s.txFrame(flow, nil)
remoteOutgoingWindow = s.incomingWindow
}
case *performDetach:
link, ok := links[body.Handle]
if !ok {
continue
}
s.muxFrameToLink(link, fr.body)
case *performEnd:
s.txFrame(&performEnd{}, nil)
s.err = errorErrorf("session ended by server: %s", body.Error)
return
default:
fmt.Printf("Unexpected frame: %s\n", body)
}
case fr := <-txTransfer:
// record current delivery ID
var deliveryID uint32
if fr.DeliveryID != nil {
deliveryID = *fr.DeliveryID
deliveryIDByHandle[fr.Handle] = deliveryID
// add to handleByDeliveryID if not sender-settled
if !fr.Settled {
handlesByDeliveryID[deliveryID] = fr.Handle
}
} else {
// if fr.DeliveryID is nil it must have been added
// to deliveryIDByHandle already
deliveryID = deliveryIDByHandle[fr.Handle]
}
// frame has been sender-settled, remove from map
if fr.Settled {
delete(handlesByDeliveryID, deliveryID)
}
// if confirmSettlement requested, add done chan to map
// and clear from frame so conn doesn't close it.
if fr.confirmSettlement && fr.done != nil {
settlementByDeliveryID[deliveryID] = fr.done
fr.done = nil
}
debug(2, "TX(Session): %s", fr)
s.txFrame(fr, fr.done)
// "Upon sending a transfer, the sending endpoint will increment
// its next-outgoing-id, decrement its remote-incoming-window,
// and MAY (depending on policy) decrement its outgoing-window."
nextOutgoingID++
remoteIncomingWindow--
case fr := <-s.tx:
switch fr := fr.(type) {
case *performFlow:
niID := nextIncomingID
fr.NextIncomingID = &niID
fr.IncomingWindow = s.incomingWindow
fr.NextOutgoingID = nextOutgoingID
fr.OutgoingWindow = s.outgoingWindow
debug(1, "TX(Session): %s", fr)
s.txFrame(fr, nil)
remoteOutgoingWindow = s.incomingWindow
case *performTransfer:
panic("transfer frames must use txTransfer")
default:
debug(1, "TX(Session): %s", fr)
s.txFrame(fr, nil)
}
}
}
}
func (s *Session) muxFrameToLink(l *link, fr frameBody) {
select {
case l.rx <- fr:
case <-l.done:
case <-s.conn.done:
}
}
// DetachError is returned by a link (Receiver/Sender) when a detach frame is received.
//
// RemoteError will be nil if the link was detached gracefully.
type DetachError struct {
RemoteError *Error
}
func (e DetachError) Error() string {
return fmt.Sprintf("link detached, reason: %+v", e.RemoteError)
}
// Default link options
const (
DefaultLinkCredit = 1
DefaultLinkBatching = true
DefaultLinkBatchMaxAge = 5 * time.Second
)
// link is a unidirectional route.
//
// May be used for sending or receiving.
type link struct {
name string // our name
handle uint32 // our handle
remoteHandle uint32 // remote's handle
dynamicAddr bool // request a dynamic link address from the server
rx chan frameBody // sessions sends frames for this link on this channel
transfers chan performTransfer // sender uses for send; receiver uses for receive
closeOnce sync.Once // closeOnce protects close from being closed multiple times
close chan struct{} // close signals the mux to shutdown
done chan struct{} // done is closed by mux/muxDetach when the link is fully detached
detachErrorMu sync.Mutex // protects detachError
detachError *Error // error to send to remote on detach, set by closeWithError
session *Session // parent session
receiver *Receiver // allows link options to modify Receiver
source *source
target *target
properties map[symbol]interface{} // additional properties sent upon link attach
// "The delivery-count is initialized by the sender when a link endpoint is created,
// and is incremented whenever a message is sent. Only the sender MAY independently
// modify this field. The receiver's value is calculated based on the last known
// value from the sender and any subsequent messages received on the link. Note that,
// despite its name, the delivery-count is not a count but a sequence number
// initialized at an arbitrary point by the sender."
deliveryCount uint32
linkCredit uint32 // maximum number of messages allowed between flow updates
senderSettleMode *SenderSettleMode
receiverSettleMode *ReceiverSettleMode
maxMessageSize uint64
detachReceived bool
err error // err returned on Close()
}
// attachLink is used by Receiver and Sender to create new links
func attachLink(s *Session, r *Receiver, opts []LinkOption) (*link, error) {
l, err := newLink(s, r, opts)
if err != nil {
return nil, err
}
isReceiver := r != nil
// buffer rx to linkCredit so that conn.mux won't block
// attempting to send to a slow reader
if isReceiver {
l.rx = make(chan frameBody, l.linkCredit)
} else {
l.rx = make(chan frameBody, 1)
}
// request handle from Session.mux
select {
case <-s.done:
return nil, s.err
case s.allocateHandle <- l:
}
// wait for handle allocation
select {
case <-s.done:
return nil, s.err
case <-l.rx:
}
// check for link request error
if l.err != nil {
return nil, l.err
}
attach := &performAttach{
Name: l.name,
Handle: l.handle,
ReceiverSettleMode: l.receiverSettleMode,
SenderSettleMode: l.senderSettleMode,
MaxMessageSize: l.maxMessageSize,
Source: l.source,
Target: l.target,
Properties: l.properties,
}
if isReceiver {
attach.Role = roleReceiver
if attach.Source == nil {
attach.Source = new(source)
}
attach.Source.Dynamic = l.dynamicAddr
} else {
attach.Role = roleSender
if attach.Target == nil {
attach.Target = new(target)
}
attach.Target.Dynamic = l.dynamicAddr
}
// send Attach frame
debug(1, "TX: %s", attach)
s.txFrame(attach, nil)
// wait for response
var fr frameBody
select {
case <-s.done:
return nil, s.err
case fr = <-l.rx:
}
debug(3, "RX: %s", fr)
resp, ok := fr.(*performAttach)
if !ok {
return nil, errorErrorf("unexpected attach response: %#v", fr)
}
if l.maxMessageSize == 0 || resp.MaxMessageSize < l.maxMessageSize {
l.maxMessageSize = resp.MaxMessageSize
}
if isReceiver {
// if dynamic address requested, copy assigned name to address
if l.dynamicAddr && resp.Source != nil {
l.source.Address = resp.Source.Address
}
// deliveryCount is a sequence number, must initialize to sender's initial sequence number
l.deliveryCount = resp.InitialDeliveryCount
// buffer receiver so that link.mux doesn't block
l.transfers = make(chan performTransfer, l.receiver.maxCredit)
if resp.SenderSettleMode != nil {
l.senderSettleMode = resp.SenderSettleMode
}
} else {
// if dynamic address requested, copy assigned name to address
if l.dynamicAddr && resp.Target != nil {
l.target.Address = resp.Target.Address
}
l.transfers = make(chan performTransfer)
if resp.ReceiverSettleMode != nil {
l.receiverSettleMode = resp.ReceiverSettleMode
}
}
go l.mux()
return l, nil
}
func newLink(s *Session, r *Receiver, opts []LinkOption) (*link, error) {
l := &link{
name: randString(40),
session: s,
receiver: r,
close: make(chan struct{}),
done: make(chan struct{}),
}
// configure options
for _, o := range opts {
err := o(l)
if err != nil {
return nil, err
}
}
return l, nil
}
func (l *link) mux() {
defer l.muxDetach()
var (
isReceiver = l.receiver != nil
isSender = !isReceiver
)
Loop:
for {
var outgoingTransfers chan performTransfer
switch {
// enable outgoing transfers case if sender and credits are available
case isSender && l.linkCredit > 0:
outgoingTransfers = l.transfers
// if receiver and linkCredit is half used, send more
case isReceiver && l.linkCredit <= l.receiver.maxCredit/2:
l.err = l.muxFlow()
if l.err != nil {
return
}
}
select {
// received frame
case fr := <-l.rx:
l.err = l.muxHandleFrame(fr)
if l.err != nil {
return
}
// send data
case tr := <-outgoingTransfers:
debug(3, "TX(link): %s", tr)
// Ensure the session mux is not blocked
for {
select {
case l.session.txTransfer <- &tr:
// decrement link-credit after entire message transferred
if !tr.More {
l.deliveryCount++
l.linkCredit--
}
continue Loop
case fr := <-l.rx:
l.err = l.muxHandleFrame(fr)
if l.err != nil {
return
}
case <-l.close:
l.err = ErrLinkClosed
return
case <-l.session.done:
l.err = l.session.err
return
}