-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsqs-to-lambda.js
77 lines (66 loc) · 1.82 KB
/
sqs-to-lambda.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
/* Two global variables should already be injected by the CloudFormation template:
*
* CONFIG (String) The comma-separated list of queue url/lambda function pairs.
* ONCE (Bool) True if the function should exit after polling each queue a single
* time. If False, the function will keep polling until it nears timeout.
*/
var AWS = require('aws-sdk');
var sqs = new AWS.SQS();
var lambda = new AWS.Lambda();
var config = CONFIG;
var once = ONCE;
function pollQueue(queueUrl, functionName, remaining, done) {
if (remaining() < 5000) {
return done();
}
if (queueUrl == "" || functionName == "") {
return done();
}
sqs.receiveMessage({
QueueUrl: queueUrl,
MaxNumberOfMessages: 1,
WaitTimeSeconds: 1
}, function(err, data) {
if (err) {
console.log(err);
return done();
}
if (!data.Messages || data.Messages.length === 0) {
if (once) {
return done();
}
return pollQueue(queueUrl, functionName, remaining, done);
}
lambda.invoke({
FunctionName: functionName,
InvocationType: "Event",
Payload: JSON.stringify({
source: "aws.sqs",
QueueUrl: queueUrl,
Message: data.Messages[0]
})
}, function(err) {
if (err) {
console.log(err);
return done();
}
return pollQueue(queueUrl, functionName, remaining, done);
});
});
}
exports.handler = function(event, context) {
if (config.length === 0) {
return context.done();
}
var remainingWorkers = config.length / 2;
var done = function() {
remainingWorkers = remainingWorkers - 1;
if (remainingWorkers == 0) {
console.log('exiting');
context.done();
}
}
for (var i = 0; i < config.length; i += 2) {
pollQueue(config[i], config[i+1], context.getRemainingTimeInMillis, done);
}
}