/
messageReceiver.ts
1114 lines (1070 loc) · 40.2 KB
/
messageReceiver.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 {
translate,
Constants,
MessagingError,
retry,
RetryOperationType,
RetryConfig,
ConditionErrorNameMapper,
ErrorNameConditionMapper
} from "@azure/amqp-common";
import {
Receiver,
OnAmqpEvent,
EventContext,
ReceiverOptions,
AmqpError,
isAmqpError
} from "rhea-promise";
import * as log from "../log";
import { LinkEntity } from "./linkEntity";
import { ClientEntityContext } from "../clientEntityContext";
import { ServiceBusMessage, DispositionType, ReceiveMode } from "../serviceBusMessage";
import { getUniqueName, calculateRenewAfterDuration } from "../util/utils";
import { MessageHandlerOptions } from "./streamingReceiver";
import { DispositionStatusOptions } from "./managementClient";
/**
* @internal
*/
interface CreateReceiverOptions {
onMessage: OnAmqpEventAsPromise;
onClose: OnAmqpEventAsPromise;
onSessionClose: OnAmqpEventAsPromise;
onError: OnAmqpEvent;
onSettled: OnAmqpEvent;
onSessionError: OnAmqpEvent;
}
/**
* @internal
*/
export interface OnAmqpEventAsPromise extends OnAmqpEvent {
(context: EventContext): Promise<void>;
}
/**
* @internal
*/
export interface PromiseLike {
resolve: (value?: any) => void;
reject: (reason?: any) => void;
timer: NodeJS.Timer;
}
/**
* @internal
*/
export enum ReceiverType {
batching = "batching",
streaming = "streaming"
}
/**
* @internal
*/
export interface ReceiveOptions extends MessageHandlerOptions {
/**
* @property {number} [receiveMode] The mode in which messages should be received.
* Default: ReceiveMode.peekLock
*/
receiveMode?: ReceiveMode;
}
/**
* Describes the signature of the message handler passed to `registerMessageHandler` method.
*/
export interface OnMessage {
/**
* Handler for processing each incoming message.
*/
(message: ServiceBusMessage): Promise<void>;
}
/**
* Describes the signature of the error handler passed to `registerMessageHandler` method.
*/
export interface OnError {
/**
* Handler for any error that occurs while receiving or processing messages.
*/
(error: MessagingError | Error): void;
}
/**
* @internal
* Describes the MessageReceiver that will receive messages from ServiceBus.
* @class MessageReceiver
*/
export class MessageReceiver extends LinkEntity {
/**
* @property {string} receiverType The type of receiver: "batching" or "streaming".
*/
receiverType: ReceiverType;
/**
* @property {number} [maxConcurrentCalls] The maximum number of messages that should be
* processed concurrently while in streaming mode. Once this limit has been reached, more
* messages will not be received until the user's message handler has completed processing current message.
* Default: 1
*/
maxConcurrentCalls: number = 1;
/**
* @property {number} [receiveMode] The mode in which messages should be received.
* Default: ReceiveMode.peekLock
*/
receiveMode: ReceiveMode;
/**
* @property {boolean} autoComplete Indicates whether `Message.complete()` should be called
* automatically after the message processing is complete while receiving messages with handlers.
* Default: false.
*/
autoComplete: boolean;
/**
* @property {number} maxAutoRenewDurationInSeconds The maximum duration within which the
* lock will be renewed automatically. This value should be greater than the longest message
* lock duration; for example, the `lockDuration` property on the received message.
*
* Default: `300` (5 minutes);
*/
maxAutoRenewDurationInSeconds: number;
/**
* @property {number} [newMessageWaitTimeoutInSeconds] The maximum amount of idle time the
* receiver will wait after a message has been received. If no messages are received by this
* time then the receive operation will end.
*/
newMessageWaitTimeoutInSeconds?: number;
/**
* @property {boolean} autoRenewLock Should lock renewal happen automatically.
*/
autoRenewLock: boolean;
/**
* @property {Receiver} [_receiver] The AMQP receiver link.
* @protected
*/
protected _receiver?: Receiver;
/**
* @property {Map<number, Promise<any>>} _deliveryDispositionMap Maintains a map of deliveries that
* are being actively disposed. It acts as a store for correlating the responses received for
* active dispositions.
*/
protected _deliveryDispositionMap: Map<number, PromiseLike> = new Map<number, PromiseLike>();
/**
* @property {OnMessage} _onMessage The message handler provided by the user that will be wrapped
* inside _onAmqpMessage.
* @protected
*/
protected _onMessage!: OnMessage;
/**
* @property {OnMessage} _onError The error handler provided by the user that will be wrapped
* inside _onAmqpError.
* @protected
*/
protected _onError?: OnError;
/**
* @property {OnAmqpEventAsPromise} _onAmqpMessage The message handler that will be set as the handler on the
* underlying rhea receiver for the "message" event.
* @protected
*/
protected _onAmqpMessage: OnAmqpEventAsPromise;
/**
* @property {OnAmqpEventAsPromise} _onAmqpClose The message handler that will be set as the handler on the
* underlying rhea receiver for the "receiver_close" event.
* @protected
*/
protected _onAmqpClose: OnAmqpEventAsPromise;
/**
* @property {OnAmqpEvent} _onSessionError The message handler that will be set as the handler on
* the underlying rhea receiver's session for the "session_error" event.
* @protected
*/
protected _onSessionError: OnAmqpEvent;
/**
* @property {OnAmqpEventAsPromise} _onSessionClose The message handler that will be set as the handler on
* the underlying rhea receiver's session for the "session_close" event.
* @protected
*/
protected _onSessionClose: OnAmqpEventAsPromise;
/**
* @property {OnAmqpEvent} _onAmqpError The message handler that will be set as the handler on the
* underlying rhea receiver for the "receiver_error" event.
* @protected
*/
protected _onAmqpError: OnAmqpEvent;
/**
* @property {OnAmqpEvent} _onSettled The message handler that will be set as the handler on the
* underlying rhea receiver for the "settled" event.
* @protected
*/
protected _onSettled: OnAmqpEvent;
/**
* @property {boolean} wasCloseInitiated Denotes if receiver was explicitly closed by user.
* @protected
*/
protected wasCloseInitiated?: boolean;
/**
* @property {Map<string, Function>} _messageRenewLockTimers Maintains a map of messages for which
* the lock is automatically renewed.
* @protected
*/
protected _messageRenewLockTimers: Map<string, NodeJS.Timer | undefined> = new Map<
string,
NodeJS.Timer | undefined
>();
/**
* @property {NodeJS.Timer} _newMessageReceivedTimer The timer that keeps track of time since the
* last message was received.
*/
protected _newMessageReceivedTimer?: NodeJS.Timer;
/**
* Resets the `_newMessageReceivedTimer` timer when a new message is received.
*/
protected resetTimerOnNewMessageReceived: () => void;
/**
* @property {Function} _clearMessageLockRenewTimer Clears the message lock renew timer for a
* specific messageId.
* @protected
*/
protected _clearMessageLockRenewTimer: (messageId: string) => void;
/**
* @property {Function} _clearMessageLockRenewTimer Clears the message lock renew timer for all
* the active messages.
* @protected
*/
protected _clearAllMessageLockRenewTimers: () => void;
/**
* Indicates whether the receiver is already actively
* running `onDetached`.
* This is expected to be true while the receiver attempts
* to bring its link back up due to a retryable issue.
*/
private _isDetaching: boolean = false;
constructor(context: ClientEntityContext, receiverType: ReceiverType, options?: ReceiveOptions) {
super(context.entityPath, context, {
address: context.entityPath,
audience: `${context.namespace.config.endpoint}${context.entityPath}`
});
if (!options) options = {};
this.wasCloseInitiated = false;
this.receiverType = receiverType;
this.receiveMode = options.receiveMode || ReceiveMode.peekLock;
if (typeof options.maxConcurrentCalls === "number" && options.maxConcurrentCalls > 0) {
this.maxConcurrentCalls = options.maxConcurrentCalls;
}
this.resetTimerOnNewMessageReceived = () => {
/** */
};
// If explicitly set to false then autoComplete is false else true (default).
this.autoComplete = options.autoComplete === false ? options.autoComplete : true;
this.maxAutoRenewDurationInSeconds =
options.maxMessageAutoRenewLockDurationInSeconds != null
? options.maxMessageAutoRenewLockDurationInSeconds
: 300;
this.autoRenewLock =
this.maxAutoRenewDurationInSeconds > 0 && this.receiveMode === ReceiveMode.peekLock;
this._clearMessageLockRenewTimer = (messageId: string) => {
if (this._messageRenewLockTimers.has(messageId)) {
clearTimeout(this._messageRenewLockTimers.get(messageId) as NodeJS.Timer);
log.receiver(
"[%s] Cleared the message renew lock timer for message with id '%s'.",
this._context.namespace.connectionId,
messageId
);
this._messageRenewLockTimers.delete(messageId);
}
};
this._clearAllMessageLockRenewTimers = () => {
log.receiver(
"[%s] Clearing message renew lock timers for all the active messages.",
this._context.namespace.connectionId
);
for (const messageId of this._messageRenewLockTimers.keys()) {
this._clearMessageLockRenewTimer(messageId);
}
};
// setting all the handlers
this._onSettled = (context: EventContext) => {
const connectionId = this._context.namespace.connectionId;
const delivery = context.delivery;
if (delivery) {
const id = delivery.id;
const state = delivery.remote_state;
const settled = delivery.remote_settled;
log.receiver(
"[%s] Delivery with id %d, remote_settled: %s, remote_state: %o has been " + "received.",
connectionId,
id,
settled,
state && state.error ? state.error : state
);
if (settled && this._deliveryDispositionMap.has(id)) {
const promise = this._deliveryDispositionMap.get(id) as PromiseLike;
clearTimeout(promise.timer);
log.receiver(
"[%s] Found the delivery with id %d in the map and cleared the timer.",
connectionId,
id
);
const deleteResult = this._deliveryDispositionMap.delete(id);
log.receiver(
"[%s] Successfully deleted the delivery with id %d from the map.",
connectionId,
id,
deleteResult
);
if (state && state.error && (state.error.condition || state.error.description)) {
const error = translate(state.error);
return promise.reject(error);
}
return promise.resolve();
}
}
};
this._onAmqpMessage = async (context: EventContext) => {
// If the receiver got closed in PeekLock mode, avoid processing the message as we
// cannot settle the message.
if (
this.receiveMode === ReceiveMode.peekLock &&
(!this._receiver || !this._receiver.isOpen())
) {
log.error(
"[%s] Not calling the user's message handler for the current message " +
"as the receiver '%s' is closed",
this._context.namespace.connectionId,
this.name
);
return;
}
this.resetTimerOnNewMessageReceived();
const connectionId = this._context.namespace.connectionId;
const bMessage: ServiceBusMessage = new ServiceBusMessage(
this._context,
context.message!,
context.delivery!,
true
);
if (this.autoRenewLock && bMessage.lockToken) {
const lockToken = bMessage.lockToken;
// - We need to renew locks before they expire by looking at bMessage.lockedUntilUtc.
// - This autorenewal needs to happen **NO MORE** than maxAutoRenewDurationInSeconds
// - We should be able to clear the renewal timer when the user's message handler
// is done (whether it succeeds or fails).
// Setting the messageId with undefined value in the _messageRenewockTimers Map because we
// track state by checking the presence of messageId in the map. It is removed from the map
// when an attempt is made to settle the message (either by the user or by the sdk) OR
// when the execution of user's message handler completes.
this._messageRenewLockTimers.set(bMessage.messageId as string, undefined);
log.receiver(
"[%s] message with id '%s' is locked until %s.",
connectionId,
bMessage.messageId,
bMessage.lockedUntilUtc!.toString()
);
const totalAutoLockRenewDuration = Date.now() + this.maxAutoRenewDurationInSeconds * 1000;
log.receiver(
"[%s] Total autolockrenew duration for message with id '%s' is: ",
connectionId,
bMessage.messageId,
new Date(totalAutoLockRenewDuration).toString()
);
const autoRenewLockTask = (): void => {
if (
new Date(totalAutoLockRenewDuration) > bMessage.lockedUntilUtc! &&
Date.now() < totalAutoLockRenewDuration
) {
if (this._messageRenewLockTimers.has(bMessage.messageId as string)) {
// TODO: We can run into problems with clock skew between the client and the server.
// It would be better to calculate the duration based on the "lockDuration" property
// of the queue. However, we do not have the management plane of the client ready for
// now. Hence we rely on the lockedUntilUtc property on the message set by ServiceBus.
const amount = calculateRenewAfterDuration(bMessage.lockedUntilUtc!);
log.receiver(
"[%s] Sleeping for %d milliseconds while renewing the lock for " +
"message with id '%s' is: ",
connectionId,
amount,
bMessage.messageId
);
// Setting the value of the messageId to the actual timer. This will be cleared when
// an attempt is made to settle the message (either by the user or by the sdk) OR
// when the execution of user's message handler completes.
this._messageRenewLockTimers.set(
bMessage.messageId as string,
setTimeout(async () => {
try {
log.receiver(
"[%s] Attempting to renew the lock for message with id '%s'.",
connectionId,
bMessage.messageId
);
bMessage.lockedUntilUtc = await this._context.managementClient!.renewLock(
lockToken
);
log.receiver(
"[%s] Successfully renewed the lock for message with id '%s'.",
connectionId,
bMessage.messageId
);
log.receiver(
"[%s] Calling the autorenewlock task again for message with " + "id '%s'.",
connectionId,
bMessage.messageId
);
autoRenewLockTask();
} catch (err) {
log.error(
"[%s] An error occured while auto renewing the message lock '%s' " +
"for message with id '%s': %O.",
connectionId,
bMessage.lockToken,
bMessage.messageId,
err
);
// Let the user know that there was an error renewing the message lock.
this._onError!(err);
}
}, amount)
);
} else {
log.receiver(
"[%s] Looks like the message lock renew timer has already been " +
"cleared for message with id '%s'.",
connectionId,
bMessage.messageId
);
}
} else {
log.receiver(
"[%s] Current time %s exceeds the total autolockrenew duration %s for " +
"message with messageId '%s'. Hence we will stop the autoLockRenewTask.",
connectionId,
new Date(Date.now()).toString(),
new Date(totalAutoLockRenewDuration).toString(),
bMessage.messageId
);
this._clearMessageLockRenewTimer(bMessage.messageId as string);
}
};
// start
autoRenewLockTask();
}
try {
await this._onMessage(bMessage);
this._clearMessageLockRenewTimer(bMessage.messageId as string);
} catch (err) {
// This ensures we call users' error handler when users' message handler throws.
if (!isAmqpError(err)) {
log.error(
"[%s] An error occurred while running user's message handler for the message " +
"with id '%s' on the receiver '%s': %O",
connectionId,
bMessage.messageId,
this.name,
err
);
this._onError!(err);
}
// Do not want renewLock to happen unnecessarily, while abandoning the message. Hence,
// doing this here. Otherwise, this should be done in finally.
this._clearMessageLockRenewTimer(bMessage.messageId as string);
const error = translate(err);
// Nothing much to do if user's message handler throws. Let us try abandoning the message.
if (
!bMessage.delivery.remote_settled &&
error.name !== ConditionErrorNameMapper["com.microsoft:message-lock-lost"] &&
this.receiveMode === ReceiveMode.peekLock &&
this.isOpen() // only try to abandon the messages if the connection is still open
) {
try {
log.error(
"[%s] Abandoning the message with id '%s' on the receiver '%s' since " +
"an error occured: %O.",
connectionId,
bMessage.messageId,
this.name,
error
);
await bMessage.abandon();
} catch (abandonError) {
const translatedError = translate(abandonError);
log.error(
"[%s] An error occurred while abandoning the message with id '%s' on the " +
"receiver '%s': %O.",
connectionId,
bMessage.messageId,
this.name,
translatedError
);
this._onError!(translatedError);
}
}
return;
} finally {
if (this._receiver) {
this._receiver.addCredit(1);
}
}
// If we've made it this far, then user's message handler completed fine. Let us try
// completing the message.
if (
this.autoComplete &&
this.receiveMode === ReceiveMode.peekLock &&
!bMessage.delivery.remote_settled
) {
try {
log[this.receiverType](
"[%s] Auto completing the message with id '%s' on " + "the receiver '%s'.",
connectionId,
bMessage.messageId,
this.name
);
await bMessage.complete();
} catch (completeError) {
const translatedError = translate(completeError);
log.error(
"[%s] An error occurred while completing the message with id '%s' on the " +
"receiver '%s': %O.",
connectionId,
bMessage.messageId,
this.name,
translatedError
);
this._onError!(translatedError);
}
}
};
this._onAmqpError = (context: EventContext) => {
const connectionId = this._context.namespace.connectionId;
const receiver = this._receiver || context.receiver!;
const receiverError = context.receiver && context.receiver.error;
if (receiverError) {
const sbError = translate(receiverError);
log.error(
"[%s] An error occurred for Receiver '%s': %O.",
connectionId,
this.name,
sbError
);
if (!sbError.retryable) {
if (receiver && !receiver.isItselfClosed()) {
log.error(
"[%s] Since the user did not close the receiver and the error is not " +
"retryable, we let the user know about it by calling the user's error handler.",
connectionId
);
this._onError!(sbError);
} else {
log.error(
"[%s] The received error is not retryable. However, the receiver was " +
"closed by the user. Hence not notifying the user's error handler.",
connectionId
);
}
} else {
log.error(
"[%s] Since received error is retryable, we will NOT notify the user's " +
"error handler.",
connectionId
);
}
}
if (this._newMessageReceivedTimer) {
clearTimeout(this._newMessageReceivedTimer);
}
};
this._onSessionError = (context: EventContext) => {
const connectionId = this._context.namespace.connectionId;
const receiver = this._receiver || context.receiver!;
const sessionError = context.session && context.session.error;
if (sessionError) {
const sbError = translate(sessionError);
log.error(
"[%s] An error occurred on the session for Receiver '%s': %O.",
connectionId,
this.name,
sbError
);
if (receiver && !receiver.isSessionItselfClosed() && !sbError.retryable) {
log.error(
"[%s] Since the user did not close the receiver and the session error is not " +
"retryable, we let the user know about it by calling the user's error handler.",
connectionId
);
this._onError!(sbError);
}
}
if (this._newMessageReceivedTimer) {
clearTimeout(this._newMessageReceivedTimer);
}
};
this._onAmqpClose = async (context: EventContext) => {
const connectionId = this._context.namespace.connectionId;
const receiverError = context.receiver && context.receiver.error;
const receiver = this._receiver || context.receiver!;
if (receiverError) {
log.error(
"[%s] 'receiver_close' event occurred for receiver '%s' with address '%s'. " +
"The associated error is: %O",
connectionId,
this.name,
this.address,
receiverError
);
}
this._clearAllMessageLockRenewTimers();
if (receiver && !receiver.isItselfClosed()) {
if (!this.isConnecting) {
log.error(
"[%s] 'receiver_close' event occurred on the receiver '%s' with address '%s' " +
"and the sdk did not initiate this. The receiver is not reconnecting. Hence, calling " +
"detached from the _onAmqpClose() handler.",
connectionId,
this.name,
this.address
);
await this.onDetached(receiverError);
} else {
log.error(
"[%s] 'receiver_close' event occurred on the receiver '%s' with address '%s' " +
"and the sdk did not initate this. Moreover the receiver is already re-connecting. " +
"Hence not calling detached from the _onAmqpClose() handler.",
connectionId,
this.name,
this.address
);
}
} else {
log.error(
"[%s] 'receiver_close' event occurred on the receiver '%s' with address '%s' " +
"because the sdk initiated it. Hence not calling detached from the _onAmqpClose" +
"() handler.",
connectionId,
this.name,
this.address
);
}
};
this._onSessionClose = async (context: EventContext) => {
const connectionId = this._context.namespace.connectionId;
const receiver = this._receiver || context.receiver!;
const sessionError = context.session && context.session.error;
if (sessionError) {
log.error(
"[%s] 'session_close' event occurred for receiver '%s' with address '%s'. " +
"The associated error is: %O",
connectionId,
this.name,
this.address,
sessionError
);
}
this._clearAllMessageLockRenewTimers();
if (receiver && !receiver.isSessionItselfClosed()) {
if (!this.isConnecting) {
log.error(
"[%s] 'session_close' event occurred on the session of receiver '%s' with " +
"address '%s' and the sdk did not initiate this. Hence calling detached from the " +
"_onSessionClose() handler.",
connectionId,
this.name,
this.address
);
await this.onDetached(sessionError);
} else {
log.error(
"[%s] 'session_close' event occurred on the session of receiver '%s' with " +
"address '%s' and the sdk did not initiate this. Moreover the receiver is already " +
"re-connecting. Hence not calling detached from the _onSessionClose() handler.",
connectionId,
this.name,
this.address
);
}
} else {
log.error(
"[%s] 'session_close' event occurred on the session of receiver '%s' with address " +
"'%s' because the sdk initiated it. Hence not calling detached from the _onSessionClose" +
"() handler.",
connectionId,
this.name,
this.address
);
}
};
}
/**
* Creates the options that need to be specified while creating an AMQP receiver link.
*/
protected _createReceiverOptions(
useNewName?: boolean,
options?: CreateReceiverOptions
): ReceiverOptions {
if (!options) {
options = {
onMessage: (context: EventContext) =>
this._onAmqpMessage(context).catch(() => {
/* */
}),
onClose: (context: EventContext) =>
this._onAmqpClose(context).catch(() => {
/* */
}),
onSessionClose: (context: EventContext) =>
this._onSessionClose(context).catch(() => {
/* */
}),
onError: this._onAmqpError,
onSessionError: this._onSessionError,
onSettled: this._onSettled
};
}
const rcvrOptions: ReceiverOptions = {
name: useNewName ? getUniqueName(this._context.entityPath) : this.name,
autoaccept: this.receiveMode === ReceiveMode.receiveAndDelete ? true : false,
// receiveAndDelete -> first(0), peekLock -> second (1)
rcv_settle_mode: this.receiveMode === ReceiveMode.receiveAndDelete ? 0 : 1,
// receiveAndDelete -> settled (1), peekLock -> unsettled (0)
snd_settle_mode: this.receiveMode === ReceiveMode.receiveAndDelete ? 1 : 0,
source: {
address: this.address
},
credit_window: 0,
...options
};
return rcvrOptions;
}
/**
* Creates a new AMQP receiver under a new AMQP session.
* @protected
*
* @returns {Promise<void>} Promise<void>.
*/
protected async _init(options?: ReceiverOptions): Promise<void> {
const connectionId = this._context.namespace.connectionId;
try {
if (!this.isOpen() && !this.isConnecting) {
if (this.wasCloseInitiated) {
// in track 1 we'll maintain backwards compatible behavior for the codebase and
// just treat this as a no-op. There are cases, like in onDetached, where throwing
// an error here could have unintended consequences.
return;
}
log.error(
"[%s] The receiver '%s' with address '%s' is not open and is not currently " +
"establishing itself. Hence let's try to connect.",
connectionId,
this.name,
this.address
);
if (options && options.name) {
this.name = options.name;
}
this.isConnecting = true;
await this._negotiateClaim();
if (!options) {
options = this._createReceiverOptions();
}
log.error(
"[%s] Trying to create receiver '%s' with options %O",
connectionId,
this.name,
options
);
this._receiver = await this._context.namespace.connection.createReceiver(options);
this.isConnecting = false;
log.error(
"[%s] Receiver '%s' with address '%s' has established itself.",
connectionId,
this.name,
this.address
);
log[this.receiverType](
"Promise to create the receiver resolved. " + "Created receiver with name: ",
this.name
);
log[this.receiverType](
"[%s] Receiver '%s' created with receiver options: %O",
connectionId,
this.name,
options
);
// It is possible for someone to close the receiver and then start it again.
// Thus make sure that the receiver is present in the client cache.
if (this.receiverType === ReceiverType.streaming && !this._context.streamingReceiver) {
this._context.streamingReceiver = this as any;
} else if (this.receiverType === ReceiverType.batching && !this._context.batchingReceiver) {
this._context.batchingReceiver = this as any;
}
await this._ensureTokenRenewal();
} else {
log.error(
"[%s] The receiver '%s' with address '%s' is open -> %s and is connecting " +
"-> %s. Hence not reconnecting.",
connectionId,
this.name,
this.address,
this.isOpen(),
this.isConnecting
);
}
} catch (err) {
this.isConnecting = false;
err = translate(err);
log.error(
"[%s] An error occured while creating the receiver '%s': %O",
this._context.namespace.connectionId,
this.name,
err
);
throw err;
}
}
protected _deleteFromCache(): void {
this._receiver = undefined;
if (this.receiverType === ReceiverType.streaming) {
this._context.streamingReceiver = undefined;
} else if (this.receiverType === ReceiverType.batching) {
this._context.batchingReceiver = undefined;
}
log.error(
"[%s] Deleted the receiver '%s' from the client cache.",
this._context.namespace.connectionId,
this.name
);
}
/**
* Will reconnect the receiver link if necessary.
* @param receiverError The receiver error or connection error, if any.
* @param connectionDidDisconnect Whether this method is called as a result of a connection disconnect.
* @returns {Promise<void>} Promise<void>.
*/
async onDetached(receiverError?: AmqpError | Error, causedByDisconnect?: boolean): Promise<void> {
const connectionId = this._context.namespace.connectionId;
// User explicitly called `close` on the receiver, so link is already closed
// and we can exit early.
if (this.wasCloseInitiated) {
return;
}
// Prevent multiple onDetached invocations from running concurrently.
if (this._isDetaching) {
// This can happen when the network connection goes down for some amount of time.
// The first connection `disconnect` will trigger `onDetached` and attempt to retry
// creating the connection/receiver link.
// While those retry attempts fail (until the network connection comes back up),
// we'll continue to see connection `disconnect` errors.
// These should be ignored until the already running `onDetached` completes
// its retry attempts or errors.
log.error(
`[${connectionId}] Call to detached on streaming receiver '${this.name}' is already in progress.`
);
return;
}
this._isDetaching = true;
try {
// Clears the token renewal timer. Closes the link and its session if they are open.
// Removes the link and its session if they are present in rhea's cache.
await this._closeLink(this._receiver);
if (this.receiverType === ReceiverType.batching) {
log.error(
"[%s] Receiver '%s' with address '%s' is a Batching Receiver, so we will not be " +
"re-establishing the receiver link.",
connectionId,
this.name,
this.address
);
return;
}
const translatedError = receiverError ? translate(receiverError) : receiverError;
// We should only attempt to reopen if either no error was present,
// or the error is considered retryable.
const shouldReopen = !translatedError || translatedError.retryable;
// Non-retryable errors that aren't caused by disconnect
// will have already been forwarded to the user's error handler.
// Swallow the error and return quickly.
if (!shouldReopen && !causedByDisconnect) {
log.error(
"[%s] Encountered a non retryable error on the receiver. Cannot recover receiver '%s' with address '%s' encountered error: %O",
connectionId,
this.name,
this.address,
translatedError
);
return;
}
// Non-retryable errors that are caused by disconnect
// haven't had a chance to show up in the user's error handler.
// Rethrow the error so the surrounding try/catch forwards it appropriately.
if (!shouldReopen && causedByDisconnect) {
log.error(
"[%s] Encountered a non retryable error on the connection. Cannot recover receiver '%s' with address '%s': %O",
connectionId,
this.name,
this.address,
translatedError
);
throw translatedError;
}
// provide a new name to the link while re-connecting it. This ensures that
// the service does not send an error stating that the link is still open.
const options: ReceiverOptions = this._createReceiverOptions(true);
// shall retry forever at an interval of 15 seconds if the error is a retryable error
// else bail out when the error is not retryable or the oepration succeeds.
const config: RetryConfig<void> = {
operation: () =>
this._init(options).then(async () => {
if (this.wasCloseInitiated) {
log.error(
"[%s] close() method of Receiver '%s' with address '%s' was called. " +
"by the time the receiver finished getting created. Hence, disallowing messages from being received. ",
connectionId,
this.name,
this.address
);
await this.close();
} else {
if (this._receiver && this.receiverType === ReceiverType.streaming) {
this._receiver.addCredit(this.maxConcurrentCalls);
}
}
return;
}),
connectionId: connectionId,
operationType: RetryOperationType.receiverLink,
times: Constants.defaultConnectionRetryAttempts,
connectionHost: this._context.namespace.config.host,
delayInSeconds: 15
};
// Attempt to reconnect. If a non-retryable error is encountered,
// retry will throw and the error will surface to the user's error handler.
await retry<void>(config);
} catch (err) {
log.error(
"[%s] An error occurred while processing detached() of Receiver '%s': %O ",
connectionId,
this.name,
this.address,
err
);
if (typeof this._onError === "function") {
log.error(
"[%s] Unable to automatically reconnect Receiver '%s' with address '%s'.",
connectionId,
this.name,
this.address
);
try {
this._onError(err);
} catch (err) {
log.error(
"[%s] User-code error in error handler called after disconnect: %O",
connectionId,
err
);
} finally {
// Once the user's error handler has been called,
// close the receiver to prevent future messages/errors from being received.
// Swallow errors from the close rather than forwarding to user's error handler
// to prevent a never ending loop.
await this.close().catch(() => {});