-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
receiver.ts
792 lines (736 loc) · 31.2 KB
/
receiver.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import {
PeekMessagesOptions,
GetMessageIteratorOptions,
MessageHandlers,
ReceiveMessagesOptions,
SubscribeOptions,
DeleteMessagesOptions,
PurgeMessagesOptions,
} from "../models";
import { OperationOptionsBase } from "../modelsToBeSharedWithEventHubs";
import { ServiceBusReceivedMessage } from "../serviceBusMessage";
import { ConnectionContext } from "../connectionContext";
import {
getAlreadyReceivingErrorMsg,
getReceiverClosedErrorMsg,
InvalidMaxMessageCountError,
throwErrorIfConnectionClosed,
throwTypeErrorIfParameterMissing,
throwTypeErrorIfParameterNotLong,
throwErrorIfInvalidOperationOnMessage,
throwTypeErrorIfParameterTypeMismatch,
} from "../util/errors";
import { ReceiveOptions } from "../core/messageReceiver";
import { StreamingReceiver } from "../core/streamingReceiver";
import { BatchingReceiver } from "../core/batchingReceiver";
import {
abandonMessage,
assertValidMessageHandlers,
completeMessage,
deadLetterMessage,
deferMessage,
getMessageIterator,
} from "./receiverCommon";
import Long from "long";
import { ServiceBusMessageImpl, DeadLetterOptions } from "../serviceBusMessage";
import { Constants, RetryConfig, RetryOperationType, RetryOptions, retry } from "@azure/core-amqp";
import { LockRenewer } from "../core/autoLockRenewer";
import { receiverLogger as logger } from "../log";
import { translateServiceBusError } from "../serviceBusError";
import { ensureValidIdentifier } from "../util/utils";
import { toSpanOptions, tracingClient } from "../diagnostics/tracing";
import { extractSpanContextFromServiceBusMessage } from "../diagnostics/instrumentServiceBusMessage";
import { TracingSpanLink } from "@azure/core-tracing";
/**
* The default time to wait for messages _after_ the first message
* has been received.
*
* This timeout only applies to receiveMessages()
*
* @internal
*/
export const defaultMaxTimeAfterFirstMessageForBatchingMs = 1000;
/**
* The maximum number of messages to delete in a single batch. This cap is established and enforced by the service.
* @internal
*/
export const MaxDeleteMessageCount = 4000;
/**
* A receiver that does not handle sessions.
*/
export interface ServiceBusReceiver {
/**
* A name used to identify the receiver. This can be used to correlate logs and exceptions.
* If not specified or empty, a random unique one will be generated.
*/
identifier: string;
/**
* Streams messages to message handlers.
* @param handlers - A handler that gets called for messages and errors.
* @param options - Options for subscribe.
* @returns An object that can be closed, sending any remaining messages to `handlers` and
* stopping new messages from arriving.
*/
subscribe(
handlers: MessageHandlers,
options?: SubscribeOptions,
): {
/**
* Causes the subscriber to stop receiving new messages.
*/
close(): Promise<void>;
};
/**
* Returns an iterator that can be used to receive messages from Service Bus.
*
* @param options - A set of options to control the receive operation.
* - `abortSignal`: The signal to use to abort the ongoing operation.
*
* @throws Error if the underlying connection, client or receiver is closed.
* @throws Error if current receiver is already in state of receiving messages.
* @throws `ServiceBusError` if the service returns an error while receiving messages.
*/
getMessageIterator(
options?: GetMessageIteratorOptions,
): AsyncIterableIterator<ServiceBusReceivedMessage>;
/**
* Returns a promise that resolves to an array of messages received from Service Bus.
*
* @param maxMessageCount - The maximum number of messages to receive.
* @param options - A set of options to control the receive operation.
* - `maxWaitTimeInMs`: The maximum time to wait for the first message before returning an empty array if no messages are available.
* - `abortSignal`: The signal to use to abort the ongoing operation.
* @returns A promise that resolves with an array of messages.
* @throws Error if the underlying connection, client or receiver is closed.
* @throws Error if current receiver is already in state of receiving messages.
* @throws `ServiceBusError` if the service returns an error while receiving messages.
*/
receiveMessages(
maxMessageCount: number,
options?: ReceiveMessagesOptions,
): Promise<ServiceBusReceivedMessage[]>;
/**
* Returns a promise that resolves to an array of deferred messages identified by given `sequenceNumbers`.
* @param sequenceNumbers - The sequence number or an array of sequence numbers for the messages that need to be received.
* @param options - Options bag to pass an abort signal or tracing options.
* @returns A list of messages identified by the given sequenceNumbers or an empty list if no messages are found.
* @throws Error if the underlying connection or receiver is closed.
* @throws `ServiceBusError` if the service returns an error while receiving deferred messages.
*/
receiveDeferredMessages(
sequenceNumbers: Long | Long[],
options?: OperationOptionsBase,
): Promise<ServiceBusReceivedMessage[]>;
/**
* Peek the next batch of active messages (including deferred but not deadlettered messages) on the
* queue or subscription without modifying them.
* - The first call to `peekMessages()` fetches the first active message. Each subsequent call fetches the
* subsequent message.
* - Unlike a "received" message, "peeked" message is a read-only version of the message.
* It cannot be `Completed/Abandoned/Deferred/Deadlettered`.
* @param maxMessageCount - The maximum number of messages to peek.
* @param options - Options that allow to specify the maximum number of messages to peek,
* the sequenceNumber to start peeking from or an abortSignal to abort the operation.
*/
peekMessages(
maxMessageCount: number,
options?: PeekMessagesOptions,
): Promise<ServiceBusReceivedMessage[]>;
/**
* Delete messages. If no option is specified, all messages will be deleted.
*
* @param options - Options to configure the operation.
* @returns number of messages that have been deleted.
*/
deleteMessages(options: DeleteMessagesOptions): Promise<number>;
/**
* Attempts to purge all messages from an entity. Locked messages are not eligible for removal and
* will remain in the entity.
*
* @param options - Options that allow to specify the cutoff time for deletion. Only messages that were enqueued
* before this time will be deleted. If not specified, current time will be used.
* @returns number of messages deleted.
*/
purgeMessages(options?: PurgeMessagesOptions): Promise<number>;
/**
* Path of the entity for which the receiver has been created.
*/
entityPath: string;
/**
* The receive mode used to create the receiver.
*/
receiveMode: "peekLock" | "receiveAndDelete";
/**
* Returns `true` if either the receiver or the client that created it has been closed.
* @readonly
*/
isClosed: boolean;
/**
* Closes the receiver.
* Once closed, the receiver cannot be used for any further operations.
* Use the `createReceiver()` method on the ServiceBusClient to create a new Receiver.
*/
close(): Promise<void>;
/**
* Removes the message from Service Bus.
*
* @throws Error with name `SessionLockLostError` (for messages from a Queue/Subscription with sessions enabled)
* if the AMQP link with which the message was received is no longer alive. This can
* happen either because the lock on the session expired or the receiver was explicitly closed by
* the user or the AMQP link is closed by the library due to network loss or service error.
* @throws Error with name `MessageLockLostError` (for messages from a Queue/Subscription with sessions not enabled)
* if the lock on the message has expired or the AMQP link with which the message was received is
* no longer alive. The latter can happen if the receiver was explicitly closed by the user or the
* AMQP link got closed by the library due to network loss or service error.
* @throws Error if the message is already settled.
* property on the message if you are not sure whether the message is settled.
* @throws Error if used in `receiveAndDelete` mode because all messages received in this mode
* are pre-settled. To avoid this error, update your code to not settle a message which is received
* in this mode.
* @throws Error with name `ServiceUnavailableError` if Service Bus does not acknowledge the request to settle
* the message in time. The message may or may not have been settled successfully.
*/
completeMessage(message: ServiceBusReceivedMessage): Promise<void>;
/**
* The lock held on the message by the receiver is let go, making the message available again in
* Service Bus for another receive operation.
*
* @throws `ServiceBusError` with the code `SessionLockLost` (for messages from a Queue/Subscription with sessions enabled)
* if the AMQP link with which the message was received is no longer alive. This can
* happen either because the lock on the session expired or the receiver was explicitly closed by
* the user or the AMQP link is closed by the library due to network loss or service error.
* @throws `ServiceBusError` with the code `MessageLockLost` (for messages from a Queue/Subscription with sessions not enabled)
* if the lock on the message has expired or the AMQP link with which the message was received is
* no longer alive. The latter can happen if the receiver was explicitly closed by the user or the
* AMQP link got closed by the library due to network loss or service error.
* @throws Error if the message is already settled.
* property on the message if you are not sure whether the message is settled.
* @throws Error if used in `receiveAndDelete` mode because all messages received in this mode
* are pre-settled. To avoid this error, update your code to not settle a message which is received
* in this mode.
* @throws `ServiceBusError` with the code `ServiceTimeout` if Service Bus does not acknowledge the request to settle
* the message in time. The message may or may not have been settled successfully.
*
* @param propertiesToModify - The properties of the message to modify while abandoning the message.
*/
abandonMessage(
message: ServiceBusReceivedMessage,
propertiesToModify?: { [key: string]: number | boolean | string | Date | null },
): Promise<void>;
/**
* Defers the processing of the message. Save the `sequenceNumber` of the message, in order to
* receive it message again in the future using the `receiveDeferredMessage` method.
*
* @throws `ServiceBusError` with the code `SessionLockLost` (for messages from a Queue/Subscription with sessions enabled)
* if the AMQP link with which the message was received is no longer alive. This can
* happen either because the lock on the session expired or the receiver was explicitly closed by
* the user or the AMQP link is closed by the library due to network loss or service error.
* @throws `ServiceBusError` with the code `MessageLockLost` (for messages from a Queue/Subscription with sessions not enabled)
* if the lock on the message has expired or the AMQP link with which the message was received is
* no longer alive. The latter can happen if the receiver was explicitly closed by the user or the
* AMQP link got closed by the library due to network loss or service error.
* @throws Error if the message is already settled.
* property on the message if you are not sure whether the message is settled.
* @throws Error if used in `receiveAndDelete` mode because all messages received in this mode
* are pre-settled. To avoid this error, update your code to not settle a message which is received
* in this mode.
* @throws `ServiceBusError` with the code `ServiceTimeout` if Service Bus does not acknowledge the request to settle
* the message in time. The message may or may not have been settled successfully.
*
* @param propertiesToModify - The properties of the message to modify while deferring the message
*/
deferMessage(
message: ServiceBusReceivedMessage,
propertiesToModify?: { [key: string]: number | boolean | string | Date | null },
): Promise<void>;
/**
* Moves the message to the deadletter sub-queue. To receive a deadletted message, create a new
* QueueClient/SubscriptionClient using the path for the deadletter sub-queue.
*
* @throws `ServiceBusError` with the code `SessionLockLost` (for messages from a Queue/Subscription with sessions enabled)
* if the AMQP link with which the message was received is no longer alive. This can
* happen either because the lock on the session expired or the receiver was explicitly closed by
* the user or the AMQP link is closed by the library due to network loss or service error.
* @throws `ServiceBusError` with the code `MessageLockLost` (for messages from a Queue/Subscription with sessions not enabled)
* if the lock on the message has expired or the AMQP link with which the message was received is
* no longer alive. The latter can happen if the receiver was explicitly closed by the user or the
* AMQP link got closed by the library due to network loss or service error.
* @throws Error if the message is already settled.
* property on the message if you are not sure whether the message is settled.
* @throws Error if used in `receiveAndDelete` mode because all messages received in this mode
* are pre-settled. To avoid this error, update your code to not settle a message which is received
* in this mode.
* @throws `ServiceBusError` with the code `ServiceTimeout` if Service Bus does not acknowledge the request to settle
* the message in time. The message may or may not have been settled successfully.
*
* @param options - The DeadLetter options that can be provided while
* rejecting the message.
*/
deadLetterMessage(
message: ServiceBusReceivedMessage,
options?: DeadLetterOptions & { [key: string]: number | boolean | string | Date | null },
): Promise<void>;
/**
* Renews the lock on the message for the duration as specified during the Queue/Subscription
* creation.
* - Check the `lockedUntilUtc` property on the message for the time when the lock expires.
* - If a message is not settled (using either `complete()`, `defer()` or `deadletter()`,
* before its lock expires, then the message lands back in the Queue/Subscription for the next
* receive operation.
*
* @returns New lock token expiry date and time in UTC format.
* @throws Error if the underlying connection, client or receiver is closed.
* @throws ServiceBusError if the service returns an error while renewing message lock.
*/
renewMessageLock(message: ServiceBusReceivedMessage): Promise<Date>;
}
/**
* @internal
*/
export class ServiceBusReceiverImpl implements ServiceBusReceiver {
public identifier: string;
private _retryOptions: RetryOptions;
/**
* Denotes if close() was called on this receiver
*/
private _isClosed: boolean = false;
/**
* Instance of the BatchingReceiver class to use to receive messages in pull mode.
*/
private _batchingReceiver?: BatchingReceiver;
/**
* Instance of the StreamingReceiver class to use to receive messages in push mode.
*/
private _streamingReceiver?: StreamingReceiver;
private _lockRenewer: LockRenewer | undefined;
private get logPrefix(): string {
return `[${this._context.connectionId}|receiver:${this.entityPath}]`;
}
/**
* @throws Error if the underlying connection is closed.
*/
constructor(
private _context: ConnectionContext,
public entityPath: string,
public receiveMode: "peekLock" | "receiveAndDelete",
maxAutoRenewLockDurationInMs: number,
private skipParsingBodyAsJson: boolean,
private skipConvertingDate: boolean = false,
retryOptions: RetryOptions = {},
identifier?: string,
) {
throwErrorIfConnectionClosed(_context);
this._retryOptions = retryOptions;
this._lockRenewer = LockRenewer.create(
this._context,
maxAutoRenewLockDurationInMs,
receiveMode,
);
this.identifier = ensureValidIdentifier(this.entityPath, identifier);
}
private _throwIfAlreadyReceiving(): void {
if (this._isReceivingMessages()) {
const errorMessage = getAlreadyReceivingErrorMsg(this.entityPath);
const error = new Error(errorMessage);
logger.logError(error, `${this.logPrefix} is already receiving`);
throw error;
}
}
private _throwIfReceiverOrConnectionClosed(): void {
throwErrorIfConnectionClosed(this._context);
if (this.isClosed) {
const errorMessage = getReceiverClosedErrorMsg(this.entityPath);
const error = new Error(errorMessage);
logger.logError(error, `${this.logPrefix} is closed`);
throw error;
}
}
public get isClosed(): boolean {
return this._isClosed || this._context.wasConnectionCloseCalled;
}
async receiveMessages(
maxMessageCount: number,
options?: ReceiveMessagesOptions,
): Promise<ServiceBusReceivedMessage[]> {
this._throwIfReceiverOrConnectionClosed();
this._throwIfAlreadyReceiving();
throwTypeErrorIfParameterMissing(
this._context.connectionId,
"maxMessageCount",
maxMessageCount,
);
throwTypeErrorIfParameterTypeMismatch(
this._context.connectionId,
"maxMessageCount",
maxMessageCount,
"number",
);
if (isNaN(maxMessageCount) || maxMessageCount < 1) {
throw new TypeError(InvalidMaxMessageCountError);
}
const receiveMessages = async (): Promise<ServiceBusReceivedMessage[]> => {
if (!this._batchingReceiver || !this._context.messageReceivers[this._batchingReceiver.name]) {
const receiveOptions: ReceiveOptions = {
maxConcurrentCalls: 0,
receiveMode: this.receiveMode,
lockRenewer: this._lockRenewer,
skipParsingBodyAsJson: this.skipParsingBodyAsJson,
skipConvertingDate: this.skipConvertingDate,
};
this._batchingReceiver = this._createBatchingReceiver(
this._context,
this.entityPath,
receiveOptions,
);
}
const receivedMessages = await this._batchingReceiver.receive(
maxMessageCount,
options?.maxWaitTimeInMs ?? Constants.defaultOperationTimeoutInMs,
defaultMaxTimeAfterFirstMessageForBatchingMs,
options ?? {},
);
return receivedMessages;
};
const config: RetryConfig<ServiceBusReceivedMessage[]> = {
connectionHost: this._context.config.host,
connectionId: this._context.connectionId,
operation: receiveMessages,
operationType: RetryOperationType.receiveMessage,
abortSignal: options?.abortSignal,
retryOptions: this._retryOptions,
};
return retry<ServiceBusReceivedMessage[]>(config).catch((err) => {
throw translateServiceBusError(err);
});
}
getMessageIterator(
options?: GetMessageIteratorOptions,
): AsyncIterableIterator<ServiceBusReceivedMessage> {
return getMessageIterator(this, options);
}
async receiveDeferredMessages(
sequenceNumbers: Long | Long[],
options: OperationOptionsBase = {},
): Promise<ServiceBusReceivedMessage[]> {
this._throwIfReceiverOrConnectionClosed();
throwTypeErrorIfParameterMissing(
this._context.connectionId,
"sequenceNumbers",
sequenceNumbers,
);
throwTypeErrorIfParameterNotLong(
this._context.connectionId,
"sequenceNumbers",
sequenceNumbers,
);
const deferredSequenceNumbers = Array.isArray(sequenceNumbers)
? sequenceNumbers
: [sequenceNumbers];
const receiveDeferredMessagesOperationPromise = async (): Promise<
ServiceBusReceivedMessage[]
> => {
const deferredMessages = await this._context
.getManagementClient(this.entityPath)
.receiveDeferredMessages(deferredSequenceNumbers, this.receiveMode, undefined, {
...options,
associatedLinkName: this._getAssociatedReceiverName(),
requestName: "receiveDeferredMessages",
timeoutInMs: this._retryOptions.timeoutInMs,
skipParsingBodyAsJson: this.skipParsingBodyAsJson,
skipConvertingDate: this.skipConvertingDate,
});
return deferredMessages;
};
const config: RetryConfig<ServiceBusReceivedMessage[]> = {
operation: receiveDeferredMessagesOperationPromise,
connectionId: this._context.connectionId,
operationType: RetryOperationType.management,
retryOptions: this._retryOptions,
abortSignal: options?.abortSignal,
};
return retry<ServiceBusReceivedMessage[]>(config);
}
async deleteMessages(options: DeleteMessagesOptions): Promise<number> {
this._throwIfReceiverOrConnectionClosed();
const deleteMessagesOperationPromise = (): Promise<number> => {
return this._context
.getManagementClient(this.entityPath)
.deleteMessages(options.maxMessageCount, options?.beforeEnqueueTime, undefined, {
...options,
associatedLinkName: this._getAssociatedReceiverName(),
requestName: "deleteMessages",
timeoutInMs: this._retryOptions.timeoutInMs,
});
};
const config: RetryConfig<number> = {
operation: deleteMessagesOperationPromise,
connectionId: this._context.connectionId,
operationType: RetryOperationType.management,
retryOptions: this._retryOptions,
abortSignal: options?.abortSignal,
};
return retry<number>(config);
}
async purgeMessages(options?: PurgeMessagesOptions): Promise<number> {
let deletedCount = await this.deleteMessages({
maxMessageCount: MaxDeleteMessageCount,
beforeEnqueueTime: options?.beforeEnqueueTime,
});
logger.verbose(
`${this.logPrefix} receiver '${this.identifier}' deleted ${deletedCount} messages.`,
);
if (deletedCount > 0) {
let batchCount = deletedCount;
while (batchCount > 0) {
batchCount = await this.deleteMessages({
maxMessageCount: MaxDeleteMessageCount,
beforeEnqueueTime: options?.beforeEnqueueTime,
});
logger.verbose(
`${this.logPrefix} receiver '${this.identifier}' deleted ${batchCount} messages.`,
);
deletedCount += batchCount;
}
}
logger.verbose(
`${this.logPrefix} receiver '${this.identifier}' purged ${deletedCount} messages.`,
);
return deletedCount;
}
// ManagementClient methods # Begin
async peekMessages(
maxMessageCount: number,
options: PeekMessagesOptions = {},
): Promise<ServiceBusReceivedMessage[]> {
this._throwIfReceiverOrConnectionClosed();
const managementRequestOptions = {
...options,
associatedLinkName: this._getAssociatedReceiverName(),
requestName: "peekMessages",
timeoutInMs: this._retryOptions?.timeoutInMs,
skipParsingBodyAsJson: this.skipParsingBodyAsJson,
skipConvertingDate: this.skipConvertingDate,
};
const peekOperationPromise = async (): Promise<ServiceBusReceivedMessage[]> => {
if (options.fromSequenceNumber !== undefined) {
return this._context
.getManagementClient(this.entityPath)
.peekBySequenceNumber(
options.fromSequenceNumber,
maxMessageCount,
undefined,
options.omitMessageBody,
managementRequestOptions,
);
} else {
return this._context
.getManagementClient(this.entityPath)
.peek(maxMessageCount, options.omitMessageBody, managementRequestOptions);
}
};
const config: RetryConfig<ServiceBusReceivedMessage[]> = {
operation: peekOperationPromise,
connectionId: this._context.connectionId,
operationType: RetryOperationType.management,
retryOptions: this._retryOptions,
abortSignal: options?.abortSignal,
};
return retry<ServiceBusReceivedMessage[]>(config);
}
subscribe(
handlers: MessageHandlers,
options?: SubscribeOptions,
): {
close(): Promise<void>;
} {
assertValidMessageHandlers(handlers);
throwErrorIfConnectionClosed(this._context);
this._throwIfReceiverOrConnectionClosed();
this._throwIfAlreadyReceiving();
options = {
...(options ?? {}),
autoCompleteMessages: options?.autoCompleteMessages ?? true,
};
// When the user "stops" a streaming receiver (via the returned instance from 'subscribe' we just suspend
// it, leaving the link open). This allows users to stop the flow of messages but still be able to settle messages
// since the link itself hasn't been shut down.
//
// Users can, if they want, restart their subscription (since we've got a link already established).
// So you'll have an instance here if the user has done:
// 1. const subscription = receiver.subscribe()
// 2. subscription.stop()
// 3. receiver.subscribe()
this._streamingReceiver =
this._streamingReceiver ??
new StreamingReceiver(this.identifier, this._context, this.entityPath, {
...options,
receiveMode: this.receiveMode,
retryOptions: this._retryOptions,
lockRenewer: this._lockRenewer,
skipParsingBodyAsJson: this.skipParsingBodyAsJson,
skipConvertingDate: this.skipConvertingDate,
});
// this ensures that if the outer service bus client is closed that this receiver is cleaned up.
// this mostly affects us if we're in the middle of init() - the connection (and receiver) are not yet
// open but we do need to close the receiver to exit the init() loop.
this._context.messageReceivers[this._streamingReceiver.name] = this._streamingReceiver;
this._streamingReceiver.subscribe(handlers, options).catch((_) => {
// (the error will already have been reported to the user)
if (this._streamingReceiver) {
delete this._context.messageReceivers[this._streamingReceiver.name];
}
});
return {
close: async (): Promise<void> => {
return this._streamingReceiver?.stopReceivingMessages();
},
};
}
async completeMessage(message: ServiceBusReceivedMessage): Promise<void> {
this._throwIfReceiverOrConnectionClosed();
throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId);
const msgImpl = message as ServiceBusMessageImpl;
return completeMessage(msgImpl, this._context, this.entityPath, this._retryOptions);
}
async abandonMessage(
message: ServiceBusReceivedMessage,
propertiesToModify?: { [key: string]: number | boolean | string | Date | null },
): Promise<void> {
this._throwIfReceiverOrConnectionClosed();
throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId);
const msgImpl = message as ServiceBusMessageImpl;
return abandonMessage(
msgImpl,
this._context,
this.entityPath,
propertiesToModify,
this._retryOptions,
);
}
async deferMessage(
message: ServiceBusReceivedMessage,
propertiesToModify?: { [key: string]: number | boolean | string | Date | null },
): Promise<void> {
this._throwIfReceiverOrConnectionClosed();
throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId);
const msgImpl = message as ServiceBusMessageImpl;
return deferMessage(
msgImpl,
this._context,
this.entityPath,
propertiesToModify,
this._retryOptions,
);
}
async deadLetterMessage(
message: ServiceBusReceivedMessage,
options?: DeadLetterOptions & { [key: string]: number | boolean | string | Date | null },
): Promise<void> {
this._throwIfReceiverOrConnectionClosed();
throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId);
const msgImpl = message as ServiceBusMessageImpl;
return deadLetterMessage(msgImpl, this._context, this.entityPath, options, this._retryOptions);
}
async renewMessageLock(message: ServiceBusReceivedMessage): Promise<Date> {
this._throwIfReceiverOrConnectionClosed();
throwErrorIfInvalidOperationOnMessage(message, this.receiveMode, this._context.connectionId);
const tracingContext = extractSpanContextFromServiceBusMessage(message);
const spanLinks: TracingSpanLink[] = tracingContext ? [{ tracingContext }] : [];
return tracingClient.withSpan(
"ServiceBusReceiver.renewMessageLock",
{},
() => {
const msgImpl = message as ServiceBusMessageImpl;
let associatedLinkName: string | undefined;
if (msgImpl.delivery.link) {
const associatedReceiver = this._context.getReceiverFromCache(msgImpl.delivery.link.name);
associatedLinkName = associatedReceiver?.name;
}
return this._context
.getManagementClient(this.entityPath)
.renewLock(message.lockToken!, { associatedLinkName })
.then((lockedUntil) => {
message.lockedUntilUtc = lockedUntil;
return lockedUntil;
});
},
{
spanLinks,
...toSpanOptions(
{ entityPath: this.entityPath, host: this._context.config.host },
"receive",
"client",
),
},
);
}
async close(): Promise<void> {
try {
this._isClosed = true;
if (this._context.connection && this._context.connection.isOpen()) {
// Close the streaming receiver.
if (this._streamingReceiver) {
await this._streamingReceiver.close();
}
// Close the batching receiver.
if (this._batchingReceiver) {
await this._batchingReceiver.close();
}
}
} catch (err: any) {
logger.logError(err, `${this.logPrefix} An error occurred while closing the Receiver`);
throw err;
}
}
/**
* Indicates whether the receiver is currently receiving messages or not.
* When this returns true, new `registerMessageHandler()` or `receiveMessages()` calls cannot be made.
*/
private _isReceivingMessages(): boolean {
if (
this._streamingReceiver &&
this._streamingReceiver.isOpen() &&
this._streamingReceiver.isSubscribeActive
) {
return true;
}
if (
this._batchingReceiver &&
this._batchingReceiver.isOpen() &&
this._batchingReceiver.isReceivingMessages
) {
return true;
}
return false;
}
private _createBatchingReceiver(
context: ConnectionContext,
entityPath: string,
options: ReceiveOptions,
): BatchingReceiver {
const receiver = BatchingReceiver.create(this.identifier, context, entityPath, options);
logger.verbose(
`[${this.logPrefix}] receiver '${receiver.name}' created, with maxConcurrentCalls set to ${options.maxConcurrentCalls}.`,
);
return receiver;
}
/**
* Helper function to retrieve any active receiver name, regardless of streaming or
* batching if it exists. This is used for optimization on the service side
*/
private _getAssociatedReceiverName(): string | undefined {
if (this._streamingReceiver && this._streamingReceiver.isOpen()) {
return this._streamingReceiver.name;
}
if (
this._batchingReceiver &&
this._batchingReceiver.isOpen() &&
this._batchingReceiver.isReceivingMessages
) {
return this._batchingReceiver.name;
}
return;
}
}