forked from Azure/go-amqp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
473 lines (412 loc) · 13.9 KB
/
session.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
package amqp
import (
"context"
"errors"
"fmt"
"sync"
"github.com/Azure/go-amqp/internal/bitmap"
"github.com/Azure/go-amqp/internal/encoding"
"github.com/Azure/go-amqp/internal/frames"
)
// 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 frames.Frame // frames destined for this session are sent on this chan by conn.mux
tx chan frames.FrameBody // non-transfer frames to be sent; session must track disposition
txTransfer chan *frames.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 frames.Frame),
tx: make(chan frames.FrameBody),
txTransfer: make(chan *frames.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.
// it returns an error if the connection has been closed.
func (s *Session) txFrame(p frames.FrameBody, done chan encoding.DeliveryState) error {
return s.conn.SendFrame(frames.Frame{
Type: frameTypeAMQP,
Channel: s.channel,
Body: p,
Done: done,
})
}
// 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
}
// 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 *frames.PerformBegin) {
defer func() {
// clean up session record in conn.mux()
select {
case s.conn.DelSession <- s:
case <-s.conn.Done:
s.err = s.conn.Err()
}
if s.err == nil {
s.err = ErrSessionClosed
}
// Signal goroutines waiting on the session.
close(s.done)
}()
var (
links = make(map[uint32]*link) // mapping of remote handles to links
linksByKey = make(map[linkKey]*link) // mapping of name+role link
handles = bitmap.New(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
handlesByRemoteDeliveryID = make(map[uint32]uint32) // mapping of remote deliveryID to handles
settlementByDeliveryID = make(map[uint32]chan encoding.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 {
debug(1, "TX(Session): Disabling txTransfer - window exceeded. remoteIncomingWindow: %d outgoingWindow:%d",
remoteIncomingWindow,
s.outgoingWindow)
txTransfer = nil
}
select {
// conn has completed, exit
case <-s.conn.Done:
s.err = s.conn.Err()
return
// session is being closed by user
case <-s.close:
_ = s.txFrame(&frames.PerformEnd{}, nil)
// wait for the ack that the session is closed.
// we can't exit the mux, which deletes the session,
// until we receive it.
EndLoop:
for {
select {
case fr := <-s.rx:
_, ok := fr.Body.(*frames.PerformEnd)
if ok {
break EndLoop
}
case <-s.conn.Done:
s.err = s.conn.Err()
return
}
}
return
// handle allocation request
case l := <-s.allocateHandle:
// Check if link name already exists, if so then an error should be returned
if linksByKey[l.Key] != nil {
l.err = fmt.Errorf("link with name '%v' already exists", l.Key.name)
l.RX <- nil
continue
}
next, ok := handles.Next()
if !ok {
// handle numbers are zero-based, report the actual count
l.err = fmt.Errorf("reached session handle max (%d)", s.handleMax+1)
l.RX <- nil
continue
}
l.Handle = next // allocate handle to the link
linksByKey[l.Key] = 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)
delete(linksByKey, l.Key)
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 *frames.PerformDisposition:
start := body.First
end := start
if body.Last != nil {
end = *body.Last
}
for deliveryID := start; deliveryID <= end; deliveryID++ {
handles := handlesByDeliveryID
if body.Role == encoding.RoleSender {
handles = handlesByRemoteDeliveryID
}
handle, ok := handles[deliveryID]
if !ok {
continue
}
delete(handles, deliveryID)
if body.Settled && body.Role == encoding.RoleReceiver {
// 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 *frames.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(&frames.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
debug(3, "RX(Session) Flow - remoteOutgoingWindow: %d remoteIncomingWindow: %d nextOutgoingID: %d", remoteOutgoingWindow, remoteIncomingWindow, nextOutgoingID)
// 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 := &frames.PerformFlow{
NextIncomingID: &niID,
IncomingWindow: s.incomingWindow,
NextOutgoingID: nextOutgoingID,
OutgoingWindow: s.outgoingWindow,
}
debug(1, "TX (session.mux): %s", resp)
_ = s.txFrame(resp, nil)
}
case *frames.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.
//
// Note body.Role is the remote peer's role, we reverse for the local key.
link, linkOk := linksByKey[linkKey{name: body.Name, role: !body.Role}]
if !linkOk {
s.err = fmt.Errorf("protocol error: received mismatched attach frame %+v", body)
return
}
link.RemoteHandle = body.Handle
links[link.RemoteHandle] = link
s.muxFrameToLink(link, fr.Body)
case *frames.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++
// don't loop to intmax
if remoteOutgoingWindow > 0 {
remoteOutgoingWindow--
}
link, ok := links[body.Handle]
if !ok {
continue
}
select {
case <-s.conn.Done:
case link.RX <- fr.Body:
}
// if this message is received unsettled and link rcv-settle-mode == second, add to handlesByRemoteDeliveryID
if !body.Settled && body.DeliveryID != nil && link.ReceiverSettleMode != nil && *link.ReceiverSettleMode == ModeSecond {
debug(1, "TX(Session): adding handle to handlesByRemoteDeliveryID. delivery ID: %d", *body.DeliveryID)
handlesByRemoteDeliveryID[*body.DeliveryID] = body.Handle
}
debug(3, "TX(Session) Flow? remoteOutgoingWindow(%d) < s.incomingWindow(%d)/2\n", remoteOutgoingWindow, s.incomingWindow)
// Update peer's outgoing window if half has been consumed.
if remoteOutgoingWindow < s.incomingWindow/2 {
nID := nextIncomingID
flow := &frames.PerformFlow{
NextIncomingID: &nID,
IncomingWindow: s.incomingWindow,
NextOutgoingID: nextOutgoingID,
OutgoingWindow: s.outgoingWindow,
}
debug(1, "TX(Session): %s", flow)
_ = s.txFrame(flow, nil)
}
case *frames.PerformDetach:
link, ok := links[body.Handle]
if !ok {
continue
}
s.muxFrameToLink(link, fr.Body)
case *frames.PerformEnd:
_ = s.txFrame(&frames.PerformEnd{}, nil)
s.err = fmt.Errorf("session ended by server: %s", body.Error)
return
default:
// TODO: evaluate
debug(1, "session mux: 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 not settled, add done chan to map
// and clear from frame so conn doesn't close it.
if !fr.Settled && fr.Done != nil {
settlementByDeliveryID[deliveryID] = fr.Done
fr.Done = nil
}
debug(2, "TX(Session) - txtransfer: %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++
// don't decrement if we're at 0 or we could loop to int max
if remoteIncomingWindow != 0 {
remoteIncomingWindow--
}
case fr := <-s.tx:
switch fr := fr.(type) {
case *frames.PerformFlow:
niID := nextIncomingID
fr.NextIncomingID = &niID
fr.IncomingWindow = s.incomingWindow
fr.NextOutgoingID = nextOutgoingID
fr.OutgoingWindow = s.outgoingWindow
debug(1, "TX(Session) - tx: %s", fr)
_ = s.txFrame(fr, nil)
case *frames.PerformTransfer:
panic("transfer frames must use txTransfer")
default:
debug(1, "TX(Session) - default: %s", fr)
_ = s.txFrame(fr, nil)
}
}
}
}
func (s *Session) muxFrameToLink(l *link, fr frames.FrameBody) {
select {
case l.RX <- fr:
case <-l.Detached:
case <-s.conn.Done:
}
}