@ericminassian/platform-engine 0.2.0 → 0.4.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 +8 -0
- package/dist/clients.js +22 -1
- package/dist/clients.js.map +1 -1
- package/dist/compat.d.ts +21 -9
- package/dist/compat.js +27 -7
- package/dist/compat.js.map +1 -1
- package/dist/drivers/appsync.d.ts +49 -0
- package/dist/drivers/appsync.js +155 -0
- package/dist/drivers/appsync.js.map +1 -0
- package/dist/drivers/ecr.d.ts +109 -0
- package/dist/drivers/ecr.js +303 -0
- package/dist/drivers/ecr.js.map +1 -0
- package/dist/drivers/ecs.d.ts +163 -0
- package/dist/drivers/ecs.js +447 -0
- package/dist/drivers/ecs.js.map +1 -0
- package/dist/drivers/events.d.ts +10 -0
- package/dist/drivers/events.js +13 -1
- package/dist/drivers/events.js.map +1 -1
- package/dist/drivers/index.d.ts +5 -0
- package/dist/drivers/index.js +5 -0
- package/dist/drivers/index.js.map +1 -1
- package/dist/drivers/kvs.d.ts +3 -0
- package/dist/drivers/kvs.js +14 -7
- package/dist/drivers/kvs.js.map +1 -1
- package/dist/drivers/lambda.d.ts +22 -0
- package/dist/drivers/lambda.js +74 -3
- package/dist/drivers/lambda.js.map +1 -1
- package/dist/drivers/request-function.d.ts +60 -0
- package/dist/drivers/request-function.js +167 -0
- package/dist/drivers/request-function.js.map +1 -0
- package/dist/drivers/s3.d.ts +7 -0
- package/dist/drivers/s3.js +31 -0
- package/dist/drivers/s3.js.map +1 -1
- package/dist/drivers/scheduler.d.ts +24 -0
- package/dist/drivers/scheduler.js +60 -5
- package/dist/drivers/scheduler.js.map +1 -1
- package/dist/drivers/ses.d.ts +77 -0
- package/dist/drivers/ses.js +181 -0
- package/dist/drivers/ses.js.map +1 -0
- package/dist/drivers/sqs.d.ts +11 -0
- package/dist/drivers/sqs.js +67 -1
- package/dist/drivers/sqs.js.map +1 -1
- package/dist/drivers/ssm.d.ts +1 -0
- package/dist/drivers/ssm.js +23 -3
- package/dist/drivers/ssm.js.map +1 -1
- package/dist/drivers/web-function.d.ts +41 -11
- package/dist/drivers/web-function.js +62 -8
- package/dist/drivers/web-function.js.map +1 -1
- package/dist/emulator.js.map +1 -1
- package/dist/images.d.ts +104 -0
- package/dist/images.js +182 -0
- package/dist/images.js.map +1 -0
- package/dist/index.d.ts +132 -7
- package/dist/index.js +11 -2
- package/dist/index.js.map +1 -1
- package/dist/local.js +222 -7
- package/dist/local.js.map +1 -1
- package/dist/policy.d.ts +47 -4
- package/dist/policy.js +369 -15
- package/dist/policy.js.map +1 -1
- package/dist/services.d.ts +155 -0
- package/dist/services.js +464 -0
- package/dist/services.js.map +1 -0
- package/dist/stage.d.ts +44 -4
- package/dist/stage.js +681 -138
- package/dist/stage.js.map +1 -1
- package/dist/static.d.ts +1 -1
- package/dist/static.js +2 -36
- package/dist/static.js.map +1 -1
- package/dist/util.d.ts +22 -0
- package/dist/util.js +18 -2
- package/dist/util.js.map +1 -1
- package/package.json +20 -14
- package/src/clients.ts +25 -1
- package/src/compat.ts +34 -11
- package/src/drivers/appsync.ts +220 -0
- package/src/drivers/ecr.ts +457 -0
- package/src/drivers/ecs.ts +661 -0
- package/src/drivers/events.ts +29 -2
- package/src/drivers/index.ts +5 -0
- package/src/drivers/kvs.ts +21 -12
- package/src/drivers/lambda.ts +103 -2
- package/src/drivers/request-function.ts +295 -0
- package/src/drivers/s3.ts +46 -0
- package/src/drivers/scheduler.ts +88 -5
- package/src/drivers/ses.ts +267 -0
- package/src/drivers/sqs.ts +95 -0
- package/src/drivers/ssm.ts +23 -2
- package/src/drivers/web-function.ts +108 -17
- package/src/emulator.ts +3 -3
- package/src/images.ts +254 -0
- package/src/index.ts +131 -8
- package/src/local.ts +251 -7
- package/src/policy.ts +450 -26
- package/src/services.ts +663 -0
- package/src/stage.ts +839 -153
- package/src/static.ts +2 -37
- package/src/util.ts +38 -4
package/src/drivers/events.ts
CHANGED
|
@@ -29,8 +29,23 @@ export interface RuleSpec {
|
|
|
29
29
|
bus: string;
|
|
30
30
|
name: string;
|
|
31
31
|
pattern: unknown;
|
|
32
|
-
targets: Array<{
|
|
32
|
+
targets: Array<{
|
|
33
|
+
id: string;
|
|
34
|
+
arn: string;
|
|
35
|
+
input?: string;
|
|
36
|
+
roleArn?: string;
|
|
37
|
+
/**
|
|
38
|
+
* Where an event EventBridge couldn't deliver goes, after it retried for up to a day (the
|
|
39
|
+
* queue's policy must let this rule send to it).
|
|
40
|
+
*/
|
|
41
|
+
deadLetterArn?: string;
|
|
42
|
+
}>;
|
|
33
43
|
tags?: Record<string, string>;
|
|
44
|
+
/**
|
|
45
|
+
* Runs once the rule exists, before it targets anything new: where the
|
|
46
|
+
* targets grant the rule access, so no event is refused in between.
|
|
47
|
+
*/
|
|
48
|
+
beforeTargets?: (ruleArn: string) => Promise<void>;
|
|
34
49
|
}
|
|
35
50
|
|
|
36
51
|
export async function ensureRule(ctx: EngineContext, spec: RuleSpec): Promise<string> {
|
|
@@ -44,11 +59,23 @@ export async function ensureRule(ctx: EngineContext, spec: RuleSpec): Promise<st
|
|
|
44
59
|
Tags: spec.tags ? tagList(spec.tags) : undefined,
|
|
45
60
|
}),
|
|
46
61
|
);
|
|
62
|
+
await spec.beforeTargets?.(rule.RuleArn!);
|
|
47
63
|
await ev.send(
|
|
48
64
|
new PutTargetsCommand({
|
|
49
65
|
Rule: spec.name,
|
|
50
66
|
EventBusName: spec.bus,
|
|
51
|
-
Targets: spec.targets.map((t) => ({
|
|
67
|
+
Targets: spec.targets.map((t) => ({
|
|
68
|
+
Id: t.id,
|
|
69
|
+
Arn: t.arn,
|
|
70
|
+
Input: t.input,
|
|
71
|
+
RoleArn: t.roleArn,
|
|
72
|
+
...(t.deadLetterArn
|
|
73
|
+
? {
|
|
74
|
+
DeadLetterConfig: { Arn: t.deadLetterArn },
|
|
75
|
+
RetryPolicy: { MaximumRetryAttempts: 185, MaximumEventAgeInSeconds: 86_400 },
|
|
76
|
+
}
|
|
77
|
+
: {}),
|
|
78
|
+
})),
|
|
52
79
|
}),
|
|
53
80
|
);
|
|
54
81
|
const existing = await ev.send(new ListTargetsByRuleCommand({ Rule: spec.name, EventBusName: spec.bus }));
|
package/src/drivers/index.ts
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
|
+
export * from './appsync.ts';
|
|
1
2
|
export * from './cognito.ts';
|
|
2
3
|
export * from './dynamodb.ts';
|
|
4
|
+
export * from './ecr.ts';
|
|
5
|
+
export * from './ecs.ts';
|
|
3
6
|
export * from './events.ts';
|
|
4
7
|
export * from './iam.ts';
|
|
5
8
|
export * from './kvs.ts';
|
|
6
9
|
export * from './lambda.ts';
|
|
7
10
|
export * from './logs.ts';
|
|
11
|
+
export * from './request-function.ts';
|
|
8
12
|
export * from './s3.ts';
|
|
9
13
|
export * from './scheduler.ts';
|
|
14
|
+
export * from './ses.ts';
|
|
10
15
|
export * from './sqs.ts';
|
|
11
16
|
export * from './ssm.ts';
|
|
12
17
|
export * from './web-function.ts';
|
package/src/drivers/kvs.ts
CHANGED
|
@@ -19,16 +19,7 @@ export async function putRoute(
|
|
|
19
19
|
host: string,
|
|
20
20
|
record: RouteRecord,
|
|
21
21
|
): Promise<void> {
|
|
22
|
-
|
|
23
|
-
await retry(
|
|
24
|
-
async () => {
|
|
25
|
-
const d = await ctx.clients.kvs.send(new DescribeKeyValueStoreCommand({ KvsARN: kvsArn }));
|
|
26
|
-
await ctx.clients.kvs.send(
|
|
27
|
-
new PutKeyCommand({ KvsARN: kvsArn, Key: host, Value: value, IfMatch: d.ETag }),
|
|
28
|
-
);
|
|
29
|
-
},
|
|
30
|
-
{ when: isConflict, attempts: 8, delayMs: 300 },
|
|
31
|
-
);
|
|
22
|
+
await putKey(ctx, kvsArn, host, encodeRouteRecord(record));
|
|
32
23
|
ctx.log('info', `route ${host} → ${record.d}`, `route ${host}`);
|
|
33
24
|
}
|
|
34
25
|
|
|
@@ -37,8 +28,26 @@ export async function getRoute(
|
|
|
37
28
|
kvsArn: string,
|
|
38
29
|
host: string,
|
|
39
30
|
): Promise<RouteRecord | undefined> {
|
|
40
|
-
const
|
|
41
|
-
return
|
|
31
|
+
const value = await getKey(ctx, kvsArn, host);
|
|
32
|
+
return value ? (JSON.parse(value) as RouteRecord) : undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Any key's raw value (route records, and the platform's own entries such as realtime's). */
|
|
36
|
+
export async function getKey(ctx: EngineContext, kvsArn: string, key: string): Promise<string | undefined> {
|
|
37
|
+
const res = await ignoreNotFound(ctx.clients.kvs.send(new GetKeyCommand({ KvsARN: kvsArn, Key: key })));
|
|
38
|
+
return res?.Value || undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function putKey(ctx: EngineContext, kvsArn: string, key: string, value: string): Promise<void> {
|
|
42
|
+
await retry(
|
|
43
|
+
async () => {
|
|
44
|
+
const d = await ctx.clients.kvs.send(new DescribeKeyValueStoreCommand({ KvsARN: kvsArn }));
|
|
45
|
+
await ctx.clients.kvs.send(
|
|
46
|
+
new PutKeyCommand({ KvsARN: kvsArn, Key: key, Value: value, IfMatch: d.ETag }),
|
|
47
|
+
);
|
|
48
|
+
},
|
|
49
|
+
{ when: isConflict, attempts: 8, delayMs: 300 },
|
|
50
|
+
);
|
|
42
51
|
}
|
|
43
52
|
|
|
44
53
|
export async function deleteRoute(ctx: EngineContext, kvsArn: string, host: string): Promise<void> {
|
package/src/drivers/lambda.ts
CHANGED
|
@@ -4,9 +4,14 @@ import {
|
|
|
4
4
|
CreateFunctionCommand,
|
|
5
5
|
DeleteEventSourceMappingCommand,
|
|
6
6
|
DeleteFunctionCommand,
|
|
7
|
+
DeleteFunctionConcurrencyCommand,
|
|
8
|
+
GetFunctionConcurrencyCommand,
|
|
7
9
|
GetFunctionConfigurationCommand,
|
|
8
10
|
GetPolicyCommand,
|
|
9
11
|
ListEventSourceMappingsCommand,
|
|
12
|
+
ListFunctionsCommand,
|
|
13
|
+
PutFunctionConcurrencyCommand,
|
|
14
|
+
PutFunctionEventInvokeConfigCommand,
|
|
10
15
|
RemovePermissionCommand,
|
|
11
16
|
TagResourceCommand,
|
|
12
17
|
UpdateEventSourceMappingCommand,
|
|
@@ -55,7 +60,11 @@ export async function ensureFunction(ctx: EngineContext, spec: FunctionSpec): Pr
|
|
|
55
60
|
Timeout: spec.timeoutSeconds,
|
|
56
61
|
Description: spec.description,
|
|
57
62
|
Environment: { Variables: spec.env },
|
|
58
|
-
|
|
63
|
+
// WARN drops Lambda's own START/END/REPORT lines: the SDK's `job` and `env` lines carry the same
|
|
64
|
+
// facts, and every line is ingestion billed per GB.
|
|
65
|
+
LoggingConfig: spec.logGroup
|
|
66
|
+
? { LogFormat: 'JSON' as const, LogGroup: spec.logGroup, SystemLogLevel: 'WARN' as const }
|
|
67
|
+
: undefined,
|
|
59
68
|
};
|
|
60
69
|
|
|
61
70
|
if (!existing) {
|
|
@@ -128,6 +137,96 @@ export async function deleteFunction(ctx: EngineContext, name: string): Promise<
|
|
|
128
137
|
return res !== undefined;
|
|
129
138
|
}
|
|
130
139
|
|
|
140
|
+
/** Functions whose names start with `prefix`. Lambda can't filter by name, so this pages through all of them. */
|
|
141
|
+
export async function listFunctions(
|
|
142
|
+
ctx: EngineContext,
|
|
143
|
+
prefix: string,
|
|
144
|
+
): Promise<Array<{ name: string; arn: string }>> {
|
|
145
|
+
const out: Array<{ name: string; arn: string }> = [];
|
|
146
|
+
let Marker: string | undefined;
|
|
147
|
+
do {
|
|
148
|
+
const res = await ctx.clients.lambda.send(new ListFunctionsCommand({ Marker }));
|
|
149
|
+
for (const f of res.Functions ?? []) {
|
|
150
|
+
if (f.FunctionName?.startsWith(prefix) && f.FunctionArn)
|
|
151
|
+
out.push({ name: f.FunctionName, arn: f.FunctionArn });
|
|
152
|
+
}
|
|
153
|
+
Marker = res.NextMarker;
|
|
154
|
+
} while (Marker);
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ------------------------------------------------------------------ async invocations
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* How Lambda treats an async invocation whose run crashed or timed out (a
|
|
162
|
+
* handler's own failure never reaches Lambda: the SDK retries or
|
|
163
|
+
* dead-letters it): two more tries, events kept up to six hours while the
|
|
164
|
+
* function is throttled, then the record goes to `deadLetterArn`.
|
|
165
|
+
*/
|
|
166
|
+
export async function ensureAsyncConfig(
|
|
167
|
+
ctx: EngineContext,
|
|
168
|
+
spec: { functionName: string; deadLetterArn: string },
|
|
169
|
+
): Promise<void> {
|
|
170
|
+
// A destination is checked against the role's sqs:SendMessage grant, which IAM may still be
|
|
171
|
+
// propagating for a new role.
|
|
172
|
+
await retry(
|
|
173
|
+
() =>
|
|
174
|
+
ctx.clients.lambda.send(
|
|
175
|
+
new PutFunctionEventInvokeConfigCommand({
|
|
176
|
+
FunctionName: spec.functionName,
|
|
177
|
+
MaximumRetryAttempts: 2,
|
|
178
|
+
MaximumEventAgeInSeconds: 21_600,
|
|
179
|
+
DestinationConfig: { OnFailure: { Destination: spec.deadLetterArn } },
|
|
180
|
+
}),
|
|
181
|
+
),
|
|
182
|
+
{
|
|
183
|
+
when: (e) =>
|
|
184
|
+
isUpdateInProgress(e) ||
|
|
185
|
+
(errorName(e) === 'InvalidParameterValueException' &&
|
|
186
|
+
/permission|role|destination/i.test(errorMessage(e))),
|
|
187
|
+
attempts: 15,
|
|
188
|
+
delayMs: 2_000,
|
|
189
|
+
},
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Cap a function's concurrent runs (`undefined` removes the cap). Reserved
|
|
195
|
+
* concurrency comes out of the account's pool, which must keep 100 (or, on a
|
|
196
|
+
* new account, all of its 10) unreserved, so Lambda may refuse it.
|
|
197
|
+
*/
|
|
198
|
+
export async function ensureReservedConcurrency(
|
|
199
|
+
ctx: EngineContext,
|
|
200
|
+
functionName: string,
|
|
201
|
+
concurrency: number | undefined,
|
|
202
|
+
): Promise<void> {
|
|
203
|
+
const lambda = ctx.clients.lambda;
|
|
204
|
+
const current = (await lambda.send(new GetFunctionConcurrencyCommand({ FunctionName: functionName })))
|
|
205
|
+
.ReservedConcurrentExecutions;
|
|
206
|
+
if (current === concurrency) return;
|
|
207
|
+
if (concurrency === undefined) {
|
|
208
|
+
await lambda.send(new DeleteFunctionConcurrencyCommand({ FunctionName: functionName }));
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
await lambda.send(
|
|
213
|
+
new PutFunctionConcurrencyCommand({
|
|
214
|
+
FunctionName: functionName,
|
|
215
|
+
ReservedConcurrentExecutions: concurrency,
|
|
216
|
+
}),
|
|
217
|
+
);
|
|
218
|
+
} catch (e) {
|
|
219
|
+
if (errorName(e) === 'InvalidParameterValueException' && /unreserved/i.test(errorMessage(e)))
|
|
220
|
+
throw new Error(
|
|
221
|
+
`a queue's concurrency (${concurrency}) needs that much of the account's Lambda concurrency reserved, ` +
|
|
222
|
+
`and the account doesn't have it to spare (${errorMessage(e)}). Raise the account's ` +
|
|
223
|
+
'"Concurrent executions" quota, or lower or remove `concurrency`.',
|
|
224
|
+
{ cause: e },
|
|
225
|
+
);
|
|
226
|
+
throw e;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
131
230
|
// ------------------------------------------------------------------ event source mappings
|
|
132
231
|
|
|
133
232
|
export interface EventSourceMappingSpec {
|
|
@@ -179,6 +278,7 @@ export async function ensureEventSourceMapping(
|
|
|
179
278
|
return res.UUID!;
|
|
180
279
|
}
|
|
181
280
|
|
|
281
|
+
/** A function's mappings, except those already being deleted (deletion takes a while, and they still list). */
|
|
182
282
|
export async function listEventSourceMappings(
|
|
183
283
|
ctx: EngineContext,
|
|
184
284
|
functionName: string,
|
|
@@ -191,7 +291,8 @@ export async function listEventSourceMappings(
|
|
|
191
291
|
);
|
|
192
292
|
if (!res) return out;
|
|
193
293
|
for (const m of res.EventSourceMappings ?? []) {
|
|
194
|
-
if (m.UUID && m.EventSourceArn
|
|
294
|
+
if (m.UUID && m.EventSourceArn && m.State !== 'Deleting')
|
|
295
|
+
out.push({ uuid: m.UUID, sourceArn: m.EventSourceArn });
|
|
195
296
|
}
|
|
196
297
|
Marker = res.NextMarker;
|
|
197
298
|
} while (Marker);
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AddPermissionCommand,
|
|
3
|
+
CreateAliasCommand,
|
|
4
|
+
CreateFunctionCommand,
|
|
5
|
+
CreateFunctionUrlConfigCommand,
|
|
6
|
+
GetAliasCommand,
|
|
7
|
+
GetFunctionConfigurationCommand,
|
|
8
|
+
GetFunctionUrlConfigCommand,
|
|
9
|
+
GetPolicyCommand,
|
|
10
|
+
DeleteFunctionCommand,
|
|
11
|
+
ListVersionsByFunctionCommand,
|
|
12
|
+
PublishVersionCommand,
|
|
13
|
+
type Runtime,
|
|
14
|
+
TagResourceCommand,
|
|
15
|
+
UpdateAliasCommand,
|
|
16
|
+
UpdateFunctionCodeCommand,
|
|
17
|
+
UpdateFunctionConfigurationCommand,
|
|
18
|
+
UpdateFunctionUrlConfigCommand,
|
|
19
|
+
} from '@aws-sdk/client-lambda';
|
|
20
|
+
import { NODE_RUNTIME } from '@ericminassian/platform-core';
|
|
21
|
+
import type { S3Location } from '../index.ts';
|
|
22
|
+
import { type EngineContext, errorMessage, errorName, ignoreNotFound, retry, waitFor } from '../util.ts';
|
|
23
|
+
import { waitReady } from './lambda.ts';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A stage's server in request mode: a regular Lambda function (arm64) that
|
|
27
|
+
* Lambda invokes once per request, through function URLs.
|
|
28
|
+
*
|
|
29
|
+
* It mirrors the Web Function's two endpoints: each deploy publishes a
|
|
30
|
+
* version, and of the function's two aliases (each with its own function
|
|
31
|
+
* URL) points the one the live route doesn't use at it. The route names that
|
|
32
|
+
* URL, so the route flip switches static files and server together at each
|
|
33
|
+
* edge, and rollback to the previous deployment is a route write.
|
|
34
|
+
*
|
|
35
|
+
* The URLs take requests from anyone (AuthType NONE): CloudFront's OAC to a
|
|
36
|
+
* function URL would make every client hash POST bodies. The router sends
|
|
37
|
+
* the stage's origin secret instead, and the SDK refuses requests without it.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
export interface RequestFunctionSpec {
|
|
41
|
+
name: string;
|
|
42
|
+
roleArn: string;
|
|
43
|
+
code: S3Location;
|
|
44
|
+
env: Record<string, string>;
|
|
45
|
+
memoryMb: number;
|
|
46
|
+
timeoutSeconds: number;
|
|
47
|
+
logGroup: string;
|
|
48
|
+
/** The deployment this version is, recorded on it. */
|
|
49
|
+
deploymentId: string;
|
|
50
|
+
description: string;
|
|
51
|
+
tags?: Record<string, string>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const isRolePropagation = (e: unknown) =>
|
|
55
|
+
errorName(e) === 'InvalidParameterValueException' && /role|assume/i.test(errorMessage(e));
|
|
56
|
+
const isUpdateInProgress = (e: unknown) => errorName(e) === 'ResourceConflictException';
|
|
57
|
+
|
|
58
|
+
/** Create or update the function from `spec`, then publish it as a version. */
|
|
59
|
+
export async function publishRequestFunction(
|
|
60
|
+
ctx: EngineContext,
|
|
61
|
+
spec: RequestFunctionSpec,
|
|
62
|
+
): Promise<{ arn: string; version: string }> {
|
|
63
|
+
const lambda = ctx.clients.lambda;
|
|
64
|
+
const existing = await ignoreNotFound(
|
|
65
|
+
lambda.send(new GetFunctionConfigurationCommand({ FunctionName: spec.name })),
|
|
66
|
+
);
|
|
67
|
+
const config = {
|
|
68
|
+
Role: spec.roleArn,
|
|
69
|
+
Runtime: NODE_RUNTIME as Runtime,
|
|
70
|
+
Handler: 'index.handler',
|
|
71
|
+
MemorySize: spec.memoryMb,
|
|
72
|
+
Timeout: spec.timeoutSeconds,
|
|
73
|
+
Description: spec.description,
|
|
74
|
+
Environment: { Variables: spec.env },
|
|
75
|
+
// JSON keeps the SDK's lines parseable like the worker's. WARN drops the runtime's own start
|
|
76
|
+
// and report records of every invocation: the SDK's `req` lines carry the same facts.
|
|
77
|
+
LoggingConfig: { LogFormat: 'JSON' as const, SystemLogLevel: 'WARN' as const, LogGroup: spec.logGroup },
|
|
78
|
+
};
|
|
79
|
+
const code = { S3Bucket: spec.code.bucket, S3Key: spec.code.key, S3ObjectVersion: spec.code.versionId };
|
|
80
|
+
|
|
81
|
+
let arn: string;
|
|
82
|
+
if (!existing) {
|
|
83
|
+
const res = await retry(
|
|
84
|
+
() =>
|
|
85
|
+
lambda.send(
|
|
86
|
+
new CreateFunctionCommand({
|
|
87
|
+
FunctionName: spec.name,
|
|
88
|
+
...config,
|
|
89
|
+
Architectures: ['arm64'],
|
|
90
|
+
Code: code,
|
|
91
|
+
Tags: spec.tags,
|
|
92
|
+
}),
|
|
93
|
+
),
|
|
94
|
+
{ when: isRolePropagation, attempts: 15, delayMs: 2_000 },
|
|
95
|
+
);
|
|
96
|
+
arn = res.FunctionArn!;
|
|
97
|
+
ctx.log('info', 'created function', `function ${spec.name}`);
|
|
98
|
+
} else {
|
|
99
|
+
arn = existing.FunctionArn!;
|
|
100
|
+
await waitReady(ctx, spec.name);
|
|
101
|
+
await retry(
|
|
102
|
+
() =>
|
|
103
|
+
lambda.send(
|
|
104
|
+
new UpdateFunctionCodeCommand({ FunctionName: spec.name, ...code, Architectures: ['arm64'] }),
|
|
105
|
+
),
|
|
106
|
+
{ when: isUpdateInProgress },
|
|
107
|
+
);
|
|
108
|
+
await waitReady(ctx, spec.name);
|
|
109
|
+
await retry(
|
|
110
|
+
() => lambda.send(new UpdateFunctionConfigurationCommand({ FunctionName: spec.name, ...config })),
|
|
111
|
+
{
|
|
112
|
+
when: (e) => isUpdateInProgress(e) || isRolePropagation(e),
|
|
113
|
+
},
|
|
114
|
+
);
|
|
115
|
+
if (spec.tags) await lambda.send(new TagResourceCommand({ Resource: arn, Tags: spec.tags }));
|
|
116
|
+
}
|
|
117
|
+
await waitReady(ctx, spec.name);
|
|
118
|
+
const published = await retry(
|
|
119
|
+
() => lambda.send(new PublishVersionCommand({ FunctionName: spec.name, Description: spec.deploymentId })),
|
|
120
|
+
{ when: isUpdateInProgress },
|
|
121
|
+
);
|
|
122
|
+
const version = published.Version!;
|
|
123
|
+
await waitFor(
|
|
124
|
+
`function ${spec.name} version ${version}`,
|
|
125
|
+
async () => (await getVersionState(ctx, spec.name, version)) === 'Active',
|
|
126
|
+
{ timeoutMs: 300_000 },
|
|
127
|
+
);
|
|
128
|
+
ctx.log('info', `published version ${version}`, `function ${spec.name}`);
|
|
129
|
+
return { arn, version };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** A version's state, or undefined when it (or the function) no longer exists. */
|
|
133
|
+
export async function getVersionState(
|
|
134
|
+
ctx: EngineContext,
|
|
135
|
+
functionName: string,
|
|
136
|
+
version: string,
|
|
137
|
+
): Promise<string | undefined> {
|
|
138
|
+
const c = await ignoreNotFound(
|
|
139
|
+
ctx.clients.lambda.send(
|
|
140
|
+
new GetFunctionConfigurationCommand({ FunctionName: functionName, Qualifier: version }),
|
|
141
|
+
),
|
|
142
|
+
);
|
|
143
|
+
if (c?.State === 'Failed')
|
|
144
|
+
throw new Error(`function ${functionName} version ${version} failed: ${c.StateReason}`);
|
|
145
|
+
return c?.State;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** `abc.lambda-url.us-east-1.on.aws`: what the route's `o` holds (the emulator serves URLs under a path). */
|
|
149
|
+
export const functionUrlDomain = (url: string) => url.replace(/^https?:\/\//, '').replace(/\/+$/, '');
|
|
150
|
+
|
|
151
|
+
export interface AliasUrl {
|
|
152
|
+
domainName: string;
|
|
153
|
+
/** Every version an alias points at afterwards (keep these when pruning). */
|
|
154
|
+
pinned: string[];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* A function URL that serves `version`, never changing the alias the live
|
|
159
|
+
* route uses (`liveDomain`): edges that haven't picked up a new route keep
|
|
160
|
+
* reaching the version they had. Reuses an alias already on the version (a
|
|
161
|
+
* rollback to the previous deployment), else repoints the other one.
|
|
162
|
+
*/
|
|
163
|
+
export async function aliasForVersion(
|
|
164
|
+
ctx: EngineContext,
|
|
165
|
+
spec: {
|
|
166
|
+
functionName: string;
|
|
167
|
+
aliasNames: readonly [string, string];
|
|
168
|
+
version: string;
|
|
169
|
+
liveDomain?: string;
|
|
170
|
+
},
|
|
171
|
+
): Promise<AliasUrl> {
|
|
172
|
+
const { functionName, version } = spec;
|
|
173
|
+
const before = await Promise.all(
|
|
174
|
+
spec.aliasNames.map(async (name) => ({
|
|
175
|
+
name,
|
|
176
|
+
version: (await getAlias(ctx, functionName, name))?.FunctionVersion,
|
|
177
|
+
url: (await getFunctionUrl(ctx, functionName, name))?.FunctionUrl,
|
|
178
|
+
})),
|
|
179
|
+
);
|
|
180
|
+
const reuse = before.find((a) => a.version === version)?.name;
|
|
181
|
+
const live = before.find((a) => a.url && functionUrlDomain(a.url) === spec.liveDomain)?.name;
|
|
182
|
+
const aliasName = reuse ?? spec.aliasNames.find((n) => n !== live)!;
|
|
183
|
+
const current = before.find((a) => a.name === aliasName);
|
|
184
|
+
if (!current?.version) {
|
|
185
|
+
await ctx.clients.lambda.send(
|
|
186
|
+
new CreateAliasCommand({ FunctionName: functionName, Name: aliasName, FunctionVersion: version }),
|
|
187
|
+
);
|
|
188
|
+
} else if (current.version !== version) {
|
|
189
|
+
await ctx.clients.lambda.send(
|
|
190
|
+
new UpdateAliasCommand({ FunctionName: functionName, Name: aliasName, FunctionVersion: version }),
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
if (!reuse) ctx.log('info', `alias ${aliasName} → version ${version}`, `function ${functionName}`);
|
|
194
|
+
const url = await ensureFunctionUrl(ctx, functionName, aliasName);
|
|
195
|
+
await ensurePublicInvoke(ctx, functionName, aliasName);
|
|
196
|
+
return {
|
|
197
|
+
domainName: functionUrlDomain(url),
|
|
198
|
+
pinned: before.flatMap((a) => (a.name === aliasName ? [version] : a.version ? [a.version] : [])),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function getAlias(ctx: EngineContext, functionName: string, name: string) {
|
|
203
|
+
return ignoreNotFound(
|
|
204
|
+
ctx.clients.lambda.send(new GetAliasCommand({ FunctionName: functionName, Name: name })),
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function getFunctionUrl(ctx: EngineContext, functionName: string, alias: string) {
|
|
209
|
+
return ignoreNotFound(
|
|
210
|
+
ctx.clients.lambda.send(
|
|
211
|
+
new GetFunctionUrlConfigCommand({ FunctionName: functionName, Qualifier: alias }),
|
|
212
|
+
),
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** The alias's URL: no IAM auth, responses streamed (a body larger than 6 MB, server-sent events). */
|
|
217
|
+
async function ensureFunctionUrl(ctx: EngineContext, functionName: string, alias: string): Promise<string> {
|
|
218
|
+
const lambda = ctx.clients.lambda;
|
|
219
|
+
const wanted = { AuthType: 'NONE' as const, InvokeMode: 'RESPONSE_STREAM' as const };
|
|
220
|
+
const existing = await getFunctionUrl(ctx, functionName, alias);
|
|
221
|
+
if (!existing) {
|
|
222
|
+
const created = await lambda.send(
|
|
223
|
+
new CreateFunctionUrlConfigCommand({ FunctionName: functionName, Qualifier: alias, ...wanted }),
|
|
224
|
+
);
|
|
225
|
+
ctx.log('info', `created function URL for ${alias}`, `function ${functionName}`);
|
|
226
|
+
return created.FunctionUrl!;
|
|
227
|
+
}
|
|
228
|
+
if (existing.AuthType !== wanted.AuthType || existing.InvokeMode !== wanted.InvokeMode) {
|
|
229
|
+
await lambda.send(
|
|
230
|
+
new UpdateFunctionUrlConfigCommand({ FunctionName: functionName, Qualifier: alias, ...wanted }),
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
return existing.FunctionUrl!;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Function URLs without IAM auth need two grants on the alias (since October
|
|
238
|
+
* 2025): invoking the URL, and invoking the function, the latter only
|
|
239
|
+
* through a URL.
|
|
240
|
+
*/
|
|
241
|
+
const PUBLIC_INVOKE = [
|
|
242
|
+
{
|
|
243
|
+
StatementId: 'FunctionUrlPublic',
|
|
244
|
+
Action: 'lambda:InvokeFunctionUrl',
|
|
245
|
+
FunctionUrlAuthType: 'NONE' as const,
|
|
246
|
+
},
|
|
247
|
+
{ StatementId: 'FunctionUrlInvoke', Action: 'lambda:InvokeFunction', InvokedViaFunctionUrl: true },
|
|
248
|
+
];
|
|
249
|
+
|
|
250
|
+
async function ensurePublicInvoke(ctx: EngineContext, functionName: string, alias: string): Promise<void> {
|
|
251
|
+
const lambda = ctx.clients.lambda;
|
|
252
|
+
const current = await ignoreNotFound(
|
|
253
|
+
lambda.send(new GetPolicyCommand({ FunctionName: functionName, Qualifier: alias })),
|
|
254
|
+
);
|
|
255
|
+
const sids = new Set(
|
|
256
|
+
current?.Policy
|
|
257
|
+
? (JSON.parse(current.Policy) as { Statement: Array<{ Sid?: string }> }).Statement.map((s) => s.Sid)
|
|
258
|
+
: [],
|
|
259
|
+
);
|
|
260
|
+
for (const grant of PUBLIC_INVOKE) {
|
|
261
|
+
if (sids.has(grant.StatementId)) continue;
|
|
262
|
+
try {
|
|
263
|
+
await lambda.send(
|
|
264
|
+
new AddPermissionCommand({ FunctionName: functionName, Qualifier: alias, Principal: '*', ...grant }),
|
|
265
|
+
);
|
|
266
|
+
} catch (e) {
|
|
267
|
+
// Already there (GetPolicy can lag an earlier add).
|
|
268
|
+
if (errorName(e) !== 'ResourceConflictException') throw e;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Delete published versions beyond the `keepNewest` most recent, never touching `keep`. */
|
|
274
|
+
export async function pruneVersions(
|
|
275
|
+
ctx: EngineContext,
|
|
276
|
+
functionName: string,
|
|
277
|
+
opts: { keepNewest: number; keep: string[] },
|
|
278
|
+
): Promise<void> {
|
|
279
|
+
const lambda = ctx.clients.lambda;
|
|
280
|
+
const versions: number[] = [];
|
|
281
|
+
let Marker: string | undefined;
|
|
282
|
+
do {
|
|
283
|
+
const res = await lambda.send(new ListVersionsByFunctionCommand({ FunctionName: functionName, Marker }));
|
|
284
|
+
for (const v of res.Versions ?? [])
|
|
285
|
+
if (v.Version && v.Version !== '$LATEST') versions.push(Number(v.Version));
|
|
286
|
+
Marker = res.NextMarker;
|
|
287
|
+
} while (Marker);
|
|
288
|
+
for (const v of versions.toSorted((a, b) => b - a).slice(opts.keepNewest)) {
|
|
289
|
+
if (opts.keep.includes(String(v))) continue;
|
|
290
|
+
await ignoreNotFound(
|
|
291
|
+
lambda.send(new DeleteFunctionCommand({ FunctionName: functionName, Qualifier: String(v) })),
|
|
292
|
+
);
|
|
293
|
+
ctx.log('info', `deleted old version ${v}`, `function ${functionName}`);
|
|
294
|
+
}
|
|
295
|
+
}
|
package/src/drivers/s3.ts
CHANGED
|
@@ -143,6 +143,14 @@ export async function publishStaticZip(
|
|
|
143
143
|
return files.length;
|
|
144
144
|
}
|
|
145
145
|
|
|
146
|
+
/** Whether any object exists under `prefix`. */
|
|
147
|
+
export async function hasObjects(ctx: EngineContext, bucket: string, prefix: string): Promise<boolean> {
|
|
148
|
+
const res = await ctx.clients.s3.send(
|
|
149
|
+
new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, MaxKeys: 1 }),
|
|
150
|
+
);
|
|
151
|
+
return (res.KeyCount ?? res.Contents?.length ?? 0) > 0;
|
|
152
|
+
}
|
|
153
|
+
|
|
146
154
|
/** Immediate child "directories" under `prefix` (ends with `/`). */
|
|
147
155
|
export async function listChildPrefixes(
|
|
148
156
|
ctx: EngineContext,
|
|
@@ -194,3 +202,41 @@ export async function deletePrefix(ctx: EngineContext, bucket: string, prefix: s
|
|
|
194
202
|
}
|
|
195
203
|
return deleted;
|
|
196
204
|
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Delete the objects under `prefix` last written before `cutoff` (an
|
|
208
|
+
* unversioned bucket). Returns how many were deleted.
|
|
209
|
+
*/
|
|
210
|
+
export async function deleteObjectsOlderThan(
|
|
211
|
+
ctx: EngineContext,
|
|
212
|
+
bucket: string,
|
|
213
|
+
prefix: string,
|
|
214
|
+
cutoff: Date,
|
|
215
|
+
): Promise<number> {
|
|
216
|
+
const s3 = ctx.clients.s3;
|
|
217
|
+
let deleted = 0;
|
|
218
|
+
let ContinuationToken: string | undefined;
|
|
219
|
+
do {
|
|
220
|
+
const res = await s3.send(
|
|
221
|
+
new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, ContinuationToken }),
|
|
222
|
+
);
|
|
223
|
+
const stale = (res.Contents ?? [])
|
|
224
|
+
.filter((o) => o.Key && o.LastModified && o.LastModified < cutoff)
|
|
225
|
+
.map((o) => ({ Key: o.Key! }));
|
|
226
|
+
// A page is at most 1,000 keys, which is what one DeleteObjects takes.
|
|
227
|
+
if (stale.length) {
|
|
228
|
+
const out = await s3.send(
|
|
229
|
+
new DeleteObjectsCommand({ Bucket: bucket, Delete: { Objects: stale, Quiet: true } }),
|
|
230
|
+
);
|
|
231
|
+
if (out.Errors?.length) {
|
|
232
|
+
const first = out.Errors[0]!;
|
|
233
|
+
throw new Error(
|
|
234
|
+
`could not delete ${out.Errors.length} of ${stale.length} files under ${prefix}: ${first.Code} ${first.Message} (${first.Key})`,
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
deleted += stale.length;
|
|
238
|
+
}
|
|
239
|
+
ContinuationToken = res.NextContinuationToken;
|
|
240
|
+
} while (ContinuationToken);
|
|
241
|
+
return deleted;
|
|
242
|
+
}
|