-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
211 lines (188 loc) · 5.15 KB
/
index.js
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
// @ts-check
'use strict';
const {
SQSClient,
DeleteMessageCommand,
ReceiveMessageCommand,
ChangeMessageVisibilityCommand
} = require('@aws-sdk/client-sqs');
const EventEmitter = require('events');
class SQSConsumer extends EventEmitter {
/**
* @param {SQSConsumerConfig} config
*/
constructor({
queueUrl,
aws = {},
messageAttributeNames = [],
batchSize = 1,
waitTimeSeconds = 0,
handleMessage
}) {
super();
this.queueUrl = queueUrl;
this.messageAttributeNames = messageAttributeNames;
this.waitTimeSeconds = waitTimeSeconds;
this.handleMessage = handleMessage;
this.batchSize = batchSize;
this.client = new SQSClient(aws);
this.numActiveMessages = 0; // how many message are we currently processing
/** @type {Promise<ReceiveMessageCommandOutput> | boolean} */
this.activeRequest = false;
this.active = false;
/** @type {NodeJS.Timeout | undefined} */
this.intervalId = undefined;
}
/**
* @param {string} receiptHandle
* @return {Promise<DeleteMessageCommandOutput>}
*/
deleteMessage(receiptHandle) {
const cmd = new DeleteMessageCommand({
QueueUrl: this.queueUrl,
ReceiptHandle: receiptHandle
});
return this.client.send(cmd);
}
async poll() {
const params = {
QueueUrl: this.queueUrl,
AttributeNames: ['All'],
MessageAttributeNames: this.messageAttributeNames,
MaxNumberOfMessages: this.getMaxNumberOfMessages(),
WaitTimeSeconds: this.waitTimeSeconds,
abortSignal: new AbortController().signal
};
/** @type {NodeJS.Timeout | undefined} */
let timeout;
try {
this.activeAbortController = new AbortController();
this.activeRequest = this.client.send(new ReceiveMessageCommand(params), {abortSignal: this.activeAbortController.signal});
timeout = setTimeout(this.abort.bind(this), (this.waitTimeSeconds + 5) * 1000);
const res = await this.activeRequest;
clearTimeout(timeout);
this.activeRequest = false;
const numMessages = res.Messages ? res.Messages.length : 0;
this.emit('didPoll');
if (numMessages) {
res.Messages?.forEach((msg) => {
this.numActiveMessages++;
this.handleMessage(msg, this.createCallback(msg)).catch((err) => {
this.emit('error', err);
});
});
}
this.shouldWePoll();
} catch (err) {
this.activeRequest = false;
throw err;
} finally {
if (timeout) {
clearTimeout(timeout);
}
}
}
getMaxNumberOfMessages() {
let max = this.batchSize - this.numActiveMessages;
if (max > 10) {
max = 10;
} else if (max < 1) {
max = 1;
}
return max;
}
async shouldWePoll() {
if (this.active && !this.activeRequest && this.numActiveMessages < this.batchSize) {
try {
await this.poll();
} catch (err) {
this.emit('error', err);
}
}
}
/**
* @param {string} receiptHandle
* @return {Promise<ChangeMessageVisibilityCommandOutput>}
*/
returnMessageToQueue(receiptHandle) {
const cmd = new ChangeMessageVisibilityCommand({
QueueUrl: this.queueUrl,
ReceiptHandle: receiptHandle,
VisibilityTimeout: 0
});
return this.client.send(cmd);
}
/**
* @param {Message} msg
* @return {MessageCallback}
*/
createCallback(msg) {
return async (err) => {
this.numActiveMessages--;
this.shouldWePoll();
if (msg.ReceiptHandle) {
if (err) {
try {
await this.returnMessageToQueue(msg.ReceiptHandle);
} catch (err) {
this.emit('error', err);
}
return;
}
try {
await this.deleteMessage(msg.ReceiptHandle);
} catch (err) {
this.emit('error', err);
}
}
};
}
async start() {
this.active = true;
// do first poll and wait for it to be able to throw on start
await this.poll();
this.intervalId = setInterval(() => this.shouldWePoll(), 1000); // keep things alive;
}
abort() {
if (this.activeRequest) {
this.activeAbortController?.abort();
this.activeRequest = false;
this.activeAbortController = undefined;
}
}
async stop(gracefulTimeout = 0) {
this.active = false;
this.abort();
if (this.intervalId) {
clearInterval(this.intervalId);
}
if (!gracefulTimeout || isNaN(Number(gracefulTimeout))) {
return;
}
const start = Date.now();
while (Date.now() > start - Number(gracefulTimeout)) {
if (this.numActiveMessages <= 0) {
break;
}
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
}
module.exports = SQSConsumer;
/**
* @typedef {object} SQSConsumerConfig
* @property {string} queueUrl
* @property {import('@aws-sdk/client-sqs').SQSClientConfig} [aws]
* @property {string[]} [messageAttributeNames]
* @property {number} [batchSize]
* @property {number} [waitTimeSeconds]
* @property {SQSConsumerMessageHandler} handleMessage
*
* @typedef {(msg: Message, cb: MessageCallback) => Promise<any>} SQSConsumerMessageHandler
* @typedef {(error?: Error) => Promise<void>} MessageCallback
*
* @typedef {import('@aws-sdk/client-sqs').Message} Message
* @typedef {import('@aws-sdk/client-sqs').ReceiveMessageCommandOutput} ReceiveMessageCommandOutput
* @typedef {import('@aws-sdk/client-sqs').DeleteMessageCommandOutput} DeleteMessageCommandOutput
* @typedef {import('@aws-sdk/client-sqs').ChangeMessageVisibilityCommandOutput} ChangeMessageVisibilityCommandOutput
*/