-
Notifications
You must be signed in to change notification settings - Fork 2
/
lib.js
60 lines (50 loc) · 1.58 KB
/
lib.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
'use strict';
const Promise = require('bluebird');
const co = require('co');
const uuid = require('node-uuid');
const AWS = require('aws-sdk');
const Lambda = new AWS.Lambda();
const DynamoDB = Promise.promisifyAll(new AWS.DynamoDB.DocumentClient());
const table = 'sqs-tokens-dev';
let takeAwayToken = co.wrap(function* (queueUrl) {
let token = uuid.v4();
let queryParams = {
TableName: table,
KeyConditionExpression: 'queue = :queueUrl',
ExpressionAttributeValues: {
':queueUrl': queueUrl
}
};
let res = yield DynamoDB.queryAsync(queryParams);
if (res.Items && res.Items.length > 1) {
let item = res.Items[0];
console.log(`scaling down SQS processor : ${queueUrl} [${item.token}]`);
let delParams = {
TableName: table,
Key: {
queue: queueUrl,
token: item.token
}
};
yield DynamoDB.deleteAsync(delParams);
} else {
console.log(`there needs to be at least 1 processor for SQS : ${queueUrl}`);
console.log('ignoring scale-down request');
}
});
module.exports = co.wrap(function* (event) {
console.log(JSON.stringify(event));
let snsMsg = JSON.parse(event.Records[0].Sns.Message);
if (snsMsg.OldStateValue !== 'ALARM') {
console.log('not transitioned from an ALARM state, ignored');
return;
}
let accountId = snsMsg.AWSAccountId;
let queueName = snsMsg
.Trigger
.Dimensions
.find(dim => dim.name === 'QueueName')
.value;
let queueUrl = `https://sqs.${AWS.config.region}.amazonaws.com/${accountId}/${queueName}`;
yield takeAwayToken(queueUrl);
});