-
Notifications
You must be signed in to change notification settings - Fork 8
/
cache.js
72 lines (59 loc) · 1.81 KB
/
cache.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
const BotGenesis = 1569394800; // First ever bot tweet 25 Sep 2019
const AWS = require('aws-sdk');
require('dotenv').config();
const s3 = new AWS.S3();
const cloudfront = new AWS.CloudFront();
async function cache(toot, beebState){
// Were assuming single thread sequential URL generation here...
let num = Math.floor(Date.now()/1000) - 1569394800;
let digits = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let len = Math.min(digits.length, 62);
let tag = '';
while (num > 0) {
tag = digits[num % len] + tag;
num = parseInt(num / len, 10);
}
let body = {
'v': 3,
'toot': toot.prog,
'mode': toot.mode,
'src': toot.src,
'state': beebState,
'title': toot.title,
}
const params = {
Bucket: "bbcmic.ro",
Key: 'state/'+tag,
Body: JSON.stringify(body),
ACL:'public-read',
ContentType: 'application/json'
};
// Uploading files to the bucket
await s3.upload(params).promise();
console.log("Cache: bbcmic.ro/state/"+tag);
// load index.txt from S3, append tag, upload back to S3
let index = await s3.getObject({Bucket: "bbcmic.ro", Key: 'state/index.txt'}).promise();
index = index.Body.toString('utf-8');
index += tag+"\n";
params.Key = 'state/index.txt';
params.Body = index;
await s3.upload(params).promise();
await invalidateCloudFront(params.Key);
return tag;
}
async function invalidateCloudFront(fileKey) {
const distributionId = process.env.CLOUDFRONT;
const params = {
DistributionId: distributionId,
InvalidationBatch: {
CallerReference: Date.now().toString(),
Paths: {
Quantity: 1,
Items: [`/${fileKey}`]
}
}
};
await cloudfront.createInvalidation(params).promise();
console.log(`CloudFront invalidation created for ${fileKey}`);
}
module.exports = cache;