-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathasync-job.ts
More file actions
76 lines (67 loc) · 2.57 KB
/
async-job.ts
File metadata and controls
76 lines (67 loc) · 2.57 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
import { Construct } from 'constructs';
import { CfnOutput, Duration, RemovalPolicy, TimeZone } from 'aws-cdk-lib';
import { LogGroup, RetentionDays } from 'aws-cdk-lib/aws-logs';
import { Architecture, DockerImageCode, DockerImageFunction, IFunction } from 'aws-cdk-lib/aws-lambda';
import { Platform } from 'aws-cdk-lib/aws-ecr-assets';
import { Database } from './database';
import { EventBus } from './event-bus';
import { PolicyStatement } from 'aws-cdk-lib/aws-iam';
import { join } from 'path';
import { Schedule, ScheduleExpression, ScheduleTargetInput } from 'aws-cdk-lib/aws-scheduler';
import { LambdaInvoke } from 'aws-cdk-lib/aws-scheduler-targets';
export interface AsyncJobProps {
readonly database: Database;
readonly eventBus: EventBus;
}
export class AsyncJob extends Construct {
readonly handler: IFunction;
constructor(scope: Construct, id: string, props: AsyncJobProps) {
super(scope, id);
const { database, eventBus } = props;
const handler = new DockerImageFunction(this, 'Handler', {
code: DockerImageCode.fromImageAsset(join('..', 'webapp'), {
cmd: ['async-job-runner.handler'],
platform: Platform.LINUX_ARM64,
file: 'job.Dockerfile',
}),
memorySize: 256,
timeout: Duration.minutes(10),
architecture: Architecture.ARM_64,
environment: {
...database.getLambdaEnvironment('main'),
EVENT_HTTP_ENDPOINT: eventBus.httpEndpoint,
},
vpc: database.cluster.vpc,
// limit concurrency to mitigate any possible EDoS attacks
reservedConcurrentExecutions: 1,
logGroup: new LogGroup(this, 'HandlerLogs', {
retention: RetentionDays.ONE_WEEK,
removalPolicy: RemovalPolicy.DESTROY,
}),
});
handler.connections.allowToDefaultPort(database);
eventBus.api.grantPublish(handler);
handler.addToRolePolicy(
new PolicyStatement({
actions: ['translate:TranslateText', 'comprehend:DetectDominantLanguage'],
resources: ['*'],
}),
);
new CfnOutput(this, 'HandlerArn', { value: handler.functionArn });
this.handler = handler;
// you can add scheduled jobs here.
this.addSchedule(
'SampleJob',
ScheduleExpression.cron({ minute: '0', hour: '0', day: '1', timeZone: TimeZone.ETC_UTC }),
);
}
public addSchedule(jobType: string, schedule: ScheduleExpression, payload?: any) {
return new Schedule(this, jobType, {
schedule,
target: new LambdaInvoke(this.handler, {
input: ScheduleTargetInput.fromObject({ jobType, payload }),
retryAttempts: 5,
}),
});
}
}