/
managementClient.ts
1355 lines (1293 loc) · 46.7 KB
/
managementClient.ts
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 (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import Long from "long";
import {
EventContext,
SenderEvents,
ReceiverEvents,
SenderOptions,
ReceiverOptions,
types,
message as RheaMessageUtil,
generate_uuid,
string_to_uuid
} from "rhea-promise";
import {
defaultLock,
translate,
Constants,
RequestResponseLink,
ConditionErrorNameMapper,
AmqpMessage,
SendRequestOptions
} from "@azure/amqp-common";
import { ClientEntityContext } from "../clientEntityContext";
import {
ReceivedMessageInfo,
ServiceBusMessage,
SendableMessageInfo,
DispositionStatus,
toAmqpMessage,
getMessagePropertyTypeMismatchError
} from "../serviceBusMessage";
import { LinkEntity } from "./linkEntity";
import * as log from "../log";
import { ReceiveMode, fromAmqpMessage } from "../serviceBusMessage";
import { toBuffer } from "../util/utils";
import {
throwErrorIfConnectionClosed,
throwTypeErrorIfParameterMissing,
throwTypeErrorIfParameterNotLong,
throwTypeErrorIfParameterTypeMismatch,
throwTypeErrorIfParameterIsEmptyString
} from "../util/errors";
import { Typed } from "rhea-promise";
import { max32BitNumber } from "../util/constants";
import { Buffer } from "buffer";
/**
* Represents a Rule on a Subscription that is used to filter the incoming message from the
* Subscription.
*/
export interface RuleDescription {
/**
* Filter expression used to match messages. Supports 2 types:
* - `string`: SQL-like condition expression that is evaluated against the messages'
* user-defined properties and system properties. All system properties will be prefixed with
* `sys.` in the condition expression.
* - `CorrelationFilter`: Properties of the filter will be used to match with the message properties.
*/
filter?: string | CorrelationFilter;
/**
* Action to perform if the message satisfies the filtering expression.
*/
action?: string;
/**
* Represents the name of the rule.
*/
name: string;
}
/**
* Represents the correlation filter expression.
* A CorrelationFilter holds a set of conditions that are matched against user and system properties
* of incoming messages from a Subscription.
*/
export interface CorrelationFilter {
/**
* Value to be matched with the `correlationId` property of the incoming message.
*/
correlationId?: string;
/**
* Value to be matched with the `messageId` property of the incoming message.
*/
messageId?: string;
/**
* Value to be matched with the `to` property of the incoming message.
*/
to?: string;
/**
* Value to be matched with the `replyTo` property of the incoming message.
*/
replyTo?: string;
/**
* Value to be matched with the `label` property of the incoming message.
*/
label?: string;
/**
* Value to be matched with the `sessionId` property of the incoming message.
*/
sessionId?: string;
/**
* Value to be matched with the `replyToSessionId` property of the incoming message.
*/
replyToSessionId?: string;
/**
* Value to be matched with the `contentType` property of the incoming message.
*/
contentType?: string;
/**
* Value to be matched with the user properties of the incoming message.
*/
userProperties?: any;
}
const correlationProperties = [
"correlationId",
"messageId",
"to",
"replyTo",
"label",
"sessionId",
"replyToSessionId",
"contentType",
"userProperties"
];
/**
* @internal
* Options to set when updating the disposition status
*/
interface DispositionStatusOptions {
/**
* @property [propertiesToModify] A dictionary of Service Bus brokered message properties
* to modify.
*/
propertiesToModify?: { [key: string]: any };
/**
* @property [deadLetterReason] The deadletter reason. May be set if disposition status
* is set to suspended.
*/
deadLetterReason?: string;
/**
* @property [deadLetterDescription] The deadletter description. May be set if disposition status
* is set to suspended.
*/
deadLetterDescription?: string;
/**
* This should only be provided if `session` is enabled for a Queue or Topic.
*/
sessionId?: string;
}
/**
* @internal
* Options passed to the constructor of ManagementClient
*/
export interface ManagementClientOptions {
address?: string;
audience?: string;
}
/**
* @internal
* @class ManagementClient
* Descibes the ServiceBus Management Client that talks
* to the $management endpoint over AMQP connection.
*/
export class ManagementClient extends LinkEntity {
readonly managementLock: string = `${Constants.managementRequestKey}-${generate_uuid()}`;
/**
* @property {string} entityPath - The name/path of the entity (queue/topic/subscription name)
* for which the management request needs to be made.
*/
entityPath: string;
/**
* @property {string} replyTo The reply to Guid for the management client.
*/
replyTo: string = generate_uuid();
/**
* @property $management sender, receiver on the same session.
* @private
*/
private _mgmtReqResLink?: RequestResponseLink;
/**
* @property _lastPeekedSequenceNumber Provides the sequence number of the last peeked message.
* @private
*/
private _lastPeekedSequenceNumber: Long = Long.ZERO;
/**
* @constructor
* Instantiates the management client.
* @param {ClientEntityContext} context The client entity context.
* @param {ManagementClientOptions} [options] Options to be provided for creating the
* "$management" client.
*/
constructor(context: ClientEntityContext, options?: ManagementClientOptions) {
super(`${context.entityPath}/$management`, context, {
address: options && options.address ? options.address : Constants.management,
audience:
options && options.audience
? options.audience
: `${context.namespace.config.endpoint}${context.entityPath}/$management`
});
this._context = context;
this.entityPath = context.namespace.config.entityPath as string;
}
private async _init(): Promise<void> {
throwErrorIfConnectionClosed(this._context.namespace);
try {
if (!this._isMgmtRequestResponseLinkOpen()) {
await this._negotiateClaim();
const rxopt: ReceiverOptions = {
source: { address: this.address },
name: this.replyTo,
target: { address: this.replyTo },
onSessionError: (context: EventContext) => {
const id = context.connection.options.id;
const ehError = translate(context.session!.error!);
log.error(
"[%s] An error occurred on the session for request/response links for " +
"$management: %O",
id,
ehError
);
}
};
const sropt: SenderOptions = { target: { address: this.address } };
log.mgmt(
"[%s] Creating sender/receiver links on a session for $management endpoint with " +
"srOpts: %o, receiverOpts: %O.",
this._context.namespace.connectionId,
sropt,
rxopt
);
this._mgmtReqResLink = await RequestResponseLink.create(
this._context.namespace.connection,
sropt,
rxopt
);
this._mgmtReqResLink.sender.on(SenderEvents.senderError, (context: EventContext) => {
const id = context.connection.options.id;
const ehError = translate(context.sender!.error!);
log.error("[%s] An error occurred on the $management sender link.. %O", id, ehError);
});
this._mgmtReqResLink.receiver.on(ReceiverEvents.receiverError, (context: EventContext) => {
const id = context.connection.options.id;
const ehError = translate(context.receiver!.error!);
log.error("[%s] An error occurred on the $management receiver link.. %O", id, ehError);
});
log.mgmt(
"[%s] Created sender '%s' and receiver '%s' links for $management endpoint.",
this._context.namespace.connectionId,
this._mgmtReqResLink.sender.name,
this._mgmtReqResLink.receiver.name
);
await this._ensureTokenRenewal();
}
} catch (err) {
err = translate(err);
log.error(
"[%s] An error occured while establishing the $management links: %O",
this._context.namespace.connectionId,
err
);
throw err;
}
}
private _isMgmtRequestResponseLinkOpen(): boolean {
return this._mgmtReqResLink! && this._mgmtReqResLink!.isOpen();
}
/**
* Given array of typed values, returns the element in given index
*/
private _safelyGetTypedValueFromArray(data: Typed[], index: number): any {
return Array.isArray(data) && data.length > index && data[index]
? data[index].value
: undefined;
}
/**
* Helper function to retrieve active receiver name, if it exists.
* @param clientEntityContext The `ClientEntityContext` associated with given Service Bus entity client
* @param sessionId `sessionId` if applicable
*/
private _getAssociatedReceiverName(
clientEntityContext: ClientEntityContext,
sessionId?: string
): string | undefined {
if (sessionId != undefined) {
if (clientEntityContext.messageSessions[sessionId]) {
return clientEntityContext.messageSessions[sessionId].name;
}
}
if (clientEntityContext.batchingReceiver) {
return clientEntityContext.batchingReceiver.name;
}
if (clientEntityContext.streamingReceiver) {
return clientEntityContext.streamingReceiver.name;
}
return;
}
/**
* Closes the AMQP management session to the ServiceBus namespace for this client,
* returning a promise that will be resolved when disconnection is completed.
* @return Promise<void>
*/
async close(): Promise<void> {
try {
if (this._isMgmtRequestResponseLinkOpen()) {
const mgmtLink = this._mgmtReqResLink;
this._mgmtReqResLink = undefined;
clearTimeout(this._tokenRenewalTimer as NodeJS.Timer);
await mgmtLink!.close();
log.mgmt("Successfully closed the management session.");
}
} catch (err) {
log.error(
"[%s] An error occurred while closing the management session: %O.",
this._context.namespace.connectionId,
err
);
throw err;
}
}
/**
* Fetches the next batch of active messages. The first call to `peek()` fetches the first
* active message for this client. Each subsequent call fetches the subsequent message in the
* entity.
*
* Unlike a `received` message, `peeked` message will not have lock token associated with it,
* and hence it cannot be `Completed/Abandoned/Deferred/Deadlettered/Renewed`. This method will
* also fetch even Deferred messages (but not Deadlettered message).
* @param {number} [messageCount] The number of messages to retrieve. Default value `1`.
* @returns Promise<ReceivedSBMessage[]>
*/
async peek(messageCount?: number): Promise<ReceivedMessageInfo[]> {
throwErrorIfConnectionClosed(this._context.namespace);
return this.peekBySequenceNumber(this._lastPeekedSequenceNumber.add(1), messageCount);
}
/**
* Fetches the next batch of active messages in the current MessageSession. The first call to
* `peek()` fetches the first active message for this client. Each subsequent call fetches the
* subsequent message in the entity.
*
* Unlike a `received` message, `peeked` message will not have lock token associated with it,
* and hence it cannot be `Completed/Abandoned/Deferred/Deadlettered/Renewed`. This method will
* also fetch even Deferred messages (but not Deadlettered message).
* @param {string} sessionId The sessionId from which messages need to be peeked.
* @param {number} [messageCount] The number of messages to retrieve. Default value `1`.
* @returns Promise<ReceivedMessageInfo[]>
*/
async peekMessagesBySession(
sessionId: string,
messageCount?: number
): Promise<ReceivedMessageInfo[]> {
throwErrorIfConnectionClosed(this._context.namespace);
return this.peekBySequenceNumber(
this._lastPeekedSequenceNumber.add(1),
messageCount,
sessionId
);
}
/**
* Peeks the desired number of messages from the specified sequence number.
* @param {Long} fromSequenceNumber The sequence number from where to read the message.
* @param {number} messageCount The number of messages to retrieve. Default value `1`.
* @param {string} sessionId The sessionId from which messages need to be peeked.
* @returns Promise<ReceivedMessageInfo[]>
*/
async peekBySequenceNumber(
fromSequenceNumber: Long,
maxMessageCount?: number,
sessionId?: string
): Promise<ReceivedMessageInfo[]> {
throwErrorIfConnectionClosed(this._context.namespace);
const connId = this._context.namespace.connectionId;
// Checks for fromSequenceNumber
throwTypeErrorIfParameterMissing(connId, "fromSequenceNumber", fromSequenceNumber);
throwTypeErrorIfParameterNotLong(connId, "fromSequenceNumber", fromSequenceNumber);
// Checks for maxMessageCount
if (maxMessageCount !== undefined) {
throwTypeErrorIfParameterTypeMismatch(connId, "maxMessageCount", maxMessageCount, "number");
if (maxMessageCount <= 0) {
return [];
}
} else {
maxMessageCount = 1;
}
const messageList: ReceivedMessageInfo[] = [];
try {
const messageBody: any = {};
messageBody[Constants.fromSequenceNumber] = types.wrap_long(
Buffer.from(fromSequenceNumber.toBytesBE())
);
messageBody[Constants.messageCount] = types.wrap_int(maxMessageCount);
if (sessionId != undefined) {
messageBody[Constants.sessionIdMapKey] = sessionId;
}
const request: AmqpMessage = {
body: messageBody,
message_id: generate_uuid(),
reply_to: this.replyTo,
application_properties: {
operation: Constants.operations.peekMessage
}
};
const associatedLinkName = this._getAssociatedReceiverName(this._context, sessionId);
if (associatedLinkName) {
request.application_properties![Constants.associatedLinkName] = associatedLinkName;
}
request.application_properties![Constants.trackingId] = generate_uuid();
log.mgmt(
"[%s] Peek by sequence number request body: %O.",
this._context.namespace.connectionId,
request.body
);
log.mgmt(
"[%s] Acquiring lock to get the management req res link.",
this._context.namespace.connectionId
);
await defaultLock.acquire(this.managementLock, () => {
return this._init();
});
const result = await this._mgmtReqResLink!.sendRequest(request);
if (result.application_properties!.statusCode !== 204) {
const messages = result.body.messages as { message: Buffer }[];
for (const msg of messages) {
const decodedMessage = RheaMessageUtil.decode(msg.message);
const message = fromAmqpMessage(decodedMessage as any);
message.body = this._context.namespace.dataTransformer.decode(message.body);
messageList.push(message);
this._lastPeekedSequenceNumber = message.sequenceNumber!;
}
}
} catch (err) {
const error = translate(err);
log.error(
"An error occurred while sending the request to peek messages to " +
"$management endpoint: %O",
error
);
// statusCode == 404 then do not throw
if (error.name !== ConditionErrorNameMapper["com.microsoft:message-not-found"]) {
throw error;
}
}
return messageList;
}
/**
* Renews the lock on the message. The lock will be renewed based on the setting specified on
* the queue.
*
* When a message is received in `PeekLock` mode, the message is locked on the server for this
* receiver instance for a duration as specified during the Queue/Subscription creation
* (LockDuration). If processing of the message requires longer than this duration, the
* lock needs to be renewed. For each renewal, it resets the time the message is locked by the
* LockDuration set on the Entity.
*
* @param {string} lockToken Lock token of the message
* @param {SendRequestOptions} [options] Options that can be set while sending the request.
* @returns {Promise<Date>} Promise<Date> New lock token expiry date and time in UTC format.
*/
async renewLock(lockToken: string, options?: SendRequestOptions): Promise<Date> {
throwErrorIfConnectionClosed(this._context.namespace);
if (!options) options = {};
if (options.delayInSeconds == null) options.delayInSeconds = 1;
if (options.timeoutInSeconds == null) options.timeoutInSeconds = 5;
if (options.times == null) options.times = 5;
try {
const messageBody: any = {};
messageBody[Constants.lockTokens] = types.wrap_array(
[string_to_uuid(lockToken)],
0x98,
undefined
);
const request: AmqpMessage = {
body: messageBody,
reply_to: this.replyTo,
application_properties: {
operation: Constants.operations.renewLock
}
};
request.application_properties![Constants.trackingId] = generate_uuid();
const associatedLinkName = this._getAssociatedReceiverName(this._context);
if (associatedLinkName) {
request.application_properties![Constants.associatedLinkName] = associatedLinkName;
}
log.mgmt(
"[%s] Renew message Lock request: %O.",
this._context.namespace.connectionId,
request
);
log.mgmt(
"[%s] Acquiring lock to get the management req res link.",
this._context.namespace.connectionId
);
await defaultLock.acquire(this.managementLock, () => {
return this._init();
});
const result = await this._mgmtReqResLink!.sendRequest(request, options);
const lockedUntilUtc = new Date(result.body.expirations[0]);
return lockedUntilUtc;
} catch (err) {
const error = translate(err);
log.error(
"An error occurred while sending the renew lock request to $management " + "endpoint: %O",
error
);
throw error;
}
}
/**
* Schedules an array of messages to appear on Service Bus at a later time.
*
* @param scheduledEnqueueTimeUtc - The UTC time at which the messages should be enqueued.
* @param messages - An array of messages that needs to be scheduled.
* @returns Promise<number> The sequence numbers of messages that were scheduled.
*/
async scheduleMessages(
scheduledEnqueueTimeUtc: Date,
messages: SendableMessageInfo[]
): Promise<Long[]> {
throwErrorIfConnectionClosed(this._context.namespace);
const messageBody: any[] = [];
for (let i = 0; i < messages.length; i++) {
const item = messages[i];
if (!item.messageId) item.messageId = generate_uuid();
item.scheduledEnqueueTimeUtc = scheduledEnqueueTimeUtc;
const amqpMessage = toAmqpMessage(item);
try {
const entry: any = {
message: RheaMessageUtil.encode(amqpMessage),
"message-id": item.messageId
};
if (item.sessionId) {
entry[Constants.sessionIdMapKey] = item.sessionId;
}
if (item.partitionKey) {
entry["partition-key"] = item.partitionKey;
}
if (item.viaPartitionKey) {
entry["via-partition-key"] = item.viaPartitionKey;
}
const wrappedEntry = types.wrap_map(entry);
messageBody.push(wrappedEntry);
} catch (err) {
let error: Error;
if (err instanceof TypeError || err.name === "TypeError") {
// `RheaMessageUtil.encode` can fail if message properties are of invalid type
// rhea throws errors with name `TypeError` but not an instance of `TypeError`, so catch them too
// Errors in such cases do not have user friendy message or call stack
// So use `getMessagePropertyTypeMismatchError` to get a better error message
error = translate(getMessagePropertyTypeMismatchError(item) || err);
} else {
error = translate(err);
}
log.error(
"An error occurred while encoding the item at position %d in the messages array" + ": %O",
i,
error
);
throw error;
}
}
try {
const request: AmqpMessage = {
body: { messages: messageBody },
reply_to: this.replyTo,
application_properties: {
operation: Constants.operations.scheduleMessage
}
};
if (this._context.sender) {
request.application_properties![Constants.associatedLinkName] = this._context.sender!.name;
}
request.application_properties![Constants.trackingId] = generate_uuid();
log.mgmt(
"[%s] Schedule messages request body: %O.",
this._context.namespace.connectionId,
request.body
);
log.mgmt(
"[%s] Acquiring lock to get the management req res link.",
this._context.namespace.connectionId
);
await defaultLock.acquire(this.managementLock, () => {
return this._init();
});
const result = await this._mgmtReqResLink!.sendRequest(request);
const sequenceNumbers = result.body[Constants.sequenceNumbers];
const sequenceNumbersAsLong = [];
for (let i = 0; i < sequenceNumbers.length; i++) {
if (typeof sequenceNumbers[i] === "number") {
sequenceNumbersAsLong.push(Long.fromNumber(sequenceNumbers[i]));
} else {
sequenceNumbersAsLong.push(Long.fromBytesBE(sequenceNumbers[i]));
}
}
return sequenceNumbersAsLong;
} catch (err) {
const error = translate(err);
log.error(
"An error occurred while sending the request to schedule messages to " +
"$management endpoint: %O",
error
);
throw error;
}
}
/**
* Cancels an array of messages that were scheduled.
* @param sequenceNumbers - An Array of sequence numbers of the message to be cancelled.
* @returns Promise<void>
*/
async cancelScheduledMessages(sequenceNumbers: Long[]): Promise<void> {
throwErrorIfConnectionClosed(this._context.namespace);
const messageBody: any = {};
messageBody[Constants.sequenceNumbers] = [];
for (let i = 0; i < sequenceNumbers.length; i++) {
const sequenceNumber = sequenceNumbers[i];
try {
messageBody[Constants.sequenceNumbers].push(Buffer.from(sequenceNumber.toBytesBE()));
} catch (err) {
const error = translate(err);
log.error(
"An error occurred while encoding the item at position %d in the " +
"sequenceNumbers array: %O",
i,
error
);
throw error;
}
}
try {
messageBody[Constants.sequenceNumbers] = types.wrap_array(
messageBody[Constants.sequenceNumbers],
0x81,
undefined
);
const request: AmqpMessage = {
body: messageBody,
message_id: generate_uuid(),
reply_to: this.replyTo,
application_properties: {
operation: Constants.operations.cancelScheduledMessage
}
};
if (this._context.sender) {
request.application_properties![Constants.associatedLinkName] = this._context.sender!.name;
}
request.application_properties![Constants.trackingId] = generate_uuid();
log.mgmt(
"[%s] Cancel scheduled messages request body: %O.",
this._context.namespace.connectionId,
request.body
);
log.mgmt(
"[%s] Acquiring lock to get the management req res link.",
this._context.namespace.connectionId
);
await defaultLock.acquire(this.managementLock, () => {
return this._init();
});
await this._mgmtReqResLink!.sendRequest(request);
} catch (err) {
const error = translate(err);
log.error(
"An error occurred while sending the request to cancel the scheduled message to " +
"$management endpoint: %O",
error
);
throw error;
}
}
/**
* Receives a list of deferred messages identified by `sequenceNumbers`.
* @param sequenceNumbers A list containing the sequence numbers to receive.
* @param receiveMode The mode in which the receiver was created.
* @returns Promise<ServiceBusMessage[]>
* - Returns a list of messages identified by the given sequenceNumbers.
* - Returns an empty list if no messages are found.
* - Throws an error if the messages have not been deferred.
*/
async receiveDeferredMessages(
sequenceNumbers: Long[],
receiveMode: ReceiveMode,
sessionId?: string
): Promise<ServiceBusMessage[]> {
throwErrorIfConnectionClosed(this._context.namespace);
const messageList: ServiceBusMessage[] = [];
const messageBody: any = {};
messageBody[Constants.sequenceNumbers] = [];
for (let i = 0; i < sequenceNumbers.length; i++) {
const sequenceNumber = sequenceNumbers[i];
try {
messageBody[Constants.sequenceNumbers].push(Buffer.from(sequenceNumber.toBytesBE()));
} catch (err) {
const error = translate(err);
log.error(
"An error occurred while encoding the item at position %d in the " +
"sequenceNumbers array: %O",
i,
error
);
throw error;
}
}
try {
messageBody[Constants.sequenceNumbers] = types.wrap_array(
messageBody[Constants.sequenceNumbers],
0x81,
undefined
);
const receiverSettleMode: number = receiveMode === ReceiveMode.receiveAndDelete ? 0 : 1;
messageBody[Constants.receiverSettleMode] = types.wrap_uint(receiverSettleMode);
if (sessionId != null) {
messageBody[Constants.sessionIdMapKey] = sessionId;
}
const request: AmqpMessage = {
body: messageBody,
message_id: generate_uuid(),
reply_to: this.replyTo,
application_properties: {
operation: Constants.operations.receiveBySequenceNumber
}
};
const associatedLinkName = this._getAssociatedReceiverName(this._context, sessionId);
if (associatedLinkName) {
request.application_properties![Constants.associatedLinkName] = associatedLinkName;
}
request.application_properties![Constants.trackingId] = generate_uuid();
log.mgmt(
"[%s] Receive deferred messages request body: %O.",
this._context.namespace.connectionId,
request.body
);
log.mgmt(
"[%s] Acquiring lock to get the management req res link.",
this._context.namespace.connectionId
);
await defaultLock.acquire(this.managementLock, () => {
return this._init();
});
const result = await this._mgmtReqResLink!.sendRequest(request);
const messages = result.body.messages as {
message: Buffer;
"lock-token": Buffer;
}[];
for (const msg of messages) {
const decodedMessage = RheaMessageUtil.decode(msg.message);
const message = new ServiceBusMessage(
this._context,
decodedMessage as any,
{ tag: msg["lock-token"] } as any,
false
);
if (message.lockToken && message.lockedUntilUtc) {
this._context.requestResponseLockedMessages.set(
message.lockToken,
message.lockedUntilUtc
);
}
messageList.push(message);
}
return messageList;
} catch (err) {
const error = translate(err);
log.error(
"An error occurred while sending the request to receive deferred messages to " +
"$management endpoint: %O",
error
);
throw error;
}
}
/**
* Updates the disposition status of deferred messages.
*
* @param lockTokens Message lock tokens to update disposition status.
* @param dispositionStatus The disposition status to be set
* @param options Optional parameters that can be provided while updating the disposition status.
*
* @returns Promise<void>
*/
async updateDispositionStatus(
lockToken: string,
dispositionStatus: DispositionStatus,
options?: DispositionStatusOptions
): Promise<void> {
throwErrorIfConnectionClosed(this._context.namespace);
if (!options) options = {};
try {
const messageBody: any = {};
const lockTokenBuffer: Buffer[] = [];
lockTokenBuffer.push(string_to_uuid(lockToken));
messageBody[Constants.lockTokens] = types.wrap_array(lockTokenBuffer, 0x98, undefined);
messageBody[Constants.dispositionStatus] = dispositionStatus;
if (options.deadLetterDescription != null) {
messageBody[Constants.deadLetterDescription] = options.deadLetterDescription;
}
if (options.deadLetterReason != null) {
messageBody[Constants.deadLetterReason] = options.deadLetterReason;
}
if (options.propertiesToModify != null) {
messageBody[Constants.propertiesToModify] = options.propertiesToModify;
}
if (options.sessionId != null) {
messageBody[Constants.sessionIdMapKey] = options.sessionId;
}
const request: AmqpMessage = {
body: messageBody,
message_id: generate_uuid(),
reply_to: this.replyTo,
application_properties: {
operation: Constants.operations.updateDisposition
}
};
const associatedLinkName = this._getAssociatedReceiverName(this._context, options.sessionId);
if (associatedLinkName) {
request.application_properties![Constants.associatedLinkName] = associatedLinkName;
}
request.application_properties![Constants.trackingId] = generate_uuid();
log.mgmt(
"[%s] Update disposition status request body: %O.",
this._context.namespace.connectionId,
request.body
);
log.mgmt(
"[%s] Acquiring lock to get the management req res link.",
this._context.namespace.connectionId
);
await defaultLock.acquire(this.managementLock, () => {
return this._init();
});
await this._mgmtReqResLink!.sendRequest(request);
} catch (err) {
const error = translate(err);
log.error(
"An error occurred while sending the request to update disposition status to " +
"$management endpoint: %O",
error
);
throw error;
}
}
/**
* Renews the lock for the specified session.
* @param sessionId Id of the session for which the lock needs to be renewed
* @param options Options that can be set while sending the request.
* @returns Promise<Date> New lock token expiry date and time in UTC format.
*/
async renewSessionLock(sessionId: string, options?: SendRequestOptions): Promise<Date> {
throwErrorIfConnectionClosed(this._context.namespace);
if (!options) options = {};
if (options.delayInSeconds == null) options.delayInSeconds = 1;
if (options.timeoutInSeconds == null) options.timeoutInSeconds = 5;
if (options.times == null) options.times = 5;
try {
const messageBody: any = {};
messageBody[Constants.sessionIdMapKey] = sessionId;
const request: AmqpMessage = {
body: messageBody,
reply_to: this.replyTo,
application_properties: {
operation: Constants.operations.renewSessionLock
}
};
request.application_properties![Constants.trackingId] = generate_uuid();
const associatedLinkName = this._getAssociatedReceiverName(this._context, sessionId);
if (associatedLinkName) {
request.application_properties![Constants.associatedLinkName] = associatedLinkName;
}
log.mgmt(
"[%s] Renew Session Lock request body: %O.",
this._context.namespace.connectionId,
request.body
);
log.mgmt(
"[%s] Acquiring lock to get the management req res link.",
this._context.namespace.connectionId
);
await defaultLock.acquire(this.managementLock, () => {
return this._init();
});
const result = await this._mgmtReqResLink!.sendRequest(request, options);
const lockedUntilUtc = new Date(result.body.expiration);
log.mgmt(
"[%s] Lock for session '%s' will expire at %s.",
this._context.namespace.connectionId,
sessionId,
lockedUntilUtc.toString()
);
return lockedUntilUtc;
} catch (err) {
const error = translate(err);
log.error(
"An error occurred while sending the renew lock request to $management " + "endpoint: %O",
error
);
throw error;
}
}
/**
* Sets the state of the specified session.
* @param sessionId The session for which the state needs to be set
* @param state The state that needs to be set.
* @returns Promise<void>
*/
async setSessionState(sessionId: string, state: any): Promise<void> {
throwErrorIfConnectionClosed(this._context.namespace);
try {
const messageBody: any = {};
messageBody[Constants.sessionIdMapKey] = sessionId;
messageBody["session-state"] = toBuffer(state);
const request: AmqpMessage = {
body: messageBody,
reply_to: this.replyTo,
application_properties: {
operation: Constants.operations.setSessionState
}
};
const associatedLinkName = this._getAssociatedReceiverName(this._context, sessionId);
if (associatedLinkName) {
request.application_properties![Constants.associatedLinkName] = associatedLinkName;
}
request.application_properties![Constants.trackingId] = generate_uuid();
log.mgmt(
"[%s] Set Session state request body: %O.",
this._context.namespace.connectionId,
request.body
);
log.mgmt(
"[%s] Acquiring lock to get the management req res link.",
this._context.namespace.connectionId
);
await defaultLock.acquire(this.managementLock, () => {
return this._init();
});
await this._mgmtReqResLink!.sendRequest(request);
} catch (err) {
const error = translate(err);
log.error(
"An error occurred while sending the renew lock request to $management " + "endpoint: %O",
error
);
throw error;
}
}
/**
* Gets the state of the specified session.
* @param sessionId The session for which the state needs to be retrieved.
* @returns Promise<any> The state of that session
*/
async getSessionState(sessionId: string): Promise<any> {
throwErrorIfConnectionClosed(this._context.namespace);
try {
const messageBody: any = {};
messageBody[Constants.sessionIdMapKey] = sessionId;
const request: AmqpMessage = {
body: messageBody,
reply_to: this.replyTo,
application_properties: {
operation: Constants.operations.getSessionState
}
};
const associatedLinkName = this._getAssociatedReceiverName(this._context, sessionId);
if (associatedLinkName) {
request.application_properties![Constants.associatedLinkName] = associatedLinkName;