@ericminassian/platform-engine 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients.d.ts +50 -0
- package/dist/clients.js +103 -0
- package/dist/clients.js.map +1 -0
- package/dist/compat.d.ts +19 -0
- package/dist/compat.js +63 -0
- package/dist/compat.js.map +1 -0
- package/dist/drivers/cognito.d.ts +18 -0
- package/dist/drivers/cognito.js +113 -0
- package/dist/drivers/cognito.js.map +1 -0
- package/dist/drivers/dynamodb.d.ts +26 -0
- package/dist/drivers/dynamodb.js +151 -0
- package/dist/drivers/dynamodb.js.map +1 -0
- package/dist/drivers/events.d.ts +21 -0
- package/dist/drivers/events.js +62 -0
- package/dist/drivers/events.js.map +1 -0
- package/dist/drivers/iam.d.ts +20 -0
- package/dist/drivers/iam.js +86 -0
- package/dist/drivers/iam.js.map +1 -0
- package/dist/drivers/index.d.ts +12 -0
- package/dist/drivers/index.js +13 -0
- package/dist/drivers/index.js.map +1 -0
- package/dist/drivers/kvs.d.ts +5 -0
- package/dist/drivers/kvs.js +28 -0
- package/dist/drivers/kvs.js.map +1 -0
- package/dist/drivers/lambda.d.ts +48 -0
- package/dist/drivers/lambda.js +158 -0
- package/dist/drivers/lambda.js.map +1 -0
- package/dist/drivers/logs.d.ts +20 -0
- package/dist/drivers/logs.js +62 -0
- package/dist/drivers/logs.js.map +1 -0
- package/dist/drivers/s3.d.ts +30 -0
- package/dist/drivers/s3.js +126 -0
- package/dist/drivers/s3.js.map +1 -0
- package/dist/drivers/scheduler.d.ts +21 -0
- package/dist/drivers/scheduler.js +59 -0
- package/dist/drivers/scheduler.js.map +1 -0
- package/dist/drivers/sqs.d.ts +18 -0
- package/dist/drivers/sqs.js +46 -0
- package/dist/drivers/sqs.js.map +1 -0
- package/dist/drivers/ssm.d.ts +16 -0
- package/dist/drivers/ssm.js +45 -0
- package/dist/drivers/ssm.js.map +1 -0
- package/dist/drivers/web-function.d.ts +71 -0
- package/dist/drivers/web-function.js +227 -0
- package/dist/drivers/web-function.js.map +1 -0
- package/dist/emulator.d.ts +51 -0
- package/dist/emulator.js +142 -0
- package/dist/emulator.js.map +1 -0
- package/dist/index.d.ts +140 -0
- package/dist/index.js +72 -0
- package/dist/index.js.map +1 -0
- package/dist/local.d.ts +12 -0
- package/dist/local.js +71 -0
- package/dist/local.js.map +1 -0
- package/dist/policy.d.ts +41 -0
- package/dist/policy.js +316 -0
- package/dist/policy.js.map +1 -0
- package/dist/stage.d.ts +19 -0
- package/dist/stage.js +479 -0
- package/dist/stage.js.map +1 -0
- package/dist/static.d.ts +9 -0
- package/dist/static.js +55 -0
- package/dist/static.js.map +1 -0
- package/dist/util.d.ts +56 -0
- package/dist/util.js +127 -0
- package/dist/util.js.map +1 -0
- package/package.json +48 -3
- package/src/clients.ts +140 -0
- package/src/compat.ts +63 -0
- package/src/drivers/cognito.ts +147 -0
- package/src/drivers/dynamodb.ts +206 -0
- package/src/drivers/events.ts +92 -0
- package/src/drivers/iam.ts +125 -0
- package/src/drivers/index.ts +12 -0
- package/src/drivers/kvs.ts +55 -0
- package/src/drivers/lambda.ts +283 -0
- package/src/drivers/logs.ts +81 -0
- package/src/drivers/s3.ts +196 -0
- package/src/drivers/scheduler.ts +90 -0
- package/src/drivers/sqs.ts +70 -0
- package/src/drivers/ssm.ts +65 -0
- package/src/drivers/web-function.ts +352 -0
- package/src/emulator.ts +203 -0
- package/src/index.ts +183 -0
- package/src/local.ts +75 -0
- package/src/policy.ts +377 -0
- package/src/stage.ts +568 -0
- package/src/static.ts +56 -0
- package/src/util.ts +175 -0
- package/README.md +0 -3
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AddPermissionCommand,
|
|
3
|
+
CreateEventSourceMappingCommand,
|
|
4
|
+
CreateFunctionCommand,
|
|
5
|
+
DeleteEventSourceMappingCommand,
|
|
6
|
+
DeleteFunctionCommand,
|
|
7
|
+
GetFunctionConfigurationCommand,
|
|
8
|
+
GetPolicyCommand,
|
|
9
|
+
ListEventSourceMappingsCommand,
|
|
10
|
+
RemovePermissionCommand,
|
|
11
|
+
TagResourceCommand,
|
|
12
|
+
UpdateEventSourceMappingCommand,
|
|
13
|
+
UpdateFunctionCodeCommand,
|
|
14
|
+
UpdateFunctionConfigurationCommand,
|
|
15
|
+
} from '@aws-sdk/client-lambda';
|
|
16
|
+
import type { S3Location } from '../index.ts';
|
|
17
|
+
import { type EngineContext, errorMessage, errorName, ignoreNotFound, retry, waitFor } from '../util.ts';
|
|
18
|
+
|
|
19
|
+
export interface FunctionSpec {
|
|
20
|
+
name: string;
|
|
21
|
+
roleArn: string;
|
|
22
|
+
runtime: string;
|
|
23
|
+
handler: string;
|
|
24
|
+
architecture: 'arm64' | 'x86_64';
|
|
25
|
+
memoryMb: number;
|
|
26
|
+
timeoutSeconds: number;
|
|
27
|
+
code: S3Location;
|
|
28
|
+
env: Record<string, string>;
|
|
29
|
+
logGroup?: string;
|
|
30
|
+
description?: string;
|
|
31
|
+
tags?: Record<string, string>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface FunctionState {
|
|
35
|
+
name: string;
|
|
36
|
+
arn: string;
|
|
37
|
+
created: boolean;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** IAM is eventually consistent: a new role can take seconds to be assumable by Lambda. */
|
|
41
|
+
const isRolePropagation = (e: unknown) =>
|
|
42
|
+
errorName(e) === 'InvalidParameterValueException' && /role|assume/i.test(errorMessage(e));
|
|
43
|
+
const isUpdateInProgress = (e: unknown) => errorName(e) === 'ResourceConflictException';
|
|
44
|
+
|
|
45
|
+
export async function ensureFunction(ctx: EngineContext, spec: FunctionSpec): Promise<FunctionState> {
|
|
46
|
+
const lambda = ctx.clients.lambda;
|
|
47
|
+
const existing = await ignoreNotFound(
|
|
48
|
+
lambda.send(new GetFunctionConfigurationCommand({ FunctionName: spec.name })),
|
|
49
|
+
);
|
|
50
|
+
const config = {
|
|
51
|
+
Role: spec.roleArn,
|
|
52
|
+
Runtime: spec.runtime as never,
|
|
53
|
+
Handler: spec.handler,
|
|
54
|
+
MemorySize: spec.memoryMb,
|
|
55
|
+
Timeout: spec.timeoutSeconds,
|
|
56
|
+
Description: spec.description,
|
|
57
|
+
Environment: { Variables: spec.env },
|
|
58
|
+
LoggingConfig: spec.logGroup ? { LogFormat: 'JSON' as const, LogGroup: spec.logGroup } : undefined,
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
if (!existing) {
|
|
62
|
+
const res = await retry(
|
|
63
|
+
() =>
|
|
64
|
+
lambda.send(
|
|
65
|
+
new CreateFunctionCommand({
|
|
66
|
+
FunctionName: spec.name,
|
|
67
|
+
...config,
|
|
68
|
+
Architectures: [spec.architecture],
|
|
69
|
+
Code: { S3Bucket: spec.code.bucket, S3Key: spec.code.key, S3ObjectVersion: spec.code.versionId },
|
|
70
|
+
Tags: spec.tags,
|
|
71
|
+
}),
|
|
72
|
+
),
|
|
73
|
+
{ when: isRolePropagation, attempts: 15, delayMs: 2_000 },
|
|
74
|
+
);
|
|
75
|
+
ctx.log('info', 'created function', `function ${spec.name}`);
|
|
76
|
+
await waitReady(ctx, spec.name);
|
|
77
|
+
return { name: spec.name, arn: res.FunctionArn!, created: true };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
await waitReady(ctx, spec.name);
|
|
81
|
+
await retry(
|
|
82
|
+
() =>
|
|
83
|
+
lambda.send(
|
|
84
|
+
new UpdateFunctionCodeCommand({
|
|
85
|
+
FunctionName: spec.name,
|
|
86
|
+
S3Bucket: spec.code.bucket,
|
|
87
|
+
S3Key: spec.code.key,
|
|
88
|
+
S3ObjectVersion: spec.code.versionId,
|
|
89
|
+
Architectures: [spec.architecture],
|
|
90
|
+
}),
|
|
91
|
+
),
|
|
92
|
+
{ when: isUpdateInProgress },
|
|
93
|
+
);
|
|
94
|
+
await waitReady(ctx, spec.name);
|
|
95
|
+
await retry(
|
|
96
|
+
() => lambda.send(new UpdateFunctionConfigurationCommand({ FunctionName: spec.name, ...config })),
|
|
97
|
+
{
|
|
98
|
+
when: (e) => isUpdateInProgress(e) || isRolePropagation(e),
|
|
99
|
+
},
|
|
100
|
+
);
|
|
101
|
+
await waitReady(ctx, spec.name);
|
|
102
|
+
if (spec.tags)
|
|
103
|
+
await lambda.send(new TagResourceCommand({ Resource: existing.FunctionArn, Tags: spec.tags }));
|
|
104
|
+
ctx.log('info', 'updated function', `function ${spec.name}`);
|
|
105
|
+
return { name: spec.name, arn: existing.FunctionArn!, created: false };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Wait until the function is Active and no update is in progress. */
|
|
109
|
+
export async function waitReady(ctx: EngineContext, name: string): Promise<void> {
|
|
110
|
+
await waitFor(
|
|
111
|
+
`function ${name} ready`,
|
|
112
|
+
async () => {
|
|
113
|
+
const c = await ctx.clients.lambda.send(new GetFunctionConfigurationCommand({ FunctionName: name }));
|
|
114
|
+
if (c.State === 'Failed') throw new Error(`function ${name} failed: ${c.StateReason}`);
|
|
115
|
+
if (c.LastUpdateStatus === 'Failed')
|
|
116
|
+
throw new Error(`function ${name} update failed: ${c.LastUpdateStatusReason}`);
|
|
117
|
+
return c.State === 'Active' && c.LastUpdateStatus !== 'InProgress';
|
|
118
|
+
},
|
|
119
|
+
{ timeoutMs: 300_000 },
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function deleteFunction(ctx: EngineContext, name: string): Promise<boolean> {
|
|
124
|
+
const res = await ignoreNotFound(
|
|
125
|
+
ctx.clients.lambda.send(new DeleteFunctionCommand({ FunctionName: name })),
|
|
126
|
+
);
|
|
127
|
+
if (res) ctx.log('info', 'deleted function', `function ${name}`);
|
|
128
|
+
return res !== undefined;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ------------------------------------------------------------------ event source mappings
|
|
132
|
+
|
|
133
|
+
export interface EventSourceMappingSpec {
|
|
134
|
+
functionName: string;
|
|
135
|
+
sourceArn: string;
|
|
136
|
+
batchSize: number;
|
|
137
|
+
maxConcurrency?: number;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function ensureEventSourceMapping(
|
|
141
|
+
ctx: EngineContext,
|
|
142
|
+
spec: EventSourceMappingSpec,
|
|
143
|
+
): Promise<string> {
|
|
144
|
+
const lambda = ctx.clients.lambda;
|
|
145
|
+
const list = await lambda.send(
|
|
146
|
+
new ListEventSourceMappingsCommand({ FunctionName: spec.functionName, EventSourceArn: spec.sourceArn }),
|
|
147
|
+
);
|
|
148
|
+
const existing = list.EventSourceMappings?.[0];
|
|
149
|
+
const common = {
|
|
150
|
+
BatchSize: spec.batchSize,
|
|
151
|
+
FunctionResponseTypes: ['ReportBatchItemFailures' as const],
|
|
152
|
+
ScalingConfig: spec.maxConcurrency ? { MaximumConcurrency: spec.maxConcurrency } : undefined,
|
|
153
|
+
Enabled: true,
|
|
154
|
+
};
|
|
155
|
+
if (existing?.UUID) {
|
|
156
|
+
await retry(() => lambda.send(new UpdateEventSourceMappingCommand({ UUID: existing.UUID, ...common })), {
|
|
157
|
+
when: isUpdateInProgress,
|
|
158
|
+
});
|
|
159
|
+
return existing.UUID;
|
|
160
|
+
}
|
|
161
|
+
// The role's sqs:ReceiveMessage grant must be visible before Lambda accepts the mapping.
|
|
162
|
+
const res = await retry(
|
|
163
|
+
() =>
|
|
164
|
+
lambda.send(
|
|
165
|
+
new CreateEventSourceMappingCommand({
|
|
166
|
+
FunctionName: spec.functionName,
|
|
167
|
+
EventSourceArn: spec.sourceArn,
|
|
168
|
+
...common,
|
|
169
|
+
}),
|
|
170
|
+
),
|
|
171
|
+
{
|
|
172
|
+
when: (e) =>
|
|
173
|
+
errorName(e) === 'InvalidParameterValueException' && /permission|role/i.test(errorMessage(e)),
|
|
174
|
+
attempts: 15,
|
|
175
|
+
delayMs: 2_000,
|
|
176
|
+
},
|
|
177
|
+
);
|
|
178
|
+
ctx.log('info', 'created event source mapping', `esm ${spec.sourceArn.split(':').pop()}`);
|
|
179
|
+
return res.UUID!;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function listEventSourceMappings(
|
|
183
|
+
ctx: EngineContext,
|
|
184
|
+
functionName: string,
|
|
185
|
+
): Promise<Array<{ uuid: string; sourceArn: string }>> {
|
|
186
|
+
const out: Array<{ uuid: string; sourceArn: string }> = [];
|
|
187
|
+
let Marker: string | undefined;
|
|
188
|
+
do {
|
|
189
|
+
const res = await ignoreNotFound(
|
|
190
|
+
ctx.clients.lambda.send(new ListEventSourceMappingsCommand({ FunctionName: functionName, Marker })),
|
|
191
|
+
);
|
|
192
|
+
if (!res) return out;
|
|
193
|
+
for (const m of res.EventSourceMappings ?? []) {
|
|
194
|
+
if (m.UUID && m.EventSourceArn) out.push({ uuid: m.UUID, sourceArn: m.EventSourceArn });
|
|
195
|
+
}
|
|
196
|
+
Marker = res.NextMarker;
|
|
197
|
+
} while (Marker);
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export async function deleteEventSourceMapping(ctx: EngineContext, uuid: string): Promise<void> {
|
|
202
|
+
// A mapping that is still Creating/Updating refuses deletion with ResourceInUseException.
|
|
203
|
+
await ignoreNotFound(
|
|
204
|
+
retry(() => ctx.clients.lambda.send(new DeleteEventSourceMappingCommand({ UUID: uuid })), {
|
|
205
|
+
when: (e) => isUpdateInProgress(e) || errorName(e) === 'ResourceInUseException',
|
|
206
|
+
attempts: 30,
|
|
207
|
+
delayMs: 1_000,
|
|
208
|
+
}),
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// ------------------------------------------------------------------ resource policy
|
|
213
|
+
|
|
214
|
+
export interface PermissionSpec {
|
|
215
|
+
functionName: string;
|
|
216
|
+
statementId: string;
|
|
217
|
+
principal: string;
|
|
218
|
+
action: string;
|
|
219
|
+
sourceArn?: string;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Add a resource-policy statement; replaces a same-id statement that differs. */
|
|
223
|
+
export async function ensurePermission(ctx: EngineContext, spec: PermissionSpec): Promise<void> {
|
|
224
|
+
const lambda = ctx.clients.lambda;
|
|
225
|
+
const current = await ignoreNotFound(
|
|
226
|
+
lambda.send(new GetPolicyCommand({ FunctionName: spec.functionName })),
|
|
227
|
+
);
|
|
228
|
+
if (current?.Policy) {
|
|
229
|
+
const doc = JSON.parse(current.Policy) as {
|
|
230
|
+
Statement: Array<{
|
|
231
|
+
Sid: string;
|
|
232
|
+
Principal?: { Service?: string };
|
|
233
|
+
Action?: string;
|
|
234
|
+
Condition?: { ArnLike?: { 'AWS:SourceArn'?: string } };
|
|
235
|
+
}>;
|
|
236
|
+
};
|
|
237
|
+
const st = doc.Statement.find((s) => s.Sid === spec.statementId);
|
|
238
|
+
if (st) {
|
|
239
|
+
const same =
|
|
240
|
+
st.Principal?.Service === spec.principal &&
|
|
241
|
+
st.Action === spec.action &&
|
|
242
|
+
(st.Condition?.ArnLike?.['AWS:SourceArn'] ?? undefined) === spec.sourceArn;
|
|
243
|
+
if (same) return;
|
|
244
|
+
await lambda.send(
|
|
245
|
+
new RemovePermissionCommand({ FunctionName: spec.functionName, StatementId: spec.statementId }),
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
try {
|
|
250
|
+
await lambda.send(
|
|
251
|
+
new AddPermissionCommand({
|
|
252
|
+
FunctionName: spec.functionName,
|
|
253
|
+
StatementId: spec.statementId,
|
|
254
|
+
Principal: spec.principal,
|
|
255
|
+
Action: spec.action,
|
|
256
|
+
SourceArn: spec.sourceArn,
|
|
257
|
+
}),
|
|
258
|
+
);
|
|
259
|
+
} catch (e) {
|
|
260
|
+
// Statement already present (e.g. GetPolicy returned a stale view).
|
|
261
|
+
if (errorName(e) !== 'ResourceConflictException') throw e;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export async function removePermission(
|
|
266
|
+
ctx: EngineContext,
|
|
267
|
+
functionName: string,
|
|
268
|
+
statementId: string,
|
|
269
|
+
): Promise<void> {
|
|
270
|
+
await ignoreNotFound(
|
|
271
|
+
ctx.clients.lambda.send(
|
|
272
|
+
new RemovePermissionCommand({ FunctionName: functionName, StatementId: statementId }),
|
|
273
|
+
),
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export async function listPermissionIds(ctx: EngineContext, functionName: string): Promise<string[]> {
|
|
278
|
+
const current = await ignoreNotFound(
|
|
279
|
+
ctx.clients.lambda.send(new GetPolicyCommand({ FunctionName: functionName })),
|
|
280
|
+
);
|
|
281
|
+
if (!current?.Policy) return [];
|
|
282
|
+
return (JSON.parse(current.Policy) as { Statement: Array<{ Sid: string }> }).Statement.map((s) => s.Sid);
|
|
283
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CreateLogGroupCommand,
|
|
3
|
+
DeleteLogGroupCommand,
|
|
4
|
+
DescribeLogGroupsCommand,
|
|
5
|
+
PutAccountPolicyCommand,
|
|
6
|
+
PutRetentionPolicyCommand,
|
|
7
|
+
} from '@aws-sdk/client-cloudwatch-logs';
|
|
8
|
+
import { type EngineContext, errorName, ignoreNotFound } from '../util.ts';
|
|
9
|
+
|
|
10
|
+
/** Retention values CloudWatch Logs accepts. */
|
|
11
|
+
const RETENTION_DAYS = [
|
|
12
|
+
1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, 3653,
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
export function snapRetention(days: number): number {
|
|
16
|
+
return RETENTION_DAYS.find((d) => d >= days) ?? 3653;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function ensureLogGroup(
|
|
20
|
+
ctx: EngineContext,
|
|
21
|
+
spec: { name: string; retentionDays: number; tags?: Record<string, string> },
|
|
22
|
+
): Promise<string> {
|
|
23
|
+
const logs = ctx.clients.logs;
|
|
24
|
+
try {
|
|
25
|
+
await logs.send(new CreateLogGroupCommand({ logGroupName: spec.name, tags: spec.tags }));
|
|
26
|
+
ctx.log('info', 'created log group', `log-group ${spec.name}`);
|
|
27
|
+
} catch (e) {
|
|
28
|
+
if (errorName(e) !== 'ResourceAlreadyExistsException') throw e;
|
|
29
|
+
}
|
|
30
|
+
await logs.send(
|
|
31
|
+
new PutRetentionPolicyCommand({
|
|
32
|
+
logGroupName: spec.name,
|
|
33
|
+
retentionInDays: snapRetention(spec.retentionDays),
|
|
34
|
+
}),
|
|
35
|
+
);
|
|
36
|
+
const acct = await ctx.accountId();
|
|
37
|
+
return `arn:aws:logs:${ctx.region}:${acct}:log-group:${spec.name}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function deleteLogGroup(ctx: EngineContext, name: string): Promise<void> {
|
|
41
|
+
await ignoreNotFound(ctx.clients.logs.send(new DeleteLogGroupCommand({ logGroupName: name })));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function listLogGroups(ctx: EngineContext, prefix: string): Promise<string[]> {
|
|
45
|
+
const out: string[] = [];
|
|
46
|
+
let nextToken: string | undefined;
|
|
47
|
+
do {
|
|
48
|
+
const res = await ctx.clients.logs.send(
|
|
49
|
+
new DescribeLogGroupsCommand({ logGroupNamePrefix: prefix, nextToken }),
|
|
50
|
+
);
|
|
51
|
+
for (const g of res.logGroups ?? []) if (g.logGroupName) out.push(g.logGroupName);
|
|
52
|
+
nextToken = res.nextToken;
|
|
53
|
+
} while (nextToken);
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The one account-level subscription filter: every log group in the region
|
|
59
|
+
* (except `excludeLogGroups`, to avoid the processor feeding itself) streams
|
|
60
|
+
* lines matching `filterPattern` to `destinationArn`.
|
|
61
|
+
*/
|
|
62
|
+
export async function ensureAccountSubscriptionFilter(
|
|
63
|
+
ctx: EngineContext,
|
|
64
|
+
spec: { name: string; destinationArn: string; filterPattern: string; excludeLogGroups: string[] },
|
|
65
|
+
): Promise<void> {
|
|
66
|
+
await ctx.clients.logs.send(
|
|
67
|
+
new PutAccountPolicyCommand({
|
|
68
|
+
policyName: spec.name,
|
|
69
|
+
policyType: 'SUBSCRIPTION_FILTER_POLICY',
|
|
70
|
+
scope: 'ALL',
|
|
71
|
+
policyDocument: JSON.stringify({
|
|
72
|
+
DestinationArn: spec.destinationArn,
|
|
73
|
+
FilterPattern: spec.filterPattern,
|
|
74
|
+
}),
|
|
75
|
+
selectionCriteria: spec.excludeLogGroups.length
|
|
76
|
+
? `LogGroupName NOT IN [${spec.excludeLogGroups.map((g) => JSON.stringify(g)).join(', ')}]`
|
|
77
|
+
: undefined,
|
|
78
|
+
}),
|
|
79
|
+
);
|
|
80
|
+
ctx.log('info', 'put account subscription filter', `account-policy ${spec.name}`);
|
|
81
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type CORSRule,
|
|
3
|
+
CreateBucketCommand,
|
|
4
|
+
DeleteObjectsCommand,
|
|
5
|
+
GetObjectCommand,
|
|
6
|
+
HeadBucketCommand,
|
|
7
|
+
type LifecycleRule,
|
|
8
|
+
ListObjectsV2Command,
|
|
9
|
+
ListObjectVersionsCommand,
|
|
10
|
+
PutBucketCorsCommand,
|
|
11
|
+
PutBucketLifecycleConfigurationCommand,
|
|
12
|
+
PutBucketPolicyCommand,
|
|
13
|
+
PutBucketTaggingCommand,
|
|
14
|
+
PutBucketVersioningCommand,
|
|
15
|
+
PutObjectCommand,
|
|
16
|
+
PutPublicAccessBlockCommand,
|
|
17
|
+
} from '@aws-sdk/client-s3';
|
|
18
|
+
import { unzipSync } from 'fflate';
|
|
19
|
+
import type { S3Location } from '../index.ts';
|
|
20
|
+
import { cacheControlFor, contentTypeFor } from '../static.ts';
|
|
21
|
+
import {
|
|
22
|
+
type EngineContext,
|
|
23
|
+
errorName,
|
|
24
|
+
isNotFound,
|
|
25
|
+
mapLimit,
|
|
26
|
+
type PolicyDocument,
|
|
27
|
+
tagList,
|
|
28
|
+
} from '../util.ts';
|
|
29
|
+
|
|
30
|
+
export interface BucketSpec {
|
|
31
|
+
name: string;
|
|
32
|
+
versioned?: boolean;
|
|
33
|
+
cors?: CORSRule[];
|
|
34
|
+
lifecycle?: LifecycleRule[];
|
|
35
|
+
policy?: PolicyDocument;
|
|
36
|
+
tags?: Record<string, string>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function ensureBucket(ctx: EngineContext, spec: BucketSpec): Promise<string> {
|
|
40
|
+
const s3 = ctx.clients.s3;
|
|
41
|
+
let exists = true;
|
|
42
|
+
try {
|
|
43
|
+
await s3.send(new HeadBucketCommand({ Bucket: spec.name }));
|
|
44
|
+
} catch (e) {
|
|
45
|
+
if (!isNotFound(e) && errorName(e) !== 'NotFound') throw e;
|
|
46
|
+
exists = false;
|
|
47
|
+
}
|
|
48
|
+
if (!exists) {
|
|
49
|
+
await s3.send(
|
|
50
|
+
new CreateBucketCommand({
|
|
51
|
+
Bucket: spec.name,
|
|
52
|
+
...(ctx.region === 'us-east-1'
|
|
53
|
+
? {}
|
|
54
|
+
: { CreateBucketConfiguration: { LocationConstraint: ctx.region as never } }),
|
|
55
|
+
}),
|
|
56
|
+
);
|
|
57
|
+
ctx.log('info', 'created bucket', `bucket ${spec.name}`);
|
|
58
|
+
}
|
|
59
|
+
await s3.send(
|
|
60
|
+
new PutPublicAccessBlockCommand({
|
|
61
|
+
Bucket: spec.name,
|
|
62
|
+
PublicAccessBlockConfiguration: {
|
|
63
|
+
BlockPublicAcls: true,
|
|
64
|
+
IgnorePublicAcls: true,
|
|
65
|
+
BlockPublicPolicy: true,
|
|
66
|
+
RestrictPublicBuckets: true,
|
|
67
|
+
},
|
|
68
|
+
}),
|
|
69
|
+
);
|
|
70
|
+
if (spec.versioned) {
|
|
71
|
+
await s3.send(
|
|
72
|
+
new PutBucketVersioningCommand({ Bucket: spec.name, VersioningConfiguration: { Status: 'Enabled' } }),
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
if (spec.cors)
|
|
76
|
+
await s3.send(
|
|
77
|
+
new PutBucketCorsCommand({ Bucket: spec.name, CORSConfiguration: { CORSRules: spec.cors } }),
|
|
78
|
+
);
|
|
79
|
+
if (spec.lifecycle) {
|
|
80
|
+
await s3.send(
|
|
81
|
+
new PutBucketLifecycleConfigurationCommand({
|
|
82
|
+
Bucket: spec.name,
|
|
83
|
+
LifecycleConfiguration: { Rules: spec.lifecycle },
|
|
84
|
+
}),
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
if (spec.policy)
|
|
88
|
+
await s3.send(new PutBucketPolicyCommand({ Bucket: spec.name, Policy: JSON.stringify(spec.policy) }));
|
|
89
|
+
if (spec.tags)
|
|
90
|
+
await s3.send(
|
|
91
|
+
new PutBucketTaggingCommand({ Bucket: spec.name, Tagging: { TagSet: tagList(spec.tags) } }),
|
|
92
|
+
);
|
|
93
|
+
return `arn:aws:s3:::${spec.name}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export async function putObject(
|
|
97
|
+
ctx: EngineContext,
|
|
98
|
+
spec: {
|
|
99
|
+
bucket: string;
|
|
100
|
+
key: string;
|
|
101
|
+
body: Uint8Array | string;
|
|
102
|
+
contentType?: string;
|
|
103
|
+
cacheControl?: string;
|
|
104
|
+
},
|
|
105
|
+
): Promise<S3Location> {
|
|
106
|
+
const res = await ctx.clients.s3.send(
|
|
107
|
+
new PutObjectCommand({
|
|
108
|
+
Bucket: spec.bucket,
|
|
109
|
+
Key: spec.key,
|
|
110
|
+
Body: spec.body,
|
|
111
|
+
ContentType: spec.contentType,
|
|
112
|
+
CacheControl: spec.cacheControl,
|
|
113
|
+
}),
|
|
114
|
+
);
|
|
115
|
+
return { bucket: spec.bucket, key: spec.key, ...(res.VersionId ? { versionId: res.VersionId } : {}) };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export async function getObjectBytes(ctx: EngineContext, loc: S3Location): Promise<Uint8Array> {
|
|
119
|
+
const res = await ctx.clients.s3.send(
|
|
120
|
+
new GetObjectCommand({ Bucket: loc.bucket, Key: loc.key, VersionId: loc.versionId }),
|
|
121
|
+
);
|
|
122
|
+
return res.Body!.transformToByteArray();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Unzip a static bundle into `bucket/prefix/` with content types and cache headers. Returns file count. */
|
|
126
|
+
export async function publishStaticZip(
|
|
127
|
+
ctx: EngineContext,
|
|
128
|
+
spec: { source: S3Location; bucket: string; prefix: string },
|
|
129
|
+
): Promise<number> {
|
|
130
|
+
const zip = await getObjectBytes(ctx, spec.source);
|
|
131
|
+
const files = Object.entries(unzipSync(zip)).filter(([path]) => !path.endsWith('/'));
|
|
132
|
+
await mapLimit(files, 16, async ([path, body]) => {
|
|
133
|
+
const rel = path.replace(/^\/+/, '');
|
|
134
|
+
await putObject(ctx, {
|
|
135
|
+
bucket: spec.bucket,
|
|
136
|
+
key: `${spec.prefix}/${rel}`,
|
|
137
|
+
body,
|
|
138
|
+
contentType: contentTypeFor(rel),
|
|
139
|
+
cacheControl: cacheControlFor(rel),
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
ctx.log('info', `published ${files.length} static files`, `static ${spec.prefix}`);
|
|
143
|
+
return files.length;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Immediate child "directories" under `prefix` (ends with `/`). */
|
|
147
|
+
export async function listChildPrefixes(
|
|
148
|
+
ctx: EngineContext,
|
|
149
|
+
bucket: string,
|
|
150
|
+
prefix: string,
|
|
151
|
+
): Promise<string[]> {
|
|
152
|
+
const out: string[] = [];
|
|
153
|
+
let ContinuationToken: string | undefined;
|
|
154
|
+
do {
|
|
155
|
+
const res = await ctx.clients.s3.send(
|
|
156
|
+
new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, Delimiter: '/', ContinuationToken }),
|
|
157
|
+
);
|
|
158
|
+
for (const p of res.CommonPrefixes ?? []) if (p.Prefix) out.push(p.Prefix);
|
|
159
|
+
ContinuationToken = res.NextContinuationToken;
|
|
160
|
+
} while (ContinuationToken);
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Delete every object (and, in versioned buckets, every version) under `prefix`. */
|
|
165
|
+
export async function deletePrefix(ctx: EngineContext, bucket: string, prefix: string): Promise<number> {
|
|
166
|
+
const s3 = ctx.clients.s3;
|
|
167
|
+
let deleted = 0;
|
|
168
|
+
try {
|
|
169
|
+
let KeyMarker: string | undefined;
|
|
170
|
+
let VersionIdMarker: string | undefined;
|
|
171
|
+
do {
|
|
172
|
+
const res = await s3.send(
|
|
173
|
+
new ListObjectVersionsCommand({ Bucket: bucket, Prefix: prefix, KeyMarker, VersionIdMarker }),
|
|
174
|
+
);
|
|
175
|
+
const objects = [...(res.Versions ?? []), ...(res.DeleteMarkers ?? [])].map((v) => ({
|
|
176
|
+
Key: v.Key!,
|
|
177
|
+
VersionId: v.VersionId ?? undefined,
|
|
178
|
+
}));
|
|
179
|
+
for (let i = 0; i < objects.length; i += 1000) {
|
|
180
|
+
const batch = objects.slice(i, i + 1000);
|
|
181
|
+
if (batch.length) {
|
|
182
|
+
await s3.send(
|
|
183
|
+
new DeleteObjectsCommand({ Bucket: bucket, Delete: { Objects: batch, Quiet: true } }),
|
|
184
|
+
);
|
|
185
|
+
deleted += batch.length;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
KeyMarker = res.IsTruncated ? res.NextKeyMarker : undefined;
|
|
189
|
+
VersionIdMarker = res.IsTruncated ? res.NextVersionIdMarker : undefined;
|
|
190
|
+
} while (KeyMarker);
|
|
191
|
+
} catch (e) {
|
|
192
|
+
if (isNotFound(e)) return deleted;
|
|
193
|
+
throw e;
|
|
194
|
+
}
|
|
195
|
+
return deleted;
|
|
196
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CreateScheduleCommand,
|
|
3
|
+
CreateScheduleGroupCommand,
|
|
4
|
+
DeleteScheduleCommand,
|
|
5
|
+
DeleteScheduleGroupCommand,
|
|
6
|
+
GetScheduleCommand,
|
|
7
|
+
GetScheduleGroupCommand,
|
|
8
|
+
ListSchedulesCommand,
|
|
9
|
+
UpdateScheduleCommand,
|
|
10
|
+
} from '@aws-sdk/client-scheduler';
|
|
11
|
+
import { type EngineContext, ignoreNotFound, retry, tagList } from '../util.ts';
|
|
12
|
+
|
|
13
|
+
export async function ensureScheduleGroup(
|
|
14
|
+
ctx: EngineContext,
|
|
15
|
+
spec: { name: string; tags?: Record<string, string> },
|
|
16
|
+
): Promise<string> {
|
|
17
|
+
const sch = ctx.clients.scheduler;
|
|
18
|
+
const existing = await ignoreNotFound(sch.send(new GetScheduleGroupCommand({ Name: spec.name })));
|
|
19
|
+
if (existing?.Arn) return existing.Arn;
|
|
20
|
+
const res = await sch.send(
|
|
21
|
+
new CreateScheduleGroupCommand({ Name: spec.name, Tags: spec.tags ? tagList(spec.tags) : undefined }),
|
|
22
|
+
);
|
|
23
|
+
ctx.log('info', 'created schedule group', `schedule-group ${spec.name}`);
|
|
24
|
+
return res.ScheduleGroupArn!;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ScheduleSpec {
|
|
28
|
+
group: string;
|
|
29
|
+
name: string;
|
|
30
|
+
/** EventBridge Scheduler expression (`cron(...)` / `rate(...)`). */
|
|
31
|
+
expression: string;
|
|
32
|
+
timezone?: string;
|
|
33
|
+
target: { arn: string; roleArn: string; input: string };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function ensureSchedule(ctx: EngineContext, spec: ScheduleSpec): Promise<void> {
|
|
37
|
+
const sch = ctx.clients.scheduler;
|
|
38
|
+
const definition = {
|
|
39
|
+
Name: spec.name,
|
|
40
|
+
GroupName: spec.group,
|
|
41
|
+
ScheduleExpression: spec.expression,
|
|
42
|
+
ScheduleExpressionTimezone: spec.timezone,
|
|
43
|
+
FlexibleTimeWindow: { Mode: 'OFF' as const },
|
|
44
|
+
State: 'ENABLED' as const,
|
|
45
|
+
Target: {
|
|
46
|
+
Arn: spec.target.arn,
|
|
47
|
+
RoleArn: spec.target.roleArn,
|
|
48
|
+
Input: spec.target.input,
|
|
49
|
+
RetryPolicy: { MaximumRetryAttempts: 2, MaximumEventAgeInSeconds: 3600 },
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
const existing = await ignoreNotFound(
|
|
53
|
+
sch.send(new GetScheduleCommand({ Name: spec.name, GroupName: spec.group })),
|
|
54
|
+
);
|
|
55
|
+
// A freshly created role may not be assumable by Scheduler yet.
|
|
56
|
+
await retry(
|
|
57
|
+
() =>
|
|
58
|
+
existing
|
|
59
|
+
? sch.send(new UpdateScheduleCommand(definition))
|
|
60
|
+
: sch.send(new CreateScheduleCommand(definition)),
|
|
61
|
+
{ when: (e) => /assume the role|execution role/i.test(String((e as Error).message)), attempts: 12 },
|
|
62
|
+
);
|
|
63
|
+
if (!existing) ctx.log('info', 'created schedule', `schedule ${spec.group}/${spec.name}`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function listSchedules(ctx: EngineContext, group: string): Promise<string[]> {
|
|
67
|
+
const out: string[] = [];
|
|
68
|
+
let NextToken: string | undefined;
|
|
69
|
+
do {
|
|
70
|
+
const res = await ignoreNotFound(
|
|
71
|
+
ctx.clients.scheduler.send(new ListSchedulesCommand({ GroupName: group, NextToken })),
|
|
72
|
+
);
|
|
73
|
+
if (!res) return out;
|
|
74
|
+
for (const s of res.Schedules ?? []) if (s.Name) out.push(s.Name);
|
|
75
|
+
NextToken = res.NextToken;
|
|
76
|
+
} while (NextToken);
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function deleteSchedule(ctx: EngineContext, group: string, name: string): Promise<void> {
|
|
81
|
+
await ignoreNotFound(
|
|
82
|
+
ctx.clients.scheduler.send(new DeleteScheduleCommand({ Name: name, GroupName: group })),
|
|
83
|
+
);
|
|
84
|
+
ctx.log('info', 'deleted schedule', `schedule ${group}/${name}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function deleteScheduleGroup(ctx: EngineContext, group: string): Promise<void> {
|
|
88
|
+
for (const s of await listSchedules(ctx, group)) await deleteSchedule(ctx, group, s);
|
|
89
|
+
await ignoreNotFound(ctx.clients.scheduler.send(new DeleteScheduleGroupCommand({ Name: group })));
|
|
90
|
+
}
|