-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
messageSender.ts
750 lines (724 loc) · 26.4 KB
/
messageSender.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as log from "../log";
import {
messageProperties,
Sender,
EventContext,
OnAmqpEvent,
SenderOptions,
SenderEvents,
message as RheaMessageUtil,
AmqpError,
generate_uuid
} from "rhea-promise";
import {
defaultLock,
Func,
retry,
translate,
AmqpMessage,
ErrorNameConditionMapper,
RetryConfig,
RetryOperationType,
Constants,
randomNumberFromInterval
} from "@azure/amqp-common";
import {
SendableMessageInfo,
toAmqpMessage,
getMessagePropertyTypeMismatchError
} from "../serviceBusMessage";
import { ClientEntityContext } from "../clientEntityContext";
import { LinkEntity } from "./linkEntity";
import { getUniqueName } from "../util/utils";
import { throwErrorIfConnectionClosed } from "../util/errors";
/**
* @internal
*/
interface CreateSenderOptions {
newName?: boolean;
}
/**
* @internal
* Describes the MessageSender that will send messages to ServiceBus.
* @class MessageSender
*/
export class MessageSender extends LinkEntity {
/**
* @property {string} senderLock The unqiue lock name per connection that is used to acquire the
* lock for establishing a sender link by an entity on that connection.
* @readonly
*/
readonly senderLock: string = `sender-${generate_uuid()}`;
/**
* @property {OnAmqpEvent} _onAmqpError The handler function to handle errors that happen on the
* underlying sender.
* @readonly
*/
private readonly _onAmqpError: OnAmqpEvent;
/**
* @property {OnAmqpEvent} _onAmqpClose The handler function to handle "sender_close" event
* that happens on the underlying sender.
* @readonly
*/
private readonly _onAmqpClose: OnAmqpEvent;
/**
* @property {OnAmqpEvent} _onSessionError The message handler that will be set as the handler on
* the underlying rhea sender's session for the "session_error" event.
* @private
*/
private _onSessionError: OnAmqpEvent;
/**
* @property {OnAmqpEvent} _onSessionClose The message handler that will be set as the handler on
* the underlying rhea sender's session for the "session_close" event.
* @private
*/
private _onSessionClose: OnAmqpEvent;
/**
* @property {Sender} [_sender] The AMQP sender link.
* @private
*/
private _sender?: Sender;
/**
* Creates a new MessageSender instance.
* @constructor
* @param {ClientEntityContext} context The client entity context.
*/
constructor(context: ClientEntityContext) {
super(context.entityPath, context, {
address: context.entityPath,
audience: `${context.namespace.config.endpoint}${context.entityPath}`
});
this._onAmqpError = (context: EventContext) => {
const senderError = context.sender && context.sender.error;
if (senderError) {
const err = translate(senderError);
log.error(
"[%s] An error occurred for sender '%s': %O.",
this._context.namespace.connectionId,
this.name,
err
);
}
};
this._onSessionError = (context: EventContext) => {
const sessionError = context.session && context.session.error;
if (sessionError) {
const err = translate(sessionError);
log.error(
"[%s] An error occurred on the session of sender '%s': %O.",
this._context.namespace.connectionId,
this.name,
err
);
}
};
this._onAmqpClose = async (context: EventContext) => {
const sender = this._sender || context.sender!;
const senderError = context.sender && context.sender.error;
if (senderError) {
log.error(
"[%s] 'sender_close' event occurred for sender '%s' with address '%s'. " +
"The associated error is: %O",
this._context.namespace.connectionId,
this.name,
this.address,
senderError
);
}
if (sender && !sender.isItselfClosed()) {
if (!this.isConnecting) {
log.error(
"[%s] 'sender_close' event occurred on the sender '%s' with address '%s' " +
"and the sdk did not initiate this. The sender is not reconnecting. Hence, calling " +
"detached from the _onAmqpClose() handler.",
this._context.namespace.connectionId,
this.name,
this.address
);
await this.onDetached(senderError);
} else {
log.error(
"[%s] 'sender_close' event occurred on the sender '%s' with address '%s' " +
"and the sdk did not initate this. Moreover the sender is already re-connecting. " +
"Hence not calling detached from the _onAmqpClose() handler.",
this._context.namespace.connectionId,
this.name,
this.address
);
}
} else {
log.error(
"[%s] 'sender_close' event occurred on the sender '%s' with address '%s' " +
"because the sdk initiated it. Hence not calling detached from the _onAmqpClose" +
"() handler.",
this._context.namespace.connectionId,
this.name,
this.address
);
}
};
this._onSessionClose = async (context: EventContext) => {
const sender = this._sender || context.sender!;
const sessionError = context.session && context.session.error;
if (sessionError) {
log.error(
"[%s] 'session_close' event occurred for sender '%s' with address '%s'. " +
"The associated error is: %O",
this._context.namespace.connectionId,
this.name,
this.address,
sessionError
);
}
if (sender && !sender.isSessionItselfClosed()) {
if (!this.isConnecting) {
log.error(
"[%s] 'session_close' event occurred on the session of sender '%s' with " +
"address '%s' and the sdk did not initiate this. Hence calling detached from the " +
"_onSessionClose() handler.",
this._context.namespace.connectionId,
this.name,
this.address
);
await this.onDetached(sessionError);
} else {
log.error(
"[%s] 'session_close' event occurred on the session of sender '%s' with " +
"address '%s' and the sdk did not initiate this. Moreover the sender is already " +
"re-connecting. Hence not calling detached from the _onSessionClose() handler.",
this._context.namespace.connectionId,
this.name,
this.address
);
}
} else {
log.error(
"[%s] 'session_close' event occurred on the session of sender '%s' with address " +
"'%s' because the sdk initiated it. Hence not calling detached from the _onSessionClose" +
"() handler.",
this._context.namespace.connectionId,
this.name,
this.address
);
}
};
}
private _deleteFromCache(): void {
this._sender = undefined;
delete this._context.sender;
log.error(
"[%s] Deleted the sender '%s' with address '%s' from the client cache.",
this._context.namespace.connectionId,
this.name,
this.address
);
}
private _createSenderOptions(options: CreateSenderOptions): SenderOptions {
if (options.newName) this.name = getUniqueName(this._context.entityPath);
const srOptions: SenderOptions = {
name: this.name,
target: {
address: this.address
},
onError: this._onAmqpError,
onClose: this._onAmqpClose,
onSessionError: this._onSessionError,
onSessionClose: this._onSessionClose
};
log.sender("Creating sender with options: %O", srOptions);
return srOptions;
}
/**
* Tries to send the message to ServiceBus if there is enough credit to send them
* and the circular buffer has available space to settle the message after sending them.
*
* We have implemented a synchronous send over here in the sense that we shall be waiting
* for the message to be accepted or rejected and accordingly resolve or reject the promise.
*
* @param encodedMessage The encoded message to be sent to ServiceBus.
* @param sendBatch Boolean indicating whether the encoded message represents a batch of messages or not
* @return {Promise<Delivery>} Promise<Delivery>
*/
private _trySend(encodedMessage: Buffer, sendBatch?: boolean): Promise<void> {
const sendEventPromise = () =>
new Promise<void>((resolve, reject) => {
let waitTimer: any;
log.sender(
"[%s] Sender '%s', credit: %d available: %d",
this._context.namespace.connectionId,
this.name,
this._sender!.credit,
this._sender!.session.outgoing.available()
);
if (this._sender!.sendable()) {
let onRejected: Func<EventContext, void>;
let onReleased: Func<EventContext, void>;
let onModified: Func<EventContext, void>;
let onAccepted: Func<EventContext, void>;
const removeListeners = (): void => {
clearTimeout(waitTimer);
// When `removeListeners` is called on timeout, the sender might be closed and cleared
// So, check if it exists, before removing listeners from it.
if (this._sender) {
this._sender.removeListener(SenderEvents.rejected, onRejected);
this._sender.removeListener(SenderEvents.accepted, onAccepted);
this._sender.removeListener(SenderEvents.released, onReleased);
this._sender.removeListener(SenderEvents.modified, onModified);
}
};
onAccepted = (context: EventContext) => {
// Since we will be adding listener for accepted and rejected event every time
// we send a message, we need to remove listener for both the events.
// This will ensure duplicate listeners are not added for the same event.
removeListeners();
log.sender(
"[%s] Sender '%s', got event accepted.",
this._context.namespace.connectionId,
this.name
);
resolve();
};
onRejected = (context: EventContext) => {
removeListeners();
log.error(
"[%s] Sender '%s', got event rejected.",
this._context.namespace.connectionId,
this.name
);
const err = translate(context!.delivery!.remote_state!.error);
reject(err);
};
onReleased = (context: EventContext) => {
removeListeners();
log.error(
"[%s] Sender '%s', got event released.",
this._context.namespace.connectionId,
this.name
);
let err: Error;
if (context!.delivery!.remote_state!.error) {
err = translate(context!.delivery!.remote_state!.error);
} else {
err = new Error(
`[${this._context.namespace.connectionId}]Sender '${this.name}', ` +
`received a release disposition.Hence we are rejecting the promise.`
);
}
reject(err);
};
onModified = (context: EventContext) => {
removeListeners();
log.error(
"[%s] Sender '%s', got event modified.",
this._context.namespace.connectionId,
this.name
);
let err: Error;
if (context!.delivery!.remote_state!.error) {
err = translate(context!.delivery!.remote_state!.error);
} else {
err = new Error(
`[${this._context.namespace.connectionId}]Sender "${this.name}", ` +
`received a modified disposition.Hence we are rejecting the promise.`
);
}
reject(err);
};
const actionAfterTimeout = () => {
removeListeners();
const desc: string =
`[${this._context.namespace.connectionId}] Sender "${this.name}" ` +
`with address "${this.address}", was not able to send the message right now, due ` +
`to operation timeout.`;
log.error(desc);
const e: AmqpError = {
condition: ErrorNameConditionMapper.ServiceUnavailableError,
description: desc
};
return reject(translate(e));
};
this._sender!.on(SenderEvents.accepted, onAccepted);
this._sender!.on(SenderEvents.rejected, onRejected);
this._sender!.on(SenderEvents.modified, onModified);
this._sender!.on(SenderEvents.released, onReleased);
waitTimer = setTimeout(
actionAfterTimeout,
Constants.defaultOperationTimeoutInSeconds * 1000
);
try {
const delivery = this._sender!.send(
encodedMessage,
undefined,
sendBatch ? 0x80013700 : 0
);
log.sender(
"[%s] Sender '%s', sent message with delivery id: %d",
this._context.namespace.connectionId,
this.name,
delivery.id
);
} catch (error) {
removeListeners();
return reject(error);
}
} else {
// let us retry to send the message after some time.
const msg =
`[${this._context.namespace.connectionId}] Sender "${this.name}", ` +
`cannot send the message right now. Please try later.`;
log.error(msg);
const amqpError: AmqpError = {
condition: ErrorNameConditionMapper.SenderBusyError,
description: msg
};
reject(translate(amqpError));
}
});
const jitterInSeconds = randomNumberFromInterval(1, 4);
const config: RetryConfig<void> = {
operation: sendEventPromise,
connectionId: this._context.namespace.connectionId!,
operationType: RetryOperationType.sendMessage,
times: Constants.defaultRetryAttempts,
delayInSeconds: Constants.defaultDelayBetweenOperationRetriesInSeconds + jitterInSeconds
};
return retry<void>(config);
}
/**
* Initializes the sender session on the connection.
*/
private async _init(options?: SenderOptions): Promise<void> {
try {
// isOpen isConnecting Should establish
// true false No
// true true No
// false true No
// false false Yes
if (!this.isOpen()) {
log.error(
"[%s] The sender '%s' with address '%s' is not open and is not currently " +
"establishing itself. Hence let's try to connect.",
this._context.namespace.connectionId,
this.name,
this.address
);
this.isConnecting = true;
await this._negotiateClaim();
log.error(
"[%s] Trying to create sender '%s'...",
this._context.namespace.connectionId,
this.name
);
if (!options) {
options = this._createSenderOptions({});
}
this._sender = await this._context.namespace.connection.createSender(options);
this.isConnecting = false;
log.error(
"[%s] Sender '%s' with address '%s' has established itself.",
this._context.namespace.connectionId,
this.name,
this.address
);
this._sender.setMaxListeners(1000);
log.error(
"[%s] Promise to create the sender resolved. Created sender with name: %s",
this._context.namespace.connectionId,
this.name
);
log.error(
"[%s] Sender '%s' created with sender options: %O",
this._context.namespace.connectionId,
this.name,
options
);
// It is possible for someone to close the sender and then start it again.
// Thus make sure that the sender is present in the client cache.
if (!this._sender) this._context.sender = this;
await this._ensureTokenRenewal();
}
} catch (err) {
err = translate(err);
log.error(
"[%s] An error occurred while creating the sender %s",
this._context.namespace.connectionId,
this.name,
err
);
throw err;
}
}
/**
* Will reconnect the sender link if necessary.
* @param {AmqpError | Error} [senderError] The sender error if any.
* @returns {Promise<void>} Promise<void>.
*/
async onDetached(senderError?: AmqpError | Error): Promise<void> {
try {
const wasCloseInitiated = this._sender && this._sender.isItselfClosed();
// 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._sender);
// We should attempt to reopen only when the sender(sdk) did not initiate the close
let shouldReopen = false;
if (senderError && !wasCloseInitiated) {
const translatedError = translate(senderError);
if (translatedError.retryable) {
shouldReopen = true;
log.error(
"[%s] close() method of Sender '%s' with address '%s' was not called. There " +
"was an accompanying error an it is retryable. This is a candidate for re-establishing " +
"the sender link.",
this._context.namespace.connectionId,
this.name,
this.address
);
} else {
log.error(
"[%s] close() method of Sender '%s' with address '%s' was not called. There " +
"was an accompanying error and it is NOT retryable. Hence NOT re-establishing " +
"the sender link.",
this._context.namespace.connectionId,
this.name,
this.address
);
}
} else if (!wasCloseInitiated) {
shouldReopen = true;
log.error(
"[%s] close() method of Sender '%s' with address '%s' was not called. There " +
"was no accompanying error as well. This is a candidate for re-establishing " +
"the sender link.",
this._context.namespace.connectionId,
this.name,
this.address
);
} else {
const state: any = {
wasCloseInitiated: wasCloseInitiated,
senderError: senderError,
_sender: this._sender
};
log.error(
"[%s] Something went wrong. State of sender '%s' with address '%s' is: %O",
this._context.namespace.connectionId,
this.name,
this.address,
state
);
}
if (shouldReopen) {
await defaultLock.acquire(this.senderLock, () => {
const options: SenderOptions = this._createSenderOptions({
newName: 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),
connectionId: this._context.namespace.connectionId!,
operationType: RetryOperationType.senderLink,
times: Constants.defaultConnectionRetryAttempts,
connectionHost: this._context.namespace.config.host,
delayInSeconds: 15
};
return retry<void>(config);
});
}
} catch (err) {
log.error(
"[%s] An error occurred while processing detached() of Sender '%s' with address " +
"'%s': %O",
this._context.namespace.connectionId,
this.name,
this.address,
err
);
}
}
/**
* Deletes the sender fromt the context. Clears the token renewal timer. Closes the sender link.
* @return {Promise<void>} Promise<void>
*/
async close(): Promise<void> {
if (this._sender) {
log.sender(
"[%s] Closing the Sender for the entity '%s'.",
this._context.namespace.connectionId,
this._context.entityPath
);
const senderLink = this._sender;
this._deleteFromCache();
await this._closeLink(senderLink);
}
}
/**
* Determines whether the AMQP sender link is open. If open then returns true else returns false.
* @return {boolean} boolean
*/
isOpen(): boolean {
const result: boolean = this._sender! && this._sender!.isOpen();
log.error(
"[%s] Sender '%s' with address '%s' is open? -> %s",
this._context.namespace.connectionId,
this.name,
this.address,
result
);
return result;
}
/**
* Sends the given message, with the given options on this link
*
* @param {SendableMessageInfo} data Message to send. Will be sent as UTF8-encoded JSON string.
* @returns {Promise<void>}
*/
async send(data: SendableMessageInfo): Promise<void> {
throwErrorIfConnectionClosed(this._context.namespace);
try {
if (!this.isOpen()) {
log.sender(
"Acquiring lock %s for initializing the session, sender and " +
"possibly the connection.",
this.senderLock
);
await defaultLock.acquire(this.senderLock, () => {
return this._init();
});
}
const amqpMessage = toAmqpMessage(data);
amqpMessage.body = this._context.namespace.dataTransformer.encode(data.body);
let encodedMessage;
try {
encodedMessage = RheaMessageUtil.encode(amqpMessage);
} catch (error) {
if (error instanceof TypeError || error.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 = getMessagePropertyTypeMismatchError(data) || error;
}
throw error;
}
log.sender(
"[%s] Sender '%s', trying to send message: %O",
this._context.namespace.connectionId,
this.name,
data
);
return await this._trySend(encodedMessage);
} catch (err) {
log.error(
"[%s] Sender '%s': An error occurred while sending the message: %O\nError: %O",
this._context.namespace.connectionId,
this.name,
data,
err
);
throw err;
}
}
/**
* Send a batch of Message to the ServiceBus in a single AMQP message. The "message_annotations",
* "application_properties" and "properties" of the first message will be set as that
* of the envelope (batch message).
* @param {Array<Message>} inputMessages An array of Message objects to be sent in a
* Batch message.
* @return {Promise<void>}
*/
async sendBatch(inputMessages: SendableMessageInfo[]): Promise<void> {
throwErrorIfConnectionClosed(this._context.namespace);
try {
if (!Array.isArray(inputMessages)) {
inputMessages = [inputMessages];
}
if (!this.isOpen()) {
log.sender(
"Acquiring lock %s for initializing the session, sender and " +
"possibly the connection.",
this.senderLock
);
await defaultLock.acquire(this.senderLock, () => {
return this._init();
});
}
log.sender(
"[%s] Sender '%s', trying to send Message[]: %O",
this._context.namespace.connectionId,
this.name,
inputMessages
);
const amqpMessages: AmqpMessage[] = [];
const encodedMessages = [];
// Convert Message to AmqpMessage.
for (let i = 0; i < inputMessages.length; i++) {
const amqpMessage = toAmqpMessage(inputMessages[i]);
amqpMessage.body = this._context.namespace.dataTransformer.encode(inputMessages[i].body);
amqpMessages[i] = amqpMessage;
try {
encodedMessages[i] = RheaMessageUtil.encode(amqpMessage);
} catch (error) {
if (error instanceof TypeError || error.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 = getMessagePropertyTypeMismatchError(inputMessages[i]) || error;
}
throw error;
}
}
// Convert every encoded message to amqp data section
const batchMessage: AmqpMessage = {
body: RheaMessageUtil.data_sections(encodedMessages)
};
// Set message_annotations, application_properties and properties of the first message as
// that of the envelope (batch message).
if (amqpMessages[0].message_annotations) {
batchMessage.message_annotations = amqpMessages[0].message_annotations;
}
if (amqpMessages[0].application_properties) {
batchMessage.application_properties = amqpMessages[0].application_properties;
}
for (const prop of messageProperties) {
if ((amqpMessages[0] as any)[prop]) {
(batchMessage as any)[prop] = (amqpMessages[0] as any)[prop];
}
}
// Finally encode the envelope (batch message).
const encodedBatchMessage = RheaMessageUtil.encode(batchMessage);
log.sender(
"[%s]Sender '%s', sending encoded batch message.",
this._context.namespace.connectionId,
this.name,
encodedBatchMessage
);
return await this._trySend(encodedBatchMessage, true);
} catch (err) {
log.error(
"[%s] Sender '%s': An error occurred while sending the messages: %O\nError: %O",
this._context.namespace.connectionId,
this.name,
inputMessages,
err
);
throw err;
}
}
/**
* Creates a new sender to the specifiec ServiceBus entity, and optionally to a given
* partition if it is not present in the context or returns the one present in the context.
* @static
* @returns {Promise<MessageSender>}
*/
static create(context: ClientEntityContext): MessageSender {
throwErrorIfConnectionClosed(context.namespace);
if (!context.sender) {
context.sender = new MessageSender(context);
}
return context.sender;
}
}