@elumixor/devkit 0.12.2 → 0.12.4
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/README.md +83 -0
- package/package.json +26 -2
- package/src/bin/devkit.ts +32 -1
- package/src/blob/index.ts +169 -0
- package/src/build-targets/web.ts +66 -20
- package/src/cloud/aws.ts +108 -0
- package/src/cloud/bootstrap.ts +114 -0
- package/src/cloud/cli.ts +56 -0
- package/src/cloud/commands/context.ts +42 -0
- package/src/cloud/commands/destroy.ts +43 -0
- package/src/cloud/commands/domains.ts +68 -0
- package/src/cloud/commands/env.ts +59 -0
- package/src/cloud/commands/init.ts +74 -0
- package/src/cloud/commands/logs.ts +35 -0
- package/src/cloud/commands/rollback.ts +54 -0
- package/src/cloud/commands/status.ts +50 -0
- package/src/cloud/edge/router.js +86 -0
- package/src/cloud/env.ts +93 -0
- package/src/cloud/github.ts +92 -0
- package/src/cloud/index.ts +9 -0
- package/src/cloud/log-events.ts +56 -0
- package/src/cloud/mcp.ts +150 -0
- package/src/cloud/names.ts +98 -0
- package/src/cloud/nitro-build.ts +42 -0
- package/src/cloud/overview.ts +105 -0
- package/src/cloud/project.ts +143 -0
- package/src/cloud/reconcile/acm.ts +97 -0
- package/src/cloud/reconcile/cloudflare.ts +103 -0
- package/src/cloud/reconcile/edge.ts +97 -0
- package/src/cloud/reconcile/guardrails.ts +112 -0
- package/src/cloud/reconcile/iam.ts +328 -0
- package/src/cloud/reconcile/kvs.ts +98 -0
- package/src/cloud/reconcile/lambda.ts +305 -0
- package/src/cloud/reconcile/logs.ts +24 -0
- package/src/cloud/reconcile/platform.ts +281 -0
- package/src/cloud/reconcile/s3.ts +155 -0
- package/src/cloud/reconcile/scheduler.ts +100 -0
- package/src/cloud/records.ts +129 -0
- package/src/cloud/release.ts +268 -0
- package/src/cloud/runtime-wrapper.ts +84 -0
- package/src/deploy-targets/aws.ts +26 -0
- package/src/dev/board.tsx +18 -11
- package/src/run-target.ts +2 -0
- package/src/runtime/index.ts +50 -0
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AddPermissionCommand,
|
|
3
|
+
CreateAliasCommand,
|
|
4
|
+
CreateFunctionCommand,
|
|
5
|
+
CreateFunctionUrlConfigCommand,
|
|
6
|
+
DeleteFunctionCommand,
|
|
7
|
+
GetAliasCommand,
|
|
8
|
+
GetFunctionConfigurationCommand,
|
|
9
|
+
GetFunctionUrlConfigCommand,
|
|
10
|
+
InvokeWithResponseStreamCommand,
|
|
11
|
+
ListVersionsByFunctionCommand,
|
|
12
|
+
PublishVersionCommand,
|
|
13
|
+
PutFunctionConcurrencyCommand,
|
|
14
|
+
UpdateAliasCommand,
|
|
15
|
+
UpdateFunctionCodeCommand,
|
|
16
|
+
UpdateFunctionConfigurationCommand,
|
|
17
|
+
UpdateFunctionUrlConfigCommand,
|
|
18
|
+
} from "@aws-sdk/client-lambda";
|
|
19
|
+
import { CloudError, lambda, orUndefined, retryWhile, waitFor } from "../aws.ts";
|
|
20
|
+
import { LIVE_ALIAS } from "../names.ts";
|
|
21
|
+
import type { Target } from "../project.ts";
|
|
22
|
+
|
|
23
|
+
export const RUNTIME = "nodejs24.x";
|
|
24
|
+
export const ARCHITECTURE = "arm64";
|
|
25
|
+
/** The entry the deploy writes next to Nitro's output; see `src/cloud/runtime-wrapper.ts`. */
|
|
26
|
+
export const HANDLER = "dk-handler.handler";
|
|
27
|
+
/** Caps what a runaway loop can cost, and how many database connections one stage can open. */
|
|
28
|
+
export const RESERVED_CONCURRENCY = 20;
|
|
29
|
+
/** Lambda rejects a configuration whose variables total more than this. */
|
|
30
|
+
export const ENV_LIMIT_BYTES = 4096;
|
|
31
|
+
|
|
32
|
+
export interface FunctionCode {
|
|
33
|
+
bucket: string;
|
|
34
|
+
key: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface FunctionSpec {
|
|
38
|
+
roleArn: string;
|
|
39
|
+
code: FunctionCode;
|
|
40
|
+
env: Readonly<Record<string, string>>;
|
|
41
|
+
description: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function envSize(env: Readonly<Record<string, string>>) {
|
|
45
|
+
return Object.entries(env).reduce((sum, [key, value]) => sum + Buffer.byteLength(key) + Buffer.byteLength(value), 0);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Creates or updates the function's code and config, then publishes an immutable version of it. */
|
|
49
|
+
export async function publishFunction(
|
|
50
|
+
target: Target,
|
|
51
|
+
spec: FunctionSpec,
|
|
52
|
+
): Promise<{ version: string; created: boolean }> {
|
|
53
|
+
const size = envSize(spec.env);
|
|
54
|
+
if (size > ENV_LIMIT_BYTES) {
|
|
55
|
+
const biggest = Object.entries(spec.env)
|
|
56
|
+
.sort(([, a], [, b]) => b.length - a.length)
|
|
57
|
+
.slice(0, 5)
|
|
58
|
+
.map(([key, value]) => `${key} (${value.length} chars)`)
|
|
59
|
+
.join(", ");
|
|
60
|
+
throw new CloudError(
|
|
61
|
+
`Stage env is ${size} bytes; Lambda allows ${ENV_LIMIT_BYTES}. Biggest: ${biggest}. Move large values out of env.`,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const name = target.functionName;
|
|
66
|
+
const existing = await orUndefined(
|
|
67
|
+
lambda().send(new GetFunctionConfigurationCommand({ FunctionName: name })),
|
|
68
|
+
"ResourceNotFoundException",
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
if (!existing) {
|
|
72
|
+
// A role made moments ago is not yet visible to Lambda; the create is retried until it is.
|
|
73
|
+
await retryWhile(
|
|
74
|
+
() =>
|
|
75
|
+
lambda().send(
|
|
76
|
+
new CreateFunctionCommand({
|
|
77
|
+
FunctionName: name,
|
|
78
|
+
Runtime: RUNTIME,
|
|
79
|
+
Architectures: [ARCHITECTURE],
|
|
80
|
+
Handler: HANDLER,
|
|
81
|
+
Role: spec.roleArn,
|
|
82
|
+
Code: { S3Bucket: spec.code.bucket, S3Key: spec.code.key },
|
|
83
|
+
MemorySize: target.memory,
|
|
84
|
+
Timeout: target.timeout,
|
|
85
|
+
Environment: { Variables: { ...spec.env } },
|
|
86
|
+
Description: spec.description,
|
|
87
|
+
Tags: { dk: "platform", project: target.project, stage: target.stage },
|
|
88
|
+
}),
|
|
89
|
+
),
|
|
90
|
+
["InvalidParameterValueException"],
|
|
91
|
+
);
|
|
92
|
+
await waitSettled(name);
|
|
93
|
+
} else {
|
|
94
|
+
await lambda().send(
|
|
95
|
+
new UpdateFunctionConfigurationCommand({
|
|
96
|
+
FunctionName: name,
|
|
97
|
+
Runtime: RUNTIME,
|
|
98
|
+
Handler: HANDLER,
|
|
99
|
+
Role: spec.roleArn,
|
|
100
|
+
MemorySize: target.memory,
|
|
101
|
+
Timeout: target.timeout,
|
|
102
|
+
Environment: { Variables: { ...spec.env } },
|
|
103
|
+
Description: spec.description,
|
|
104
|
+
}),
|
|
105
|
+
);
|
|
106
|
+
await waitSettled(name);
|
|
107
|
+
await lambda().send(
|
|
108
|
+
new UpdateFunctionCodeCommand({
|
|
109
|
+
FunctionName: name,
|
|
110
|
+
S3Bucket: spec.code.bucket,
|
|
111
|
+
S3Key: spec.code.key,
|
|
112
|
+
Architectures: [ARCHITECTURE],
|
|
113
|
+
}),
|
|
114
|
+
);
|
|
115
|
+
await waitSettled(name);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
await lambda().send(
|
|
119
|
+
new PutFunctionConcurrencyCommand({ FunctionName: name, ReservedConcurrentExecutions: RESERVED_CONCURRENCY }),
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
const published = await lambda().send(
|
|
123
|
+
new PublishVersionCommand({ FunctionName: name, Description: spec.description }),
|
|
124
|
+
);
|
|
125
|
+
if (!published.Version) throw new CloudError(`Lambda published no version for ${name}`);
|
|
126
|
+
return { version: published.Version, created: !existing };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Lambda applies updates asynchronously; the next call fails until the last one has settled. */
|
|
130
|
+
async function waitSettled(name: string) {
|
|
131
|
+
await waitFor(
|
|
132
|
+
`${name} to finish updating`,
|
|
133
|
+
async () => {
|
|
134
|
+
const config = await lambda().send(new GetFunctionConfigurationCommand({ FunctionName: name }));
|
|
135
|
+
if (config.State === "Failed" || config.LastUpdateStatus === "Failed")
|
|
136
|
+
throw new CloudError(
|
|
137
|
+
`${name} update failed: ${config.LastUpdateStatusReason ?? config.StateReason ?? "no reason given"}`,
|
|
138
|
+
);
|
|
139
|
+
return config.State === "Active" && config.LastUpdateStatus === "Successful" ? true : undefined;
|
|
140
|
+
},
|
|
141
|
+
{ everyMs: 1500, timeoutMs: 5 * 60 * 1000 },
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Points `live` at a version — the moment a deploy or a rollback takes effect for the API. */
|
|
146
|
+
export async function pointLiveAlias(functionName: string, version: string) {
|
|
147
|
+
const alias = await orUndefined(
|
|
148
|
+
lambda().send(new GetAliasCommand({ FunctionName: functionName, Name: LIVE_ALIAS })),
|
|
149
|
+
"ResourceNotFoundException",
|
|
150
|
+
);
|
|
151
|
+
if (!alias) {
|
|
152
|
+
const created = await lambda().send(
|
|
153
|
+
new CreateAliasCommand({ FunctionName: functionName, Name: LIVE_ALIAS, FunctionVersion: version }),
|
|
154
|
+
);
|
|
155
|
+
return { arn: created.AliasArn as string, created: true };
|
|
156
|
+
}
|
|
157
|
+
if (alias.FunctionVersion !== version)
|
|
158
|
+
await lambda().send(
|
|
159
|
+
new UpdateAliasCommand({ FunctionName: functionName, Name: LIVE_ALIAS, FunctionVersion: version }),
|
|
160
|
+
);
|
|
161
|
+
return { arn: alias.AliasArn as string, created: false };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function liveVersion(functionName: string) {
|
|
165
|
+
const alias = await orUndefined(
|
|
166
|
+
lambda().send(new GetAliasCommand({ FunctionName: functionName, Name: LIVE_ALIAS })),
|
|
167
|
+
"ResourceNotFoundException",
|
|
168
|
+
);
|
|
169
|
+
return alias?.FunctionVersion;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The Function URL on the `live` alias: open to the internet (auth NONE) because CloudFront can't
|
|
174
|
+
* sign browser POST bodies, and closed by the edge secret the runtime wrapper checks instead.
|
|
175
|
+
*/
|
|
176
|
+
export async function ensureFunctionUrl(functionName: string): Promise<string> {
|
|
177
|
+
const existing = await orUndefined(
|
|
178
|
+
lambda().send(new GetFunctionUrlConfigCommand({ FunctionName: functionName, Qualifier: LIVE_ALIAS })),
|
|
179
|
+
"ResourceNotFoundException",
|
|
180
|
+
);
|
|
181
|
+
let url = existing?.FunctionUrl;
|
|
182
|
+
if (!existing) {
|
|
183
|
+
const created = await lambda().send(
|
|
184
|
+
new CreateFunctionUrlConfigCommand({
|
|
185
|
+
FunctionName: functionName,
|
|
186
|
+
Qualifier: LIVE_ALIAS,
|
|
187
|
+
AuthType: "NONE",
|
|
188
|
+
InvokeMode: "RESPONSE_STREAM",
|
|
189
|
+
}),
|
|
190
|
+
);
|
|
191
|
+
url = created.FunctionUrl;
|
|
192
|
+
} else if (existing.InvokeMode !== "RESPONSE_STREAM" || existing.AuthType !== "NONE") {
|
|
193
|
+
await lambda().send(
|
|
194
|
+
new UpdateFunctionUrlConfigCommand({
|
|
195
|
+
FunctionName: functionName,
|
|
196
|
+
Qualifier: LIVE_ALIAS,
|
|
197
|
+
AuthType: "NONE",
|
|
198
|
+
InvokeMode: "RESPONSE_STREAM",
|
|
199
|
+
}),
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
if (!url) throw new CloudError(`Lambda returned no URL for ${functionName}`);
|
|
203
|
+
|
|
204
|
+
// Both grants are needed: the URL permission, and a plain invoke permission limited to calls
|
|
205
|
+
// that arrive through the URL — without the second, every request is a 403.
|
|
206
|
+
await orUndefined(
|
|
207
|
+
lambda().send(
|
|
208
|
+
new AddPermissionCommand({
|
|
209
|
+
FunctionName: functionName,
|
|
210
|
+
Qualifier: LIVE_ALIAS,
|
|
211
|
+
StatementId: "dk-url",
|
|
212
|
+
Action: "lambda:InvokeFunctionUrl",
|
|
213
|
+
Principal: "*",
|
|
214
|
+
FunctionUrlAuthType: "NONE",
|
|
215
|
+
}),
|
|
216
|
+
),
|
|
217
|
+
"ResourceConflictException",
|
|
218
|
+
);
|
|
219
|
+
await orUndefined(
|
|
220
|
+
lambda().send(
|
|
221
|
+
new AddPermissionCommand({
|
|
222
|
+
FunctionName: functionName,
|
|
223
|
+
Qualifier: LIVE_ALIAS,
|
|
224
|
+
StatementId: "dk-url-invoke",
|
|
225
|
+
Action: "lambda:InvokeFunction",
|
|
226
|
+
Principal: "*",
|
|
227
|
+
InvokedViaFunctionUrl: true,
|
|
228
|
+
}),
|
|
229
|
+
),
|
|
230
|
+
"ResourceConflictException",
|
|
231
|
+
);
|
|
232
|
+
return url;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The hostname part of a Function URL — what the router points the origin at. */
|
|
236
|
+
export const urlHost = (url: string) => new URL(url).host;
|
|
237
|
+
|
|
238
|
+
export interface HttpResult {
|
|
239
|
+
status: number;
|
|
240
|
+
headers: Record<string, string>;
|
|
241
|
+
body: string;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Invokes one version with a Function-URL-shaped event, as the health check does before a deploy
|
|
246
|
+
* goes live. The streamed payload begins with the JSON prelude the wrapper writes, then 8 NULs.
|
|
247
|
+
*/
|
|
248
|
+
export async function invokeHttp(functionName: string, qualifier: string, event: unknown): Promise<HttpResult> {
|
|
249
|
+
const result = await lambda().send(
|
|
250
|
+
new InvokeWithResponseStreamCommand({
|
|
251
|
+
FunctionName: functionName,
|
|
252
|
+
Qualifier: qualifier,
|
|
253
|
+
Payload: JSON.stringify(event),
|
|
254
|
+
}),
|
|
255
|
+
);
|
|
256
|
+
const chunks: Uint8Array[] = [];
|
|
257
|
+
let failure: string | undefined;
|
|
258
|
+
for await (const item of result.EventStream ?? []) {
|
|
259
|
+
if (item.PayloadChunk?.Payload) chunks.push(item.PayloadChunk.Payload);
|
|
260
|
+
if (item.InvokeComplete?.ErrorCode)
|
|
261
|
+
failure = `${item.InvokeComplete.ErrorCode}: ${item.InvokeComplete.ErrorDetails ?? ""}`;
|
|
262
|
+
}
|
|
263
|
+
if (failure) throw new CloudError(`Invocation failed — ${failure}`);
|
|
264
|
+
const raw = Buffer.concat(chunks);
|
|
265
|
+
const separator = Buffer.alloc(8);
|
|
266
|
+
const at = raw.indexOf(separator);
|
|
267
|
+
if (at < 0) return { status: 200, headers: {}, body: raw.toString("utf8") };
|
|
268
|
+
const prelude = JSON.parse(raw.subarray(0, at).toString("utf8")) as {
|
|
269
|
+
statusCode?: number;
|
|
270
|
+
headers?: Record<string, string>;
|
|
271
|
+
};
|
|
272
|
+
return {
|
|
273
|
+
status: prelude.statusCode ?? 200,
|
|
274
|
+
headers: prelude.headers ?? {},
|
|
275
|
+
body: raw.subarray(at + separator.length).toString("utf8"),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Numbered versions newest first, for pruning. */
|
|
280
|
+
export async function listVersions(functionName: string) {
|
|
281
|
+
const versions: string[] = [];
|
|
282
|
+
let Marker: string | undefined;
|
|
283
|
+
do {
|
|
284
|
+
const page = await lambda().send(new ListVersionsByFunctionCommand({ FunctionName: functionName, Marker }));
|
|
285
|
+
for (const version of page.Versions ?? [])
|
|
286
|
+
if (version.Version && version.Version !== "$LATEST") versions.push(version.Version);
|
|
287
|
+
Marker = page.NextMarker;
|
|
288
|
+
} while (Marker);
|
|
289
|
+
return versions.sort((a, b) => Number(b) - Number(a));
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export async function deleteVersion(functionName: string, version: string) {
|
|
293
|
+
await orUndefined(
|
|
294
|
+
lambda().send(new DeleteFunctionCommand({ FunctionName: functionName, Qualifier: version })),
|
|
295
|
+
"ResourceNotFoundException",
|
|
296
|
+
"ResourceConflictException",
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export async function deleteFunction(functionName: string) {
|
|
301
|
+
await orUndefined(
|
|
302
|
+
lambda().send(new DeleteFunctionCommand({ FunctionName: functionName })),
|
|
303
|
+
"ResourceNotFoundException",
|
|
304
|
+
);
|
|
305
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CreateLogGroupCommand,
|
|
3
|
+
DeleteLogGroupCommand,
|
|
4
|
+
DescribeLogGroupsCommand,
|
|
5
|
+
PutRetentionPolicyCommand,
|
|
6
|
+
} from "@aws-sdk/client-cloudwatch-logs";
|
|
7
|
+
import { logs, orUndefined } from "../aws.ts";
|
|
8
|
+
|
|
9
|
+
/** Two weeks is long enough to debug last week's incident and short enough to stay inside the free 5 GB. */
|
|
10
|
+
export const LOG_RETENTION_DAYS = 14;
|
|
11
|
+
|
|
12
|
+
/** Makes the log group ahead of the function, so the retention is set before the first line lands. */
|
|
13
|
+
export async function ensureLogGroup(name: string) {
|
|
14
|
+
const found = await logs().send(new DescribeLogGroupsCommand({ logGroupNamePrefix: name }));
|
|
15
|
+
const existing = found.logGroups?.find((group) => group.logGroupName === name);
|
|
16
|
+
if (!existing) await logs().send(new CreateLogGroupCommand({ logGroupName: name, tags: { dk: "platform" } }));
|
|
17
|
+
if (existing?.retentionInDays !== LOG_RETENTION_DAYS)
|
|
18
|
+
await logs().send(new PutRetentionPolicyCommand({ logGroupName: name, retentionInDays: LOG_RETENTION_DAYS }));
|
|
19
|
+
return { created: !existing };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function deleteLogGroup(name: string) {
|
|
23
|
+
await orUndefined(logs().send(new DeleteLogGroupCommand({ logGroupName: name })), "ResourceNotFoundException");
|
|
24
|
+
}
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CreateCachePolicyCommand,
|
|
3
|
+
CreateDistributionWithTagsCommand,
|
|
4
|
+
CreateFunctionCommand,
|
|
5
|
+
CreateKeyValueStoreCommand,
|
|
6
|
+
CreateOriginAccessControlCommand,
|
|
7
|
+
DescribeFunctionCommand,
|
|
8
|
+
DescribeKeyValueStoreCommand,
|
|
9
|
+
type DistributionConfig,
|
|
10
|
+
ListCachePoliciesCommand,
|
|
11
|
+
ListOriginAccessControlsCommand,
|
|
12
|
+
PublishFunctionCommand,
|
|
13
|
+
UpdateFunctionCommand,
|
|
14
|
+
} from "@aws-sdk/client-cloudfront";
|
|
15
|
+
import {
|
|
16
|
+
CreateBucketCommand,
|
|
17
|
+
HeadBucketCommand,
|
|
18
|
+
PutBucketLifecycleConfigurationCommand,
|
|
19
|
+
PutBucketPolicyCommand,
|
|
20
|
+
PutPublicAccessBlockCommand,
|
|
21
|
+
} from "@aws-sdk/client-s3";
|
|
22
|
+
import { CloudError, cloudfront, log, orUndefined, platformTags, s3, waitFor } from "../aws.ts";
|
|
23
|
+
import { ORIGINS, PLATFORM_ALIASES, PROJECT_HEADER, platform, REGION } from "../names.ts";
|
|
24
|
+
import { DISTRIBUTION_COMMENT, type Distribution } from "./edge.ts";
|
|
25
|
+
|
|
26
|
+
/** A private bucket in the home region; nothing in it is reachable except through CloudFront or the SDK. */
|
|
27
|
+
export async function ensureBucket(name: string) {
|
|
28
|
+
const exists = await orUndefined(s3().send(new HeadBucketCommand({ Bucket: name })), "NotFound", "NoSuchBucket");
|
|
29
|
+
if (!exists) {
|
|
30
|
+
await s3().send(
|
|
31
|
+
new CreateBucketCommand({ Bucket: name, CreateBucketConfiguration: { LocationConstraint: REGION } }),
|
|
32
|
+
);
|
|
33
|
+
log(` created bucket ${name}`);
|
|
34
|
+
}
|
|
35
|
+
await s3().send(
|
|
36
|
+
new PutPublicAccessBlockCommand({
|
|
37
|
+
Bucket: name,
|
|
38
|
+
PublicAccessBlockConfiguration: {
|
|
39
|
+
BlockPublicAcls: true,
|
|
40
|
+
IgnorePublicAcls: true,
|
|
41
|
+
BlockPublicPolicy: true,
|
|
42
|
+
RestrictPublicBuckets: true,
|
|
43
|
+
},
|
|
44
|
+
}),
|
|
45
|
+
);
|
|
46
|
+
await s3().send(
|
|
47
|
+
new PutBucketLifecycleConfigurationCommand({
|
|
48
|
+
Bucket: name,
|
|
49
|
+
LifecycleConfiguration: {
|
|
50
|
+
Rules: [
|
|
51
|
+
{
|
|
52
|
+
ID: "abort-incomplete",
|
|
53
|
+
Status: "Enabled",
|
|
54
|
+
Filter: {},
|
|
55
|
+
AbortIncompleteMultipartUpload: { DaysAfterInitiation: 2 },
|
|
56
|
+
},
|
|
57
|
+
],
|
|
58
|
+
},
|
|
59
|
+
}),
|
|
60
|
+
);
|
|
61
|
+
return { created: !exists };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Lets the one distribution read a bucket: everything in the sites bucket, only `public/` blobs. */
|
|
65
|
+
export async function allowDistribution(bucket: string, distributionArn: string, objectPattern: string) {
|
|
66
|
+
await s3().send(
|
|
67
|
+
new PutBucketPolicyCommand({
|
|
68
|
+
Bucket: bucket,
|
|
69
|
+
Policy: JSON.stringify({
|
|
70
|
+
Version: "2012-10-17",
|
|
71
|
+
Statement: [
|
|
72
|
+
{
|
|
73
|
+
Sid: "cloudfront-read",
|
|
74
|
+
Effect: "Allow",
|
|
75
|
+
Principal: { Service: "cloudfront.amazonaws.com" },
|
|
76
|
+
Action: "s3:GetObject",
|
|
77
|
+
Resource: `arn:aws:s3:::${bucket}/${objectPattern}`,
|
|
78
|
+
Condition: { StringEquals: { "AWS:SourceArn": distributionArn } },
|
|
79
|
+
},
|
|
80
|
+
// With list permission a missing file is a 404 rather than a 403, which is what a browser expects.
|
|
81
|
+
{
|
|
82
|
+
Sid: "cloudfront-list",
|
|
83
|
+
Effect: "Allow",
|
|
84
|
+
Principal: { Service: "cloudfront.amazonaws.com" },
|
|
85
|
+
Action: "s3:ListBucket",
|
|
86
|
+
Resource: `arn:aws:s3:::${bucket}`,
|
|
87
|
+
Condition: { StringEquals: { "AWS:SourceArn": distributionArn } },
|
|
88
|
+
},
|
|
89
|
+
],
|
|
90
|
+
}),
|
|
91
|
+
}),
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function ensureOriginAccessControl() {
|
|
96
|
+
const list = await cloudfront().send(new ListOriginAccessControlsCommand({}));
|
|
97
|
+
const existing = list.OriginAccessControlList?.Items?.find((item) => item.Name === platform.originAccessControl);
|
|
98
|
+
if (existing?.Id) return existing.Id;
|
|
99
|
+
const created = await cloudfront().send(
|
|
100
|
+
new CreateOriginAccessControlCommand({
|
|
101
|
+
OriginAccessControlConfig: {
|
|
102
|
+
Name: platform.originAccessControl,
|
|
103
|
+
OriginAccessControlOriginType: "s3",
|
|
104
|
+
SigningBehavior: "always",
|
|
105
|
+
SigningProtocol: "sigv4",
|
|
106
|
+
Description: "Devkit Cloud: CloudFront reads the sites and blobs buckets",
|
|
107
|
+
},
|
|
108
|
+
}),
|
|
109
|
+
);
|
|
110
|
+
if (!created.OriginAccessControl?.Id) throw new CloudError("CloudFront returned no OAC id");
|
|
111
|
+
log(" created origin access control");
|
|
112
|
+
return created.OriginAccessControl.Id;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* TTLs of zero mean the origin's `Cache-Control` decides: fingerprinted assets say a year, HTML
|
|
117
|
+
* says revalidate, the API says nothing and is never cached. The project header keeps two
|
|
118
|
+
* projects' identical paths apart in the cache.
|
|
119
|
+
*/
|
|
120
|
+
export async function ensureCachePolicy() {
|
|
121
|
+
const list = await cloudfront().send(new ListCachePoliciesCommand({ Type: "custom" }));
|
|
122
|
+
const existing = list.CachePolicyList?.Items?.find(
|
|
123
|
+
(item) => item.CachePolicy?.CachePolicyConfig?.Name === platform.cachePolicy,
|
|
124
|
+
);
|
|
125
|
+
if (existing?.CachePolicy?.Id) return existing.CachePolicy.Id;
|
|
126
|
+
const created = await cloudfront().send(
|
|
127
|
+
new CreateCachePolicyCommand({
|
|
128
|
+
CachePolicyConfig: {
|
|
129
|
+
Name: platform.cachePolicy,
|
|
130
|
+
Comment: "Devkit Cloud: origin headers decide, keyed by project",
|
|
131
|
+
MinTTL: 0,
|
|
132
|
+
DefaultTTL: 0,
|
|
133
|
+
MaxTTL: 31536000,
|
|
134
|
+
ParametersInCacheKeyAndForwardedToOrigin: {
|
|
135
|
+
EnableAcceptEncodingGzip: true,
|
|
136
|
+
EnableAcceptEncodingBrotli: true,
|
|
137
|
+
HeadersConfig: { HeaderBehavior: "whitelist", Headers: { Quantity: 1, Items: [PROJECT_HEADER] } },
|
|
138
|
+
CookiesConfig: { CookieBehavior: "none" },
|
|
139
|
+
QueryStringsConfig: { QueryStringBehavior: "all" },
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
}),
|
|
143
|
+
);
|
|
144
|
+
if (!created.CachePolicy?.Id) throw new CloudError("CloudFront returned no cache policy id");
|
|
145
|
+
log(" created cache policy");
|
|
146
|
+
return created.CachePolicy.Id;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export async function ensureKeyValueStore() {
|
|
150
|
+
const existing = await orUndefined(
|
|
151
|
+
cloudfront().send(new DescribeKeyValueStoreCommand({ Name: platform.kvs })),
|
|
152
|
+
"EntityNotFound",
|
|
153
|
+
);
|
|
154
|
+
if (!existing) {
|
|
155
|
+
await cloudfront().send(
|
|
156
|
+
new CreateKeyValueStoreCommand({ Name: platform.kvs, Comment: "Devkit Cloud route records" }),
|
|
157
|
+
);
|
|
158
|
+
log(" created key value store (takes a minute)");
|
|
159
|
+
}
|
|
160
|
+
return waitFor(
|
|
161
|
+
"key value store",
|
|
162
|
+
async () => {
|
|
163
|
+
const described = await cloudfront().send(new DescribeKeyValueStoreCommand({ Name: platform.kvs }));
|
|
164
|
+
return described.KeyValueStore?.Status === "READY" ? (described.KeyValueStore.ARN as string) : undefined;
|
|
165
|
+
},
|
|
166
|
+
{ everyMs: 5000 },
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Creates or updates the router from `edge/router.js`, then publishes it to LIVE. */
|
|
171
|
+
export async function ensureRouterFunction(kvsArn: string) {
|
|
172
|
+
const code = new TextEncoder().encode(await Bun.file(new URL("../edge/router.js", import.meta.url)).text());
|
|
173
|
+
const config = {
|
|
174
|
+
Comment: "Devkit Cloud router",
|
|
175
|
+
Runtime: "cloudfront-js-2.0" as const,
|
|
176
|
+
KeyValueStoreAssociations: { Quantity: 1, Items: [{ KeyValueStoreARN: kvsArn }] },
|
|
177
|
+
};
|
|
178
|
+
const existing = await orUndefined(
|
|
179
|
+
cloudfront().send(new DescribeFunctionCommand({ Name: platform.routerFunction, Stage: "DEVELOPMENT" })),
|
|
180
|
+
"NoSuchFunctionExists",
|
|
181
|
+
);
|
|
182
|
+
let etag: string | undefined;
|
|
183
|
+
if (!existing) {
|
|
184
|
+
const created = await cloudfront().send(
|
|
185
|
+
new CreateFunctionCommand({ Name: platform.routerFunction, FunctionConfig: config, FunctionCode: code }),
|
|
186
|
+
);
|
|
187
|
+
etag = created.ETag;
|
|
188
|
+
log(" created router function");
|
|
189
|
+
} else {
|
|
190
|
+
const updated = await cloudfront().send(
|
|
191
|
+
new UpdateFunctionCommand({
|
|
192
|
+
Name: platform.routerFunction,
|
|
193
|
+
IfMatch: existing.ETag,
|
|
194
|
+
FunctionConfig: config,
|
|
195
|
+
FunctionCode: code,
|
|
196
|
+
}),
|
|
197
|
+
);
|
|
198
|
+
etag = updated.ETag;
|
|
199
|
+
log(" updated router function");
|
|
200
|
+
}
|
|
201
|
+
const published = await cloudfront().send(
|
|
202
|
+
new PublishFunctionCommand({ Name: platform.routerFunction, IfMatch: etag }),
|
|
203
|
+
);
|
|
204
|
+
const arn = published.FunctionSummary?.FunctionMetadata?.FunctionARN;
|
|
205
|
+
if (!arn) throw new CloudError("CloudFront published the router without an ARN");
|
|
206
|
+
return arn;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export interface DistributionInputs {
|
|
210
|
+
sitesBucket: string;
|
|
211
|
+
blobsBucket: string;
|
|
212
|
+
oacId: string;
|
|
213
|
+
cachePolicyId: string;
|
|
214
|
+
routerArn: string;
|
|
215
|
+
certificateArn: string;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function distributionConfig(inputs: DistributionInputs): DistributionConfig {
|
|
219
|
+
const s3Origin = (id: string, bucket: string) => ({
|
|
220
|
+
Id: id,
|
|
221
|
+
DomainName: `${bucket}.s3.${REGION}.amazonaws.com`,
|
|
222
|
+
OriginAccessControlId: inputs.oacId,
|
|
223
|
+
S3OriginConfig: { OriginAccessIdentity: "" },
|
|
224
|
+
OriginPath: "",
|
|
225
|
+
CustomHeaders: { Quantity: 0 },
|
|
226
|
+
ConnectionAttempts: 3,
|
|
227
|
+
ConnectionTimeout: 10,
|
|
228
|
+
});
|
|
229
|
+
return {
|
|
230
|
+
CallerReference: DISTRIBUTION_COMMENT,
|
|
231
|
+
Comment: DISTRIBUTION_COMMENT,
|
|
232
|
+
Enabled: true,
|
|
233
|
+
HttpVersion: "http2and3",
|
|
234
|
+
IsIPV6Enabled: true,
|
|
235
|
+
PriceClass: "PriceClass_100",
|
|
236
|
+
Aliases: { Quantity: PLATFORM_ALIASES.length, Items: [...PLATFORM_ALIASES] },
|
|
237
|
+
ViewerCertificate: {
|
|
238
|
+
ACMCertificateArn: inputs.certificateArn,
|
|
239
|
+
SSLSupportMethod: "sni-only",
|
|
240
|
+
MinimumProtocolVersion: "TLSv1.2_2021",
|
|
241
|
+
CloudFrontDefaultCertificate: false,
|
|
242
|
+
},
|
|
243
|
+
Origins: {
|
|
244
|
+
Quantity: 2,
|
|
245
|
+
Items: [s3Origin(ORIGINS.sites, inputs.sitesBucket), s3Origin(ORIGINS.blobs, inputs.blobsBucket)],
|
|
246
|
+
},
|
|
247
|
+
DefaultCacheBehavior: {
|
|
248
|
+
TargetOriginId: ORIGINS.sites,
|
|
249
|
+
ViewerProtocolPolicy: "redirect-to-https",
|
|
250
|
+
AllowedMethods: {
|
|
251
|
+
Quantity: 7,
|
|
252
|
+
Items: ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"],
|
|
253
|
+
CachedMethods: { Quantity: 2, Items: ["GET", "HEAD"] },
|
|
254
|
+
},
|
|
255
|
+
Compress: true,
|
|
256
|
+
CachePolicyId: inputs.cachePolicyId,
|
|
257
|
+
OriginRequestPolicyId: platform.originRequestPolicyId,
|
|
258
|
+
FunctionAssociations: { Quantity: 1, Items: [{ EventType: "viewer-request", FunctionARN: inputs.routerArn }] },
|
|
259
|
+
},
|
|
260
|
+
DefaultRootObject: "",
|
|
261
|
+
Restrictions: { GeoRestriction: { RestrictionType: "none", Quantity: 0 } },
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export async function createDistribution(inputs: DistributionInputs): Promise<Distribution> {
|
|
266
|
+
const created = await cloudfront().send(
|
|
267
|
+
new CreateDistributionWithTagsCommand({
|
|
268
|
+
DistributionConfigWithTags: { DistributionConfig: distributionConfig(inputs), Tags: { Items: platformTags() } },
|
|
269
|
+
}),
|
|
270
|
+
);
|
|
271
|
+
const distribution = created.Distribution;
|
|
272
|
+
if (!distribution?.Id || !distribution.ARN || !distribution.DomainName)
|
|
273
|
+
throw new CloudError("CloudFront created a distribution without an id");
|
|
274
|
+
log(` created distribution ${distribution.Id} (${distribution.DomainName})`);
|
|
275
|
+
return {
|
|
276
|
+
id: distribution.Id,
|
|
277
|
+
arn: distribution.ARN,
|
|
278
|
+
domainName: distribution.DomainName,
|
|
279
|
+
aliases: distribution.DistributionConfig?.Aliases?.Items ?? [],
|
|
280
|
+
};
|
|
281
|
+
}
|