forked from bbc/sqs-consumer
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
303 lines (259 loc) · 8.7 KB
/
Copy pathindex.js
File metadata and controls
303 lines (259 loc) · 8.7 KB
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
'use strict';
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var AWS = require('aws-sdk');
var debug = require('debug')('sqs-consumer');
var requiredOptions = [
'queueUrl',
'handleMessage'
];
const VISIBILITY_TIMEOUT_FACTOR = 0.75;
const MAX_DURATION_OF_MESSAGE = 11 * 60 * 60 * 1000; // 11 hours
/**
* Construct a new SQSError
*/
function SQSError(message) {
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = (message || '');
}
util.inherits(SQSError, Error);
function validate(options) {
requiredOptions.forEach(function (option) {
if (!options[option]) {
throw new Error('Missing SQS consumer option [' + option + '].');
}
});
if (options.batchSize > 10 || options.batchSize < 1) {
throw new Error('SQS batchSize option must be between 1 and 10.');
}
}
function isAuthenticationError(err) {
return (err.statusCode === 403 || err.code === 'CredentialsError');
}
/**
* An SQS consumer.
* @param {object} options
* @param {string|array} options.queueUrl
* @param {string} options.region
* @param {function} options.handleMessage
* @param {array} options.attributeNames
* @param {array} options.messageAttributeNames
* @param {number} options.batchSize
* @param {object} options.sqs
* @param {number} options.visibilityTimeout
* @param {number|array} options.waitTimeSeconds
* @param {array} options.sticky
*/
function Consumer(options) {
validate(options);
this.currentQueueIndex = 0;
this.numberActive = 0;
this.maxNumberActive = options.batchSize || 1;
this.queueUrls = [].concat(options.queueUrl);
this.handleMessage = options.handleMessage;
this.attributeNames = options.attributeNames || [];
this.messageAttributeNames = options.messageAttributeNames || [];
this.stopped = true;
this.maxDurationOfMessage = options.maxDurationOfMessage || MAX_DURATION_OF_MESSAGE;
this.visibilityTimeout = options.visibilityTimeout || 30;
this.initialVisibilityTimeout = options.initialVisibilityTimeout || this.visibilityTimeout;
this.terminateVisibilityTimeout = options.terminateVisibilityTimeout || false;
this.waitTimeSeconds = options.waitTimeSeconds || 20;
if (!Array.isArray(this.waitTimeSeconds)) {
this.waitTimeSeconds = this.queueUrls.map(() => this.waitTimeSeconds);
}
this.sticky = options.sticky || this.queueUrls.map(() => 0);
this.lastReceiveTime = this.queueUrls.map(() => 0);
this.authenticationErrorTimeout = options.authenticationErrorTimeout || 10000;
this.sqs = options.sqs || new AWS.SQS({
region: options.region || process.env.AWS_REGION || 'eu-west-1'
});
}
util.inherits(Consumer, EventEmitter);
/**
* Construct a new Consumer
*/
Consumer.create = function (options) {
return new Consumer(options);
};
/**
* Start polling for messages.
*/
Consumer.prototype.start = function () {
if (this.stopped) {
debug('Starting consumer');
this.stopped = false;
this._poll();
}
};
/**
* Stop polling for messages.
*/
Consumer.prototype.stop = function () {
debug('Stopping consumer');
if (!this.stopped) {
this.emit('stopped');
this.stopped = true;
}
};
Consumer.prototype._poll = function () {
if (this.stopped) {
return;
}
if (this.numberActive < this.maxNumberActive) {
clearTimeout(this._pollDebounce);
this._pollDebounce = setTimeout(() => {
let index = 0;
// if we get messages and the queue is "sticky",
// make sure we process that queue again next
let stickyValue = this.sticky[this.currentQueueIndex];
let lastReceiveTime = this.lastReceiveTime[this.currentQueueIndex];
if (stickyValue && (stickyValue === true || (new Date().getTime() - lastReceiveTime) < stickyValue)) {
index = this.currentQueueIndex;
}
else {
this.lastReceiveTime[this.currentQueueIndex] = 0;
this.currentQueueIndex++;
if (this.currentQueueIndex >= this.queueUrls.length) {
this.currentQueueIndex = 0;
}
index = this.currentQueueIndex;
}
let url = this.queueUrls[index];
this._pollQueue(url, index, lastReceiveTime > 0 ? 1 : undefined);
}, 0);
}
};
Consumer.prototype._pollQueue = function(queueUrl, index, waitTimeOverride) {
if (this.stopped) {
return;
}
var waitTime = this.waitTimeSeconds[index];
var receiveParams = {
QueueUrl: queueUrl,
AttributeNames: this.attributeNames,
MessageAttributeNames: this.messageAttributeNames,
MaxNumberOfMessages: this.maxNumberActive - this.numberActive,
WaitTimeSeconds: waitTimeOverride || waitTime,
VisibilityTimeout: this.initialVisibilityTimeout
};
this.sqs.receiveMessage(receiveParams, (err, response) => {
if (err) {
this.emit('error', new SQSError('SQS receive message failed: ' + err.message));
}
debug('Received SQS response');
debug(response);
if (response && response.Messages && response.Messages.length > 0) {
// mark the first time we receive a message in this cycle through the queues
if (this.lastReceiveTime[index] === 0) {
this.lastReceiveTime[index] = new Date().getTime();
}
response.Messages.forEach(message => this._processMessage(message, queueUrl));
}
else if (response && !response.Messages) {
this.emit('empty');
this.lastReceiveTime[index] = 0;
this._poll();
}
else if (err && isAuthenticationError(err)) {
// there was an authentication error, so wait a bit before repolling
this.lastReceiveTime[index] = 0;
debug('There was an authentication error. Pausing before retrying.');
setTimeout(this._poll.bind(this), this.authenticationErrorTimeout);
}
else {
// there were no messages, so start polling again
this.lastReceiveTime[index] = 0;
this._poll();
}
});
};
Consumer.prototype._processMessage = function (message, queueUrl) {
// make sure we aren't over-extending ourselves
if (this.stopped || this.numberActive >= this.maxNumberActive) {
this._cancelProcessingMessage(message, queueUrl);
return;
}
// mark us as having worked on this message ---
// it is VERY important that all paths out of this processing will
// decrement the counter
this.numberActive++;
this.emit('message_received', message);
let startTime = new Date().getTime(),
hasDecremented = false,
keepAliveTimeout = null,
keepAlive = () => {
// if the message takes a REALLY long time to process,
// at some point SQS stops being able to extend the visibility timeout...
// so we have to just delete the message and hope it finishes.
// this is not ideal for the super long term, but it better than the message
// becoming visible again and being processed again.
if (this.maxDurationOfMessage < new Date().getTime() - startTime) {
this._deleteMessage(message, queueUrl);
return;
}
this.sqs.changeMessageVisibility({
QueueUrl: queueUrl,
ReceiptHandle: message.ReceiptHandle,
VisibilityTimeout: this.visibilityTimeout
}, err => {
if (hasDecremented) return;
debug(err, message);
});
keepAliveTimeout = setTimeout(keepAlive, this.visibilityTimeout * VISIBILITY_TIMEOUT_FACTOR * 1000);
};
let done = err => {
if (!hasDecremented) {
this.numberActive--;
hasDecremented = true;
}
clearTimeout(keepAliveTimeout);
if (err) {
if (err.name === SQSError.name) {
this.emit('error', err, message);
} else {
this.emit('processing_error', err, message);
}
if (this.terminateVisibilityTimeout) {
this._cancelProcessingMessage(message, queueUrl);
}
else {
this._poll();
}
}
else {
this._deleteMessage(message, queueUrl);
this.emit('message_processed', message);
}
};
keepAlive();
try {
this.handleMessage(message, done, queueUrl);
}
catch (err) {
done(new Error('Unexpected message handler failure: ' + err.message));
}
};
Consumer.prototype._deleteMessage = function (message, queueUrl) {
var deleteParams = {
QueueUrl: queueUrl,
ReceiptHandle: message.ReceiptHandle
};
debug('Deleting message %s', message.MessageId);
this.sqs.deleteMessage(deleteParams, err => {
if (err) this.emit('error', new SQSError('SQS delete message failed: ' + err.message));
this._poll();
});
};
Consumer.prototype._cancelProcessingMessage = function (message, queueUrl) {
this.sqs.changeMessageVisibility({
QueueUrl: queueUrl,
ReceiptHandle: message.ReceiptHandle,
VisibilityTimeout: 0
}, err => {
if (err) this.emit('error', err, message);
this._poll();
});
};
module.exports = Consumer;