This repository has been archived by the owner on Oct 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
/
rpc.go
723 lines (604 loc) · 19.5 KB
/
rpc.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
package servicebus
// MIT License
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE
import (
"context"
"errors"
"fmt"
"sort"
"sync"
"time"
common "github.com/Azure/azure-amqp-common-go/v3"
"github.com/Azure/azure-amqp-common-go/v3/rpc"
"github.com/Azure/azure-amqp-common-go/v3/uuid"
"github.com/Azure/go-amqp"
"github.com/devigned/tab"
)
type (
rpcClient struct {
ec entityConnector
client *amqp.Client
clientMu sync.RWMutex
linkCache map[string]*rpc.Link // stores 'address' => rpc.Link.
sessionID *string
isSessionFilterSet bool
cancelAuthRefresh func() <-chan struct{}
// replaceable for testing
// alias of 'rpc.NewLink'
newRPCLink func(conn *amqp.Client, address string, opts ...rpc.LinkOption) (*rpc.Link, error)
// alias of function 'newAMQPClient'
newAMQPClient func(ctx context.Context, ec entityConnector) (*amqp.Client, func() <-chan struct{}, error)
// alias of 'amqp.Client.Close()'
closeAMQPClient func() error
}
rpcClientOption func(*rpcClient) error
)
func newRPCClient(ctx context.Context, ec entityConnector, opts ...rpcClientOption) (*rpcClient, error) {
r := &rpcClient{
ec: ec,
linkCache: map[string]*rpc.Link{},
newRPCLink: rpc.NewLink,
newAMQPClient: newAMQPClient,
}
r.closeAMQPClient = func() error { return r.client.Close() }
for _, opt := range opts {
if err := opt(r); err != nil {
tab.For(ctx).Error(err)
return nil, err
}
}
var err error
r.client, r.cancelAuthRefresh, err = r.newAMQPClient(ctx, r.ec)
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
return r, nil
}
// newAMQPClient creates a client and starts auth auto-refresh.
func newAMQPClient(ctx context.Context, ec entityConnector) (*amqp.Client, func() <-chan struct{}, error) {
client, err := ec.Namespace().newClient(ctx)
if err != nil {
return nil, nil, err
}
cancelAuthRefresh, err := ec.Namespace().negotiateClaim(ctx, client, ec.ManagementPath())
if err != nil {
client.Close()
return nil, nil, err
}
return client, cancelAuthRefresh, nil
}
// Recover will attempt to close the current session and link, then rebuild them
func (r *rpcClient) Recover(ctx context.Context) error {
ctx, span := r.startSpanFromContext(ctx, "sb.rpcClient.Recover")
defer span.End()
// atomically close and rebuild the client
r.clientMu.Lock()
defer r.clientMu.Unlock()
_ = r.close()
var err error
r.client, r.cancelAuthRefresh, err = r.newAMQPClient(ctx, r.ec)
if err != nil {
tab.For(ctx).Error(err)
return err
}
return nil
}
// Close will close the AMQP connection
func (r *rpcClient) Close() error {
r.clientMu.Lock()
defer r.clientMu.Unlock()
return r.close()
}
// closes the AMQP connection. callers *must* hold the client write lock before calling!
func (r *rpcClient) close() error {
if r.cancelAuthRefresh != nil {
<-r.cancelAuthRefresh()
}
// we don't want to interrupt the cleanup of these links.
r.resetLinkCache(context.Background())
return r.closeAMQPClient()
}
// resetLinkCache removes any cached links with the assumption that we are
// recovering and do not care about errors that occur with links.
func (r *rpcClient) resetLinkCache(ctx context.Context) {
var links []*rpc.Link
for _, link := range r.linkCache {
links = append(links, link)
}
// make a new links map - Recover() also goes through here (through `close`)
// so we should be prepared to handle more cached links.
r.linkCache = map[string]*rpc.Link{}
for _, link := range links {
link.Close(ctx)
}
}
func (r *rpcClient) getCachedLink(ctx context.Context, address string) (*rpc.Link, error) {
r.clientMu.RLock()
link, ok := r.linkCache[address]
r.clientMu.RUnlock()
if ok {
return link, nil
}
// possibly need to create the link
r.clientMu.Lock()
defer r.clientMu.Unlock()
// might have been added in between us checking and
// us getting the lock.
link, ok = r.linkCache[address]
if ok {
return link, nil
}
link, err := r.newRPCLink(r.client, address)
if err != nil {
return nil, err
}
r.linkCache[address] = link
return link, nil
}
// creates a new link and sends the RPC request, recovering and retrying on certain AMQP errors
func (r *rpcClient) doRPCWithRetry(ctx context.Context, address string, msg *amqp.Message, times int, delay time.Duration, opts ...rpc.LinkOption) (*rpc.Response, error) {
// track the number of times we attempt to perform the RPC call.
// this is to avoid a potential infinite loop if the returned error
// is always transient and Recover() doesn't fail.
sendCount := 0
for {
r.clientMu.RLock()
client := r.client
r.clientMu.RUnlock()
var link *rpc.Link
var rsp *rpc.Response
var err error
isCachedLink := false
if len(opts) == 0 {
// Can use a cached client since there's nothing unique about this particular
// link for this call.
// It looks like creating a management link with a session filter is the
// only time we don't do this.
isCachedLink = true
link, err = r.getCachedLink(ctx, address)
} else {
link, err = rpc.NewLink(client, address)
}
if err == nil {
defer func() {
if isCachedLink || link == nil {
// cached links are closed by `rpcClient.close()`
// (which is also called during recovery)
return
}
link.Close(ctx)
}()
rsp, err = link.RetryableRPC(ctx, times, delay, msg)
if err == nil {
return rsp, nil
}
}
if sendCount >= amqpRetryDefaultTimes || !isAMQPTransientError(ctx, err) {
return nil, err
}
sendCount++
// if we get here, recover and try again
tab.For(ctx).Debug("recovering RPC connection")
_, retryErr := common.Retry(amqpRetryDefaultTimes, amqpRetryDefaultDelay, func() (interface{}, error) {
ctx, sp := r.startProducerSpanFromContext(ctx, "sb.rpcClient.doRPCWithRetry.tryRecover")
defer sp.End()
if err := r.Recover(ctx); err == nil {
tab.For(ctx).Debug("recovered RPC connection")
return nil, nil
}
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
return nil, common.Retryable(err.Error())
}
})
if retryErr != nil {
tab.For(ctx).Debug("RPC recovering retried, but error was unrecoverable")
return nil, retryErr
}
}
}
// returns true if the AMQP error is considered transient
func isAMQPTransientError(ctx context.Context, err error) bool {
// always retry on a detach error
var amqpDetach *amqp.DetachError
if errors.As(err, &amqpDetach) {
return true
}
// for an AMQP error, only retry depending on the condition
var amqpErr *amqp.Error
if errors.As(err, &amqpErr) {
switch amqpErr.Condition {
case errorServerBusy, errorTimeout, errorOperationCancelled, errorContainerClose:
return true
default:
tab.For(ctx).Debug(fmt.Sprintf("isAMQPTransientError: condition %s is not transient", amqpErr.Condition))
return false
}
}
tab.For(ctx).Debug(fmt.Sprintf("isAMQPTransientError: %T is not transient", err))
return false
}
func (r *rpcClient) ReceiveDeferred(ctx context.Context, mode ReceiveMode, sequenceNumbers ...int64) ([]*Message, error) {
ctx, span := startConsumerSpanFromContext(ctx, "sb.rpcClient.ReceiveDeferred")
defer span.End()
const messagesField, messageField = "messages", "message"
backwardsMode := uint32(0)
if mode == PeekLockMode {
backwardsMode = 1
}
values := map[string]interface{}{
"sequence-numbers": sequenceNumbers,
"receiver-settle-mode": uint32(backwardsMode), // pick up messages with peek lock
}
var opts []rpc.LinkOption
if r.isSessionFilterSet {
opts = append(opts, rpc.LinkWithSessionFilter(r.sessionID))
values["session-id"] = r.sessionID
}
msg := &amqp.Message{
ApplicationProperties: map[string]interface{}{
operationFieldName: "com.microsoft:receive-by-sequence-number",
},
Value: values,
}
rsp, err := r.doRPCWithRetry(ctx, r.ec.ManagementPath(), msg, 5, 5*time.Second, opts...)
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
if rsp.Code == 204 {
return nil, ErrNoMessages{}
}
// Deferred messages come back in a relatively convoluted manner:
// a map (always with one key: "messages")
// of arrays
// of maps (always with one key: "message")
// of an array with raw encoded Service Bus messages
val, ok := rsp.Message.Value.(map[string]interface{})
if !ok {
return nil, newErrIncorrectType(messageField, map[string]interface{}{}, rsp.Message.Value)
}
rawMessages, ok := val[messagesField]
if !ok {
return nil, ErrMissingField(messagesField)
}
messages, ok := rawMessages.([]interface{})
if !ok {
return nil, newErrIncorrectType(messagesField, []interface{}{}, rawMessages)
}
transformedMessages := make([]*Message, len(messages))
for i := range messages {
rawEntry, ok := messages[i].(map[string]interface{})
if !ok {
return nil, newErrIncorrectType(messageField, map[string]interface{}{}, messages[i])
}
rawMessage, ok := rawEntry[messageField]
if !ok {
return nil, ErrMissingField(messageField)
}
marshaled, ok := rawMessage.([]byte)
if !ok {
return nil, new(ErrMalformedMessage)
}
var rehydrated amqp.Message
err = rehydrated.UnmarshalBinary(marshaled)
if err != nil {
return nil, err
}
transformedMessages[i], err = messageFromAMQPMessage(&rehydrated, nil)
if err != nil {
return nil, err
}
transformedMessages[i].ec = r.ec
transformedMessages[i].useSession = r.isSessionFilterSet
transformedMessages[i].sessionID = r.sessionID
}
// This sort is done to ensure that folks wanting to peek messages in sequence order may do so.
sort.Slice(transformedMessages, func(i, j int) bool {
iSeq := *transformedMessages[i].SystemProperties.SequenceNumber
jSeq := *transformedMessages[j].SystemProperties.SequenceNumber
return iSeq < jSeq
})
return transformedMessages, nil
}
func (r *rpcClient) GetNextPage(ctx context.Context, fromSequenceNumber int64, messageCount int32) ([]*Message, error) {
ctx, span := startConsumerSpanFromContext(ctx, "sb.rpcClient.GetNextPage")
defer span.End()
const messagesField, messageField = "messages", "message"
msg := &amqp.Message{
ApplicationProperties: map[string]interface{}{
operationFieldName: peekMessageOperationID,
},
Value: map[string]interface{}{
"from-sequence-number": fromSequenceNumber,
"message-count": messageCount,
},
}
if deadline, ok := ctx.Deadline(); ok {
msg.ApplicationProperties["server-timeout"] = uint(time.Until(deadline) / time.Millisecond)
}
rsp, err := r.doRPCWithRetry(ctx, r.ec.ManagementPath(), msg, 5, 5*time.Second)
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
if rsp.Code == 204 {
return nil, ErrNoMessages{}
}
// Peeked messages come back in a relatively convoluted manner:
// a map (always with one key: "messages")
// of arrays
// of maps (always with one key: "message")
// of an array with raw encoded Service Bus messages
val, ok := rsp.Message.Value.(map[string]interface{})
if !ok {
err = newErrIncorrectType(messageField, map[string]interface{}{}, rsp.Message.Value)
tab.For(ctx).Error(err)
return nil, err
}
rawMessages, ok := val[messagesField]
if !ok {
err = ErrMissingField(messagesField)
tab.For(ctx).Error(err)
return nil, err
}
messages, ok := rawMessages.([]interface{})
if !ok {
err = newErrIncorrectType(messagesField, []interface{}{}, rawMessages)
tab.For(ctx).Error(err)
return nil, err
}
transformedMessages := make([]*Message, len(messages))
for i := range messages {
rawEntry, ok := messages[i].(map[string]interface{})
if !ok {
err = newErrIncorrectType(messageField, map[string]interface{}{}, messages[i])
tab.For(ctx).Error(err)
return nil, err
}
rawMessage, ok := rawEntry[messageField]
if !ok {
err = ErrMissingField(messageField)
tab.For(ctx).Error(err)
return nil, err
}
marshaled, ok := rawMessage.([]byte)
if !ok {
err = new(ErrMalformedMessage)
tab.For(ctx).Error(err)
return nil, err
}
var rehydrated amqp.Message
err = rehydrated.UnmarshalBinary(marshaled)
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
transformedMessages[i], err = messageFromAMQPMessage(&rehydrated, nil)
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
transformedMessages[i].ec = r.ec
transformedMessages[i].useSession = r.isSessionFilterSet
transformedMessages[i].sessionID = r.sessionID
}
// This sort is done to ensure that folks wanting to peek messages in sequence order may do so.
sort.Slice(transformedMessages, func(i, j int) bool {
iSeq := *transformedMessages[i].SystemProperties.SequenceNumber
jSeq := *transformedMessages[j].SystemProperties.SequenceNumber
return iSeq < jSeq
})
return transformedMessages, nil
}
func (r *rpcClient) RenewLocks(ctx context.Context, messages ...*Message) error {
ctx, span := startConsumerSpanFromContext(ctx, "sb.RenewLocks")
defer span.End()
var linkName string
lockTokens := make([]amqp.UUID, 0, len(messages))
for _, m := range messages {
if m.LockToken == nil {
tab.For(ctx).Error(fmt.Errorf("failed: message has nil lock token, cannot renew lock"), tab.StringAttribute("messageId", m.ID))
continue
}
amqpLockToken := amqp.UUID(*m.LockToken)
lockTokens = append(lockTokens, amqpLockToken)
if linkName == "" {
linkName = m.getLinkName()
}
}
if len(lockTokens) < 1 {
tab.For(ctx).Info("no lock tokens present to renew")
return nil
}
renewRequestMsg := &amqp.Message{
ApplicationProperties: map[string]interface{}{
operationFieldName: lockRenewalOperationName,
},
Value: map[string]interface{}{
lockTokensFieldName: lockTokens,
},
}
if linkName != "" {
renewRequestMsg.ApplicationProperties[associatedLinkName] = linkName
}
response, err := r.doRPCWithRetry(ctx, r.ec.ManagementPath(), renewRequestMsg, 3, 1*time.Second)
if err != nil {
tab.For(ctx).Error(err)
return err
}
if response.Code != 200 {
err := fmt.Errorf("error renewing locks: %v", response.Description)
tab.For(ctx).Error(err)
return err
}
return nil
}
func (r *rpcClient) SendDisposition(ctx context.Context, m *Message, state disposition) error {
ctx, span := startConsumerSpanFromContext(ctx, "sb.rpcClient.SendDisposition")
defer span.End()
if m.LockToken == nil {
err := errors.New("lock token on the message is not set, thus cannot send disposition")
tab.For(ctx).Error(err)
return err
}
var opts []rpc.LinkOption
value := map[string]interface{}{
"disposition-status": string(state.Status),
"lock-tokens": []amqp.UUID{amqp.UUID(*m.LockToken)},
}
if state.DeadLetterReason != nil {
value["deadletter-reason"] = state.DeadLetterReason
}
if state.DeadLetterDescription != nil {
value["deadletter-description"] = state.DeadLetterDescription
}
if m.useSession {
value["session-id"] = m.sessionID
opts = append(opts, rpc.LinkWithSessionFilter(m.sessionID))
}
msg := &amqp.Message{
ApplicationProperties: map[string]interface{}{
operationFieldName: "com.microsoft:update-disposition",
},
Value: value,
}
// no error, then it was successful
_, err := r.doRPCWithRetry(ctx, m.ec.ManagementPath(), msg, 5, 5*time.Second, opts...)
if err != nil {
tab.For(ctx).Error(err)
return err
}
return nil
}
// ScheduleAt will send a batch of messages to a Queue, schedule them to be enqueued, and return the sequence numbers
// that can be used to cancel each message.
func (r *rpcClient) ScheduleAt(ctx context.Context, enqueueTime time.Time, messages ...*Message) ([]int64, error) {
ctx, span := startConsumerSpanFromContext(ctx, "sb.rpcClient.ScheduleAt")
defer span.End()
if len(messages) <= 0 {
return nil, errors.New("expected one or more messages")
}
transformed := make([]interface{}, 0, len(messages))
for i := range messages {
messages[i].ScheduleAt(enqueueTime)
if messages[i].ID == "" {
id, err := uuid.NewV4()
if err != nil {
return nil, err
}
messages[i].ID = id.String()
}
rawAmqp, err := messages[i].toMsg()
if err != nil {
return nil, err
}
encoded, err := rawAmqp.MarshalBinary()
if err != nil {
return nil, err
}
individualMessage := map[string]interface{}{
"message-id": messages[i].ID,
"message": encoded,
}
if messages[i].SessionID != nil {
individualMessage["session-id"] = *messages[i].SessionID
}
if partitionKey := messages[i].SystemProperties.PartitionKey; partitionKey != nil {
individualMessage["partition-key"] = *partitionKey
}
if viaPartitionKey := messages[i].SystemProperties.ViaPartitionKey; viaPartitionKey != nil {
individualMessage["via-partition-key"] = *viaPartitionKey
}
transformed = append(transformed, individualMessage)
}
msg := &amqp.Message{
ApplicationProperties: map[string]interface{}{
operationFieldName: scheduleMessageOperationID,
},
Value: map[string]interface{}{
"messages": transformed,
},
}
if deadline, ok := ctx.Deadline(); ok {
msg.ApplicationProperties[serverTimeoutFieldName] = uint(time.Until(deadline) / time.Millisecond)
}
resp, err := r.doRPCWithRetry(ctx, r.ec.ManagementPath(), msg, 5, 5*time.Second)
if err != nil {
tab.For(ctx).Error(err)
return nil, err
}
if resp.Code != 200 {
return nil, ErrAMQP(*resp)
}
retval := make([]int64, 0, len(messages))
if rawVal, ok := resp.Message.Value.(map[string]interface{}); ok {
const sequenceFieldName = "sequence-numbers"
if rawArr, ok := rawVal[sequenceFieldName]; ok {
if arr, ok := rawArr.([]int64); ok {
for i := range arr {
retval = append(retval, arr[i])
}
return retval, nil
}
return nil, newErrIncorrectType(sequenceFieldName, []int64{}, rawArr)
}
return nil, ErrMissingField(sequenceFieldName)
}
return nil, newErrIncorrectType("value", map[string]interface{}{}, resp.Message.Value)
}
// CancelScheduled allows for removal of messages that have been handed to the Service Bus broker for later delivery,
// but have not yet ben enqueued.
func (r *rpcClient) CancelScheduled(ctx context.Context, seq ...int64) error {
ctx, span := startConsumerSpanFromContext(ctx, "sb.rpcClient.CancelScheduled")
defer span.End()
msg := &amqp.Message{
ApplicationProperties: map[string]interface{}{
operationFieldName: cancelScheduledOperationID,
},
Value: map[string]interface{}{
"sequence-numbers": seq,
},
}
if deadline, ok := ctx.Deadline(); ok {
msg.ApplicationProperties[serverTimeoutFieldName] = uint(time.Until(deadline) / time.Millisecond)
}
resp, err := r.doRPCWithRetry(ctx, r.ec.ManagementPath(), msg, 5, 5*time.Second)
if err != nil {
tab.For(ctx).Error(err)
return err
}
if resp.Code != 200 {
return ErrAMQP(*resp)
}
return nil
}
func rpcClientWithSession(sessionID *string) rpcClientOption {
return func(r *rpcClient) error {
r.sessionID = sessionID
r.isSessionFilterSet = true
return nil
}
}