-
Notifications
You must be signed in to change notification settings - Fork 339
/
consumer.ts
642 lines (586 loc) · 18.6 KB
/
consumer.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
import {
SQSClient,
Message,
ChangeMessageVisibilityCommand,
ChangeMessageVisibilityCommandInput,
ChangeMessageVisibilityCommandOutput,
ChangeMessageVisibilityBatchCommand,
ChangeMessageVisibilityBatchCommandInput,
ChangeMessageVisibilityBatchCommandOutput,
DeleteMessageCommand,
DeleteMessageCommandInput,
DeleteMessageBatchCommand,
DeleteMessageBatchCommandInput,
ReceiveMessageCommand,
ReceiveMessageCommandInput,
ReceiveMessageCommandOutput,
QueueAttributeName,
MessageSystemAttributeName,
} from "@aws-sdk/client-sqs";
import { ConsumerOptions, StopOptions, UpdatableOptions } from "./types.js";
import { TypedEventEmitter } from "./emitter.js";
import {
SQSError,
TimeoutError,
toStandardError,
toTimeoutError,
toSQSError,
isConnectionError,
} from "./errors.js";
import { validateOption, assertOptions, hasMessages } from "./validation.js";
import { logger } from "./logger.js";
/**
* [Usage](https://bbc.github.io/sqs-consumer/index.html#usage)
*/
export class Consumer extends TypedEventEmitter {
private pollingTimeoutId: NodeJS.Timeout | undefined = undefined;
private stopped = true;
private queueUrl: string;
private handleMessage: (message: Message) => Promise<Message | void>;
private handleMessageBatch: (message: Message[]) => Promise<Message[] | void>;
private preReceiveMessageCallback?: () => Promise<void>;
private postReceiveMessageCallback?: () => Promise<void>;
private sqs: SQSClient;
private handleMessageTimeout: number;
private attributeNames: QueueAttributeName[];
private messageAttributeNames: string[];
private messageSystemAttributeNames: MessageSystemAttributeName[];
private shouldDeleteMessages: boolean;
private alwaysAcknowledge: boolean;
private batchSize: number;
private visibilityTimeout: number;
private terminateVisibilityTimeout: boolean | number;
private waitTimeSeconds: number;
private authenticationErrorTimeout: number;
private pollingWaitTimeMs: number;
private pollingCompleteWaitTimeMs: number;
private heartbeatInterval: number;
private isPolling = false;
private stopRequestedAtTimestamp: number;
public abortController: AbortController;
private extendedAWSErrors: boolean;
constructor(options: ConsumerOptions) {
super();
assertOptions(options);
this.queueUrl = options.queueUrl;
this.handleMessage = options.handleMessage;
this.handleMessageBatch = options.handleMessageBatch;
this.preReceiveMessageCallback = options.preReceiveMessageCallback;
this.postReceiveMessageCallback = options.postReceiveMessageCallback;
this.handleMessageTimeout = options.handleMessageTimeout;
this.attributeNames = options.attributeNames || [];
this.messageAttributeNames = options.messageAttributeNames || [];
this.messageSystemAttributeNames =
options.messageSystemAttributeNames || [];
this.batchSize = options.batchSize || 1;
this.visibilityTimeout = options.visibilityTimeout;
this.terminateVisibilityTimeout =
options.terminateVisibilityTimeout || false;
this.heartbeatInterval = options.heartbeatInterval;
this.waitTimeSeconds = options.waitTimeSeconds ?? 20;
this.authenticationErrorTimeout =
options.authenticationErrorTimeout ?? 10000;
this.pollingWaitTimeMs = options.pollingWaitTimeMs ?? 0;
this.pollingCompleteWaitTimeMs = options.pollingCompleteWaitTimeMs ?? 0;
this.shouldDeleteMessages = options.shouldDeleteMessages ?? true;
this.alwaysAcknowledge = options.alwaysAcknowledge ?? false;
this.extendedAWSErrors = options.extendedAWSErrors ?? false;
this.sqs =
options.sqs ||
new SQSClient({
useQueueUrlAsEndpoint: options.useQueueUrlAsEndpoint ?? true,
region: options.region || process.env.AWS_REGION || "eu-west-1",
});
}
/**
* Creates a new SQS consumer.
*/
public static create(options: ConsumerOptions): Consumer {
return new Consumer(options);
}
/**
* Start polling the queue for messages.
*/
public start(): void {
if (this.stopped) {
// Create a new abort controller each time the consumer is started
this.abortController = new AbortController();
logger.debug("starting");
this.stopped = false;
this.emit("started");
this.poll();
}
}
/**
* A reusable options object for sqs.send that's used to avoid duplication.
*/
private get sqsSendOptions(): { abortSignal: AbortSignal } {
return {
// return the current abortController signal or a fresh signal that has not been aborted.
// This effectively defaults the signal sent to the AWS SDK to not aborted
abortSignal: this.abortController?.signal || new AbortController().signal,
};
}
/**
* Stop polling the queue for messages (pre existing requests will still be made until concluded).
*/
public stop(options?: StopOptions): void {
if (this.stopped) {
logger.debug("already_stopped");
return;
}
logger.debug("stopping");
this.stopped = true;
if (this.pollingTimeoutId) {
clearTimeout(this.pollingTimeoutId);
this.pollingTimeoutId = undefined;
}
if (options?.abort) {
logger.debug("aborting");
this.abortController.abort();
this.emit("aborted");
}
this.stopRequestedAtTimestamp = Date.now();
this.waitForPollingToComplete();
}
/**
* Wait for final poll and in flight messages to complete.
* @private
*/
private waitForPollingToComplete(): void {
if (!this.isPolling || !(this.pollingCompleteWaitTimeMs > 0)) {
this.emit("stopped");
return;
}
const exceededTimeout: boolean =
Date.now() - this.stopRequestedAtTimestamp >
this.pollingCompleteWaitTimeMs;
if (exceededTimeout) {
this.emit("waiting_for_polling_to_complete_timeout_exceeded");
this.emit("stopped");
return;
}
this.emit("waiting_for_polling_to_complete");
setTimeout(() => this.waitForPollingToComplete(), 1000);
}
/**
* Returns the current status of the consumer.
* This includes whether it is running or currently polling.
*/
public get status(): {
isRunning: boolean;
isPolling: boolean;
} {
return {
isRunning: !this.stopped,
isPolling: this.isPolling,
};
}
/**
* Validates and then updates the provided option to the provided value.
* @param option The option to validate and then update
* @param value The value to set the provided option to
*/
public updateOption(
option: UpdatableOptions,
value: ConsumerOptions[UpdatableOptions],
): void {
validateOption(option, value, this, true);
this[option] = value;
this.emit("option_updated", option, value);
}
/**
* Emit one of the consumer's error events depending on the error received.
* @param err The error object to forward on
* @param message The message that the error occurred on
*/
private emitError(err: Error, message?: Message): void {
if (!message) {
this.emit("error", err);
} else if (err.name === SQSError.name) {
this.emit("error", err, message);
} else if (err instanceof TimeoutError) {
this.emit("timeout_error", err, message);
} else {
this.emit("processing_error", err, message);
}
}
/**
* Poll for new messages from SQS
*/
private poll(): void {
if (this.stopped) {
logger.debug("cancelling_poll", {
detail:
"Poll was called while consumer was stopped, cancelling poll...",
});
return;
}
logger.debug("polling");
this.isPolling = true;
let currentPollingTimeout: number = this.pollingWaitTimeMs;
this.receiveMessage({
QueueUrl: this.queueUrl,
AttributeNames: this.attributeNames,
MessageAttributeNames: this.messageAttributeNames,
MessageSystemAttributeNames: this.messageSystemAttributeNames,
MaxNumberOfMessages: this.batchSize,
WaitTimeSeconds: this.waitTimeSeconds,
VisibilityTimeout: this.visibilityTimeout,
})
.then((output: ReceiveMessageCommandOutput) =>
this.handleSqsResponse(output),
)
.catch((err): void => {
this.emitError(err);
if (isConnectionError(err)) {
logger.debug("authentication_error", {
code: err.code || "Unknown",
detail:
"There was an authentication error. Pausing before retrying.",
});
currentPollingTimeout = this.authenticationErrorTimeout;
}
return;
})
.then((): void => {
if (this.pollingTimeoutId) {
clearTimeout(this.pollingTimeoutId);
}
this.pollingTimeoutId = setTimeout(
() => this.poll(),
currentPollingTimeout,
);
})
.catch((err): void => {
this.emitError(err);
})
.finally((): void => {
this.isPolling = false;
});
}
/**
* Send a request to SQS to retrieve messages
* @param params The required params to receive messages from SQS
*/
private async receiveMessage(
params: ReceiveMessageCommandInput,
): Promise<ReceiveMessageCommandOutput> {
try {
if (this.preReceiveMessageCallback) {
await this.preReceiveMessageCallback();
}
const result: ReceiveMessageCommandOutput = await this.sqs.send(
new ReceiveMessageCommand(params),
this.sqsSendOptions,
);
if (this.postReceiveMessageCallback) {
await this.postReceiveMessageCallback();
}
return result;
} catch (err) {
throw toSQSError(
err,
`SQS receive message failed: ${err.message}`,
this.extendedAWSErrors,
);
}
}
/**
* Handles the response from AWS SQS, determining if we should proceed to
* the message handler.
* @param response The output from AWS SQS
*/
private async handleSqsResponse(
response: ReceiveMessageCommandOutput,
): Promise<void> {
if (hasMessages(response)) {
if (this.handleMessageBatch) {
await this.processMessageBatch(response.Messages);
} else {
await Promise.all(
response.Messages.map((message: Message) =>
this.processMessage(message),
),
);
}
this.emit("response_processed");
} else if (response) {
this.emit("empty");
}
}
/**
* Process a message that has been received from SQS. This will execute the message
* handler and delete the message once complete.
* @param message The message that was delivered from SQS
*/
private async processMessage(message: Message): Promise<void> {
let heartbeatTimeoutId: NodeJS.Timeout | undefined = undefined;
try {
this.emit("message_received", message);
if (this.heartbeatInterval) {
heartbeatTimeoutId = this.startHeartbeat(message);
}
const ackedMessage: Message = await this.executeHandler(message);
if (ackedMessage?.MessageId === message.MessageId) {
await this.deleteMessage(message);
this.emit("message_processed", message);
}
} catch (err) {
this.emitError(err, message);
if (this.terminateVisibilityTimeout !== false) {
const timeout =
this.terminateVisibilityTimeout === true
? 0
: this.terminateVisibilityTimeout;
await this.changeVisibilityTimeout(message, timeout);
}
} finally {
if (this.heartbeatInterval) {
clearInterval(heartbeatTimeoutId);
}
}
}
/**
* Process a batch of messages from the SQS queue.
* @param messages The messages that were delivered from SQS
*/
private async processMessageBatch(messages: Message[]): Promise<void> {
let heartbeatTimeoutId: NodeJS.Timeout | undefined = undefined;
try {
messages.forEach((message: Message): void => {
this.emit("message_received", message);
});
if (this.heartbeatInterval) {
heartbeatTimeoutId = this.startHeartbeat(null, messages);
}
const ackedMessages: Message[] = await this.executeBatchHandler(messages);
if (ackedMessages?.length > 0) {
await this.deleteMessageBatch(ackedMessages);
ackedMessages.forEach((message: Message): void => {
this.emit("message_processed", message);
});
}
} catch (err) {
this.emit("error", err, messages);
if (this.terminateVisibilityTimeout !== false) {
const timeout =
this.terminateVisibilityTimeout === true
? 0
: this.terminateVisibilityTimeout;
await this.changeVisibilityTimeoutBatch(messages, timeout);
}
} finally {
clearInterval(heartbeatTimeoutId);
}
}
/**
* Trigger a function on a set interval
* @param heartbeatFn The function that should be triggered
*/
private startHeartbeat(
message?: Message,
messages?: Message[],
): NodeJS.Timeout {
return setInterval(() => {
if (this.handleMessageBatch) {
return this.changeVisibilityTimeoutBatch(
messages,
this.visibilityTimeout,
);
} else {
return this.changeVisibilityTimeout(message, this.visibilityTimeout);
}
}, this.heartbeatInterval * 1000);
}
/**
* Change the visibility timeout on a message
* @param message The message to change the value of
* @param timeout The new timeout that should be set
*/
private async changeVisibilityTimeout(
message: Message,
timeout: number,
): Promise<ChangeMessageVisibilityCommandOutput> {
try {
const input: ChangeMessageVisibilityCommandInput = {
QueueUrl: this.queueUrl,
ReceiptHandle: message.ReceiptHandle,
VisibilityTimeout: timeout,
};
return await this.sqs.send(
new ChangeMessageVisibilityCommand(input),
this.sqsSendOptions,
);
} catch (err) {
this.emit(
"error",
toSQSError(
err,
`Error changing visibility timeout: ${err.message}`,
this.extendedAWSErrors,
),
message,
);
}
}
/**
* Change the visibility timeout on a batch of messages
* @param messages The messages to change the value of
* @param timeout The new timeout that should be set
*/
private async changeVisibilityTimeoutBatch(
messages: Message[],
timeout: number,
): Promise<ChangeMessageVisibilityBatchCommandOutput> {
const params: ChangeMessageVisibilityBatchCommandInput = {
QueueUrl: this.queueUrl,
Entries: messages.map((message: Message) => ({
Id: message.MessageId,
ReceiptHandle: message.ReceiptHandle,
VisibilityTimeout: timeout,
})),
};
try {
return await this.sqs.send(
new ChangeMessageVisibilityBatchCommand(params),
this.sqsSendOptions,
);
} catch (err) {
this.emit(
"error",
toSQSError(
err,
`Error changing visibility timeout: ${err.message}`,
this.extendedAWSErrors,
),
messages,
);
}
}
/**
* Trigger the applications handleMessage function
* @param message The message that was received from SQS
*/
private async executeHandler(message: Message): Promise<Message> {
let handleMessageTimeoutId: NodeJS.Timeout | undefined = undefined;
try {
let result;
if (this.handleMessageTimeout) {
const pending: Promise<void> = new Promise((_, reject): void => {
handleMessageTimeoutId = setTimeout((): void => {
reject(new TimeoutError());
}, this.handleMessageTimeout);
});
result = await Promise.race([this.handleMessage(message), pending]);
} else {
result = await this.handleMessage(message);
}
return !this.alwaysAcknowledge && result instanceof Object
? result
: message;
} catch (err) {
if (err instanceof TimeoutError) {
throw toTimeoutError(
err,
`Message handler timed out after ${this.handleMessageTimeout}ms: Operation timed out.`,
);
} else if (err instanceof Error) {
throw toStandardError(
err,
`Unexpected message handler failure: ${err.message}`,
);
}
throw err;
} finally {
if (handleMessageTimeoutId) {
clearTimeout(handleMessageTimeoutId);
}
}
}
/**
* Execute the application's message batch handler
* @param messages The messages that should be forwarded from the SQS queue
*/
private async executeBatchHandler(messages: Message[]): Promise<Message[]> {
try {
const result: void | Message[] = await this.handleMessageBatch(messages);
return !this.alwaysAcknowledge && result instanceof Object
? result
: messages;
} catch (err) {
if (err instanceof Error) {
throw toStandardError(
err,
`Unexpected message handler failure: ${err.message}`,
);
}
throw err;
}
}
/**
* Delete a single message from SQS
* @param message The message to delete from the SQS queue
*/
private async deleteMessage(message: Message): Promise<void> {
if (!this.shouldDeleteMessages) {
logger.debug("skipping_delete", {
detail:
"Skipping message delete since shouldDeleteMessages is set to false",
});
return;
}
logger.debug("deleting_message", { messageId: message.MessageId });
const deleteParams: DeleteMessageCommandInput = {
QueueUrl: this.queueUrl,
ReceiptHandle: message.ReceiptHandle,
};
try {
await this.sqs.send(
new DeleteMessageCommand(deleteParams),
this.sqsSendOptions,
);
} catch (err) {
throw toSQSError(
err,
`SQS delete message failed: ${err.message}`,
this.extendedAWSErrors,
);
}
}
/**
* Delete a batch of messages from the SQS queue.
* @param messages The messages that should be deleted from SQS
*/
private async deleteMessageBatch(messages: Message[]): Promise<void> {
if (!this.shouldDeleteMessages) {
logger.debug("skipping_delete", {
detail:
"Skipping message delete since shouldDeleteMessages is set to false",
});
return;
}
logger.debug("deleting_messages", {
messageIds: messages.map((msg: Message) => msg.MessageId),
});
const deleteParams: DeleteMessageBatchCommandInput = {
QueueUrl: this.queueUrl,
Entries: messages.map((message: Message) => ({
Id: message.MessageId,
ReceiptHandle: message.ReceiptHandle,
})),
};
try {
await this.sqs.send(
new DeleteMessageBatchCommand(deleteParams),
this.sqsSendOptions,
);
} catch (err) {
throw toSQSError(
err,
`SQS delete message failed: ${err.message}`,
this.extendedAWSErrors,
);
}
}
}