-
Notifications
You must be signed in to change notification settings - Fork 800
/
mgmt.go
555 lines (439 loc) · 14.3 KB
/
mgmt.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package internal
import (
"context"
"errors"
"fmt"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/internal/uuid"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal/amqpwrap"
"github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal/exported"
"github.com/Azure/go-amqp"
)
type Disposition struct {
Status DispositionStatus
LockTokens []*uuid.UUID
DeadLetterReason *string
DeadLetterDescription *string
}
type DispositionStatus string
const (
CompletedDisposition DispositionStatus = "completed"
AbandonedDisposition DispositionStatus = "abandoned"
SuspendedDisposition DispositionStatus = "suspended"
DeferredDisposition DispositionStatus = "defered"
)
func ReceiveDeferred(ctx context.Context, rpcLink amqpwrap.RPCLink, linkName string, mode exported.ReceiveMode, sequenceNumbers []int64) ([]*amqp.Message, error) {
const messagesField, messageField = "messages", "message"
backwardsMode := uint32(0)
if mode == exported.PeekLock {
backwardsMode = 1
}
values := map[string]any{
"sequence-numbers": sequenceNumbers,
"receiver-settle-mode": uint32(backwardsMode), // pick up messages with peek lock
}
msg := &amqp.Message{
ApplicationProperties: map[string]any{
"operation": "com.microsoft:receive-by-sequence-number",
},
Value: values,
}
addAssociatedLinkName(linkName, msg)
rsp, err := rpcLink.RPC(ctx, msg)
if err != nil {
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]any)
if !ok {
return nil, NewErrIncorrectType(messageField, map[string]any{}, rsp.Message.Value)
}
rawMessages, ok := val[messagesField]
if !ok {
return nil, ErrMissingField(messagesField)
}
messages, ok := rawMessages.([]any)
if !ok {
return nil, NewErrIncorrectType(messagesField, []any{}, rawMessages)
}
transformedMessages := make([]*amqp.Message, len(messages))
for i := range messages {
rawEntry, ok := messages[i].(map[string]any)
if !ok {
return nil, NewErrIncorrectType(messageField, map[string]any{}, 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] = &rehydrated
}
return transformedMessages, nil
}
func PeekMessages(ctx context.Context, rpcLink amqpwrap.RPCLink, linkName string, fromSequenceNumber int64, messageCount int32) ([]*amqp.Message, error) {
const messagesField, messageField = "messages", "message"
msg := &amqp.Message{
ApplicationProperties: map[string]any{
"operation": "com.microsoft:peek-message",
},
Value: map[string]any{
"from-sequence-number": fromSequenceNumber,
"message-count": messageCount,
},
}
addAssociatedLinkName(linkName, msg)
if deadline, ok := ctx.Deadline(); ok {
msg.ApplicationProperties["server-timeout"] = uint(time.Until(deadline) / time.Millisecond)
}
rsp, err := rpcLink.RPC(ctx, msg)
if err != nil {
return nil, err
}
if rsp.Code == 204 {
// no messages available
return nil, nil
}
// 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]any)
if !ok {
err = NewErrIncorrectType(messageField, map[string]any{}, rsp.Message.Value)
return nil, err
}
rawMessages, ok := val[messagesField]
if !ok {
err = ErrMissingField(messagesField)
return nil, err
}
messages, ok := rawMessages.([]any)
if !ok {
err = NewErrIncorrectType(messagesField, []any{}, rawMessages)
return nil, err
}
transformedMessages := make([]*amqp.Message, len(messages))
for i := range messages {
rawEntry, ok := messages[i].(map[string]any)
if !ok {
err = NewErrIncorrectType(messageField, map[string]any{}, messages[i])
return nil, err
}
rawMessage, ok := rawEntry[messageField]
if !ok {
err = ErrMissingField(messageField)
return nil, err
}
marshaled, ok := rawMessage.([]byte)
if !ok {
err = new(ErrMalformedMessage)
return nil, err
}
var rehydrated amqp.Message
err = rehydrated.UnmarshalBinary(marshaled)
if err != nil {
return nil, err
}
transformedMessages[i] = &rehydrated
// transformedMessages[i], err = MessageFromAMQPMessage(&rehydrated)
// if err != nil {
// tab.For(ctx).Error(err)
// return nil, err
// }
// 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
}
// RenewLocks renews the locks in a single 'com.microsoft:renew-lock' operation.
// NOTE: this function assumes all the messages received on the same link.
func RenewLocks(ctx context.Context, rpcLink amqpwrap.RPCLink, linkName string, lockTokens []amqp.UUID) ([]time.Time, error) {
renewRequestMsg := &amqp.Message{
ApplicationProperties: map[string]any{
"operation": "com.microsoft:renew-lock",
},
Value: map[string]any{
"lock-tokens": lockTokens,
},
}
addAssociatedLinkName(linkName, renewRequestMsg)
response, err := rpcLink.RPC(ctx, renewRequestMsg)
if err != nil {
return nil, err
}
if response.Code != 200 {
err := fmt.Errorf("error renewing locks: %v", response.Description)
return nil, err
}
// extract the new lock renewal times from the response
// response.Message.
val, ok := response.Message.Value.(map[string]any)
if !ok {
return nil, NewErrIncorrectType("Message.Value", map[string]any{}, response.Message.Value)
}
expirations, ok := val["expirations"]
if !ok {
return nil, NewErrIncorrectType("Message.Value[\"expirations\"]", map[string]any{}, response.Message.Value)
}
asTimes, ok := expirations.([]time.Time)
if !ok {
return nil, NewErrIncorrectType("Message.Value[\"expirations\"] as times", map[string]any{}, response.Message.Value)
}
return asTimes, nil
}
// RenewSessionLocks renews a session lock.
func RenewSessionLock(ctx context.Context, rpcLink amqpwrap.RPCLink, linkName string, sessionID string) (time.Time, error) {
body := map[string]any{
"session-id": sessionID,
}
msg := &amqp.Message{
Value: body,
ApplicationProperties: map[string]any{
"operation": "com.microsoft:renew-session-lock",
},
}
addAssociatedLinkName(linkName, msg)
resp, err := rpcLink.RPC(ctx, msg)
if err != nil {
return time.Time{}, err
}
m, ok := resp.Message.Value.(map[string]any)
if !ok {
return time.Time{}, NewErrIncorrectType("Message.Value", map[string]any{}, resp.Message.Value)
}
lockedUntil, ok := m["expiration"].(time.Time)
if !ok {
return time.Time{}, NewErrIncorrectType("Message.Value[\"expiration\"] as times", time.Time{}, resp.Message.Value)
}
return lockedUntil, nil
}
// GetSessionState retrieves state associated with the session.
func GetSessionState(ctx context.Context, rpcLink amqpwrap.RPCLink, linkName string, sessionID string) ([]byte, error) {
amqpMsg := &amqp.Message{
Value: map[string]any{
"session-id": sessionID,
},
ApplicationProperties: map[string]any{
"operation": "com.microsoft:get-session-state",
},
}
addAssociatedLinkName(linkName, amqpMsg)
resp, err := rpcLink.RPC(ctx, amqpMsg)
if err != nil {
return nil, err
}
if resp.Code != 200 {
return nil, ErrAMQP(*resp)
}
asMap, ok := resp.Message.Value.(map[string]any)
if !ok {
return nil, NewErrIncorrectType("Value", map[string]any{}, resp.Message.Value)
}
val := asMap["session-state"]
if val == nil {
// no session state set
return nil, nil
}
asBytes, ok := val.([]byte)
if !ok {
return nil, NewErrIncorrectType("Value['session-state']", []byte{}, asMap["session-state"])
}
return asBytes, nil
}
// SetSessionState sets the state associated with the session.
func SetSessionState(ctx context.Context, rpcLink amqpwrap.RPCLink, linkName string, sessionID string, state []byte) error {
uuid, err := uuid.New()
if err != nil {
return err
}
amqpMsg := &amqp.Message{
Value: map[string]any{
"session-id": sessionID,
"session-state": state,
},
ApplicationProperties: map[string]any{
"operation": "com.microsoft:set-session-state",
"com.microsoft:tracking-id": uuid.String(),
},
}
addAssociatedLinkName(linkName, amqpMsg)
resp, err := rpcLink.RPC(ctx, amqpMsg)
if err != nil {
return err
}
if resp.Code != 200 {
return ErrAMQP(*resp)
}
return nil
}
// SettleOnMgmtLink allows you settle a message using the management link, rather than via your
// *amqp.Receiver. Use this if the receiver has been closed/lost or if the message isn't associated
// with a link (ex: deferred messages).
func SettleOnMgmtLink(ctx context.Context, rpcLink amqpwrap.RPCLink, linkName string, lockToken *amqp.UUID, state Disposition, propertiesToModify map[string]any) error {
if lockToken == nil {
err := errors.New("lock token on the message is not set, thus cannot send disposition")
return err
}
value := map[string]any{
"disposition-status": string(state.Status),
"lock-tokens": []amqp.UUID{*lockToken},
}
if state.DeadLetterReason != nil {
value["deadletter-reason"] = state.DeadLetterReason
}
if state.DeadLetterDescription != nil {
value["deadletter-description"] = state.DeadLetterDescription
}
if propertiesToModify != nil {
value["properties-to-modify"] = propertiesToModify
}
msg := &amqp.Message{
ApplicationProperties: map[string]any{
"operation": "com.microsoft:update-disposition",
},
Value: value,
}
addAssociatedLinkName(linkName, msg)
// no error, then it was successful
_, err := rpcLink.RPC(ctx, msg)
if err != nil {
return err
}
return nil
}
// ScheduleMessages 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 ScheduleMessages(ctx context.Context, rpcLink amqpwrap.RPCLink, linkName string, enqueueTime time.Time, messages []*amqp.Message) ([]int64, error) {
if len(messages) <= 0 {
return nil, errors.New("expected one or more messages")
}
transformed := make([]any, 0, len(messages))
enqueueTimeAsUTC := enqueueTime.UTC()
for i := range messages {
if messages[i].Annotations == nil {
return nil, errors.New("message does not have an initialized Annotations property")
}
messages[i].Annotations["x-opt-scheduled-enqueue-time"] = &enqueueTimeAsUTC
if messages[i].Properties == nil {
messages[i].Properties = &amqp.MessageProperties{}
}
// TODO: this is in two spots now (in Message, and here). Since this one
// could potentially take the raw AMQP message we need to check it, and we assume
// that 'nil' is the only zero value that matters.
if messages[i].Properties.MessageID == nil {
id, err := uuid.New()
if err != nil {
return nil, err
}
messages[i].Properties.MessageID = id.String()
}
encoded, err := messages[i].MarshalBinary()
if err != nil {
return nil, err
}
individualMessage := map[string]any{
"message-id": messages[i].Properties.MessageID,
"message": encoded,
}
if messages[i].Properties.GroupID != nil {
individualMessage["session-id"] = messages[i].Properties.GroupID
}
if value, ok := messages[i].Annotations["x-opt-partition-key"]; ok {
individualMessage["partition-key"] = value.(string)
}
if value, ok := messages[i].Annotations["x-opt-via-partition-key"]; ok {
individualMessage["via-partition-key"] = value.(string)
}
transformed = append(transformed, individualMessage)
}
msg := &amqp.Message{
ApplicationProperties: map[string]any{
"operation": "com.microsoft:schedule-message",
},
Value: map[string]any{
"messages": transformed,
},
}
addAssociatedLinkName(linkName, msg)
if deadline, ok := ctx.Deadline(); ok {
msg.ApplicationProperties["com.microsoft:server-timeout"] = uint(time.Until(deadline) / time.Millisecond)
}
resp, err := rpcLink.RPC(ctx, msg)
if err != nil {
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]any); ok {
const sequenceFieldName = "sequence-numbers"
if rawArr, ok := rawVal[sequenceFieldName]; ok {
if arr, ok := rawArr.([]int64); ok {
retval = append(retval, arr...)
return retval, nil
}
return nil, NewErrIncorrectType(sequenceFieldName, []int64{}, rawArr)
}
return nil, ErrMissingField(sequenceFieldName)
}
return nil, NewErrIncorrectType("value", map[string]any{}, resp.Message.Value)
}
// CancelScheduledMessages allows for removal of messages that have been handed to the Service Bus broker for later delivery,
// but have not yet ben enqueued.
func CancelScheduledMessages(ctx context.Context, rpcLink amqpwrap.RPCLink, linkName string, seq []int64) error {
msg := &amqp.Message{
ApplicationProperties: map[string]any{
"operation": "com.microsoft:cancel-scheduled-message",
},
Value: map[string]any{
"sequence-numbers": seq,
},
}
addAssociatedLinkName(linkName, msg)
if deadline, ok := ctx.Deadline(); ok {
msg.ApplicationProperties["com.microsoft:server-timeout"] = uint(time.Until(deadline) / time.Millisecond)
}
resp, err := rpcLink.RPC(ctx, msg)
if err != nil {
return err
}
if resp.Code != 200 {
return ErrAMQP(*resp)
}
return nil
}
// addAssociatedLinkName adds the 'associated-link-name' application
// property to the AMQP message. Setting this property associates
// management link activity with a sender or receiver link, which can
// prevent it from idling out.
func addAssociatedLinkName(linkName string, msg *amqp.Message) {
if linkName != "" {
msg.ApplicationProperties["associated-link-name"] = linkName
}
}