forked from openaq/openaq-fetch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.ts
More file actions
104 lines (92 loc) · 2.63 KB
/
stack.ts
File metadata and controls
104 lines (92 loc) · 2.63 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
import * as cdk from 'aws-cdk-lib';
import * as iam from 'aws-cdk-lib/aws-iam';
import {
aws_events as events,
aws_events_targets as eventTargets,
aws_lambda as lambda,
aws_s3 as s3,
aws_sqs as sqs,
} from 'aws-cdk-lib';
import { SqsEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
import { execSync } from 'child_process';
import { copyFileSync, readdirSync } from 'fs';
interface keyable {
[key: string]: string
}
interface StackProps extends cdk.StackProps {
env: keyable;
}
export class RealtimeFetcherStack extends cdk.Stack {
constructor(
scope: cdk.App,
id: string,
{ env, ...props }: StackProps
) {
super(scope, id, props);
// add the package.json file
copyFileSync('./package.json', './src/package.json');
// add the node modules
const cmd = [
'npm ci',
].join(' ');
execSync(cmd);
env.QUEUE_NAME = `${id}-queue`;
const bucket = s3.Bucket.fromBucketName(
this,
'Data',
env.AWS_BUCKET_NAME
);
const queue = new sqs.Queue(this, 'RealtimeFetcherQueue', {
queueName: env.QUEUE_NAME,
visibilityTimeout: cdk.Duration.seconds(1800),
});
const scheduler = new lambda.Function(
this,
`${id}-scheduler-lambda`,
{
description: `Scheduler for ${id}-fetcher`,
code: lambda.Code.fromAsset('./src', { exclude: ['.env*', '*.sh'] }),
handler: 'scheduler.handler',
memorySize: 128,
runtime: lambda.Runtime.NODEJS_22_X,
timeout: cdk.Duration.seconds(30),
environment: env,
}
);
const fetcher = new lambda.Function(
this,
`${id}-fetcher-lambda`,
{
description: `Fetcher for ${id}`,
code: lambda.Code.fromAsset('./src', { exclude: ['.env*', '*.sh'] }),
handler: 'fetch.handler',
memorySize: 2048,
runtime: lambda.Runtime.NODEJS_22_X,
timeout: cdk.Duration.seconds(900),
environment: env,
}
);
if(env.TOPIC_ARN) {
fetcher.addToRolePolicy(
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ['sns:Publish'],
resources: [env.TOPIC_ARN],
})
);
}
bucket.grantReadWrite(fetcher);
queue.grantSendMessages(scheduler);
queue.grantConsumeMessages(fetcher);
fetcher.addEventSource(
new SqsEventSource(queue, {
batchSize: 1,
})
);
// finally we create our cron/event
new events.Rule(this, `${id}-scheduler-cron`, {
schedule: events.Schedule.rate(cdk.Duration.minutes(15)),
targets: [new eventTargets.LambdaFunction(scheduler)],
});
}
}