@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
|
@@ -27,10 +27,16 @@ import {
|
|
|
27
27
|
} from '../util.ts';
|
|
28
28
|
|
|
29
29
|
/**
|
|
30
|
-
* Lambda Web Functions (launched 2026-10)
|
|
31
|
-
* revisions; an endpoint routes traffic to up to
|
|
32
|
-
*
|
|
33
|
-
*
|
|
30
|
+
* Lambda Web Functions (launched 2026-10), a stage's server in instance mode:
|
|
31
|
+
* a function holds immutable revisions; an endpoint routes traffic to up to
|
|
32
|
+
* two revisions by weight.
|
|
33
|
+
*
|
|
34
|
+
* The engine gives each stage two endpoints and pins each to one revision
|
|
35
|
+
* (100%). A route record names an endpoint, so the route flip switches
|
|
36
|
+
* static files and server together at each edge: edges still on the old
|
|
37
|
+
* route keep reaching the old revision through the other endpoint until
|
|
38
|
+
* they pick up the new one. That also makes rollback to the previous
|
|
39
|
+
* deployment a route write only.
|
|
34
40
|
*/
|
|
35
41
|
|
|
36
42
|
export interface RevisionSpec {
|
|
@@ -59,7 +65,10 @@ function revisionConfig(spec: RevisionSpec) {
|
|
|
59
65
|
timeoutSeconds: spec.timeoutSeconds,
|
|
60
66
|
maxConcurrencyPerEnvironment: spec.maxConcurrency,
|
|
61
67
|
environmentVariables: spec.env,
|
|
62
|
-
|
|
68
|
+
// WARN drops the runtime's per-minute `platform.invokeSummary` and its init, invoke and
|
|
69
|
+
// spin-down records: the SDK's own `env` and `req` lines carry the same facts, and nothing
|
|
70
|
+
// reads the runtime's beyond showing them in the logs.
|
|
71
|
+
telemetryConfig: { loggingConfig: { logGroup: spec.logGroup, systemLogLevel: 'WARN' as const } },
|
|
63
72
|
},
|
|
64
73
|
};
|
|
65
74
|
}
|
|
@@ -79,12 +88,13 @@ export async function ensureWebFunction(
|
|
|
79
88
|
spec: {
|
|
80
89
|
name: string;
|
|
81
90
|
tags?: Record<string, string>;
|
|
82
|
-
initial: { revision: RevisionSpec; endpointName: string };
|
|
91
|
+
initial: { revision: RevisionSpec; endpointName: string; maxEnvironments?: number };
|
|
83
92
|
},
|
|
84
93
|
): Promise<{ arn: string; initialRevisionId?: string }> {
|
|
85
94
|
const lw = ctx.clients.lambdaWeb;
|
|
86
95
|
const existing = await ignoreNotFound(lw.send(new GetWebFunctionCommand({ functionName: spec.name })));
|
|
87
96
|
if (existing?.functionArn) return { arn: existing.functionArn };
|
|
97
|
+
const { maxEnvironments } = spec.initial;
|
|
88
98
|
const res = await retry(
|
|
89
99
|
() =>
|
|
90
100
|
lw.send(
|
|
@@ -98,6 +108,7 @@ export async function ensureWebFunction(
|
|
|
98
108
|
authType: 'IamAuth',
|
|
99
109
|
// Traffic moves only when the engine sets weights, so rollback stays explicit.
|
|
100
110
|
autoDeploymentMode: 'Disabled',
|
|
111
|
+
...(maxEnvironments ? { scalingConfig: { maxEnvironments } } : {}),
|
|
101
112
|
},
|
|
102
113
|
}),
|
|
103
114
|
),
|
|
@@ -122,6 +133,18 @@ export async function createRevision(ctx: EngineContext, spec: RevisionSpec): Pr
|
|
|
122
133
|
return res.revisionId!;
|
|
123
134
|
}
|
|
124
135
|
|
|
136
|
+
/** A revision's state, or undefined if it (or its function) no longer exists. */
|
|
137
|
+
export async function getRevisionState(
|
|
138
|
+
ctx: EngineContext,
|
|
139
|
+
functionName: string,
|
|
140
|
+
revisionId: string,
|
|
141
|
+
): Promise<string | undefined> {
|
|
142
|
+
const r = await ignoreNotFound(
|
|
143
|
+
ctx.clients.lambdaWeb.send(new GetWebFunctionRevisionCommand({ functionName, revisionId })),
|
|
144
|
+
);
|
|
145
|
+
return r?.state;
|
|
146
|
+
}
|
|
147
|
+
|
|
125
148
|
async function waitRevisionActive(
|
|
126
149
|
ctx: EngineContext,
|
|
127
150
|
functionName: string,
|
|
@@ -151,19 +174,24 @@ export interface EndpointState {
|
|
|
151
174
|
revisionIds: string[];
|
|
152
175
|
}
|
|
153
176
|
|
|
154
|
-
/**
|
|
177
|
+
/**
|
|
178
|
+
* Ensure the endpoint exists and routes 100% to `revisionId`, with at most
|
|
179
|
+
* `maxEnvironments` environments when given (left as it is otherwise).
|
|
180
|
+
*/
|
|
155
181
|
export async function ensureEndpoint(
|
|
156
182
|
ctx: EngineContext,
|
|
157
|
-
spec: { functionName: string; endpointName: string; revisionId: string },
|
|
183
|
+
spec: { functionName: string; endpointName: string; revisionId: string; maxEnvironments?: number },
|
|
158
184
|
): Promise<EndpointState> {
|
|
159
185
|
const lw = ctx.clients.lambdaWeb;
|
|
160
186
|
const weights = [{ revisionId: spec.revisionId, weight: 100 }];
|
|
187
|
+
const scaling = spec.maxEnvironments ? { scalingConfig: { maxEnvironments: spec.maxEnvironments } } : {};
|
|
161
188
|
// Endpoints only accept updates while Active (a new one starts Pending).
|
|
162
189
|
const existing = await waitEndpointSettled(ctx, spec.functionName, spec.endpointName);
|
|
163
190
|
const routed =
|
|
164
191
|
existing?.revisionWeights?.length === 1 &&
|
|
165
192
|
existing.revisionWeights[0]?.revisionId === spec.revisionId &&
|
|
166
193
|
existing.revisionWeights[0]?.weight === 100;
|
|
194
|
+
const scaled = !spec.maxEnvironments || existing?.scalingConfig?.maxEnvironments === spec.maxEnvironments;
|
|
167
195
|
if (!existing) {
|
|
168
196
|
await lw.send(
|
|
169
197
|
new CreateWebFunctionEndpointCommand({
|
|
@@ -173,6 +201,7 @@ export async function ensureEndpoint(
|
|
|
173
201
|
authType: 'IamAuth',
|
|
174
202
|
autoDeploymentMode: 'Disabled',
|
|
175
203
|
revisionWeights: weights,
|
|
204
|
+
...scaling,
|
|
176
205
|
}),
|
|
177
206
|
);
|
|
178
207
|
ctx.log(
|
|
@@ -180,12 +209,13 @@ export async function ensureEndpoint(
|
|
|
180
209
|
'created web function endpoint',
|
|
181
210
|
`web-function ${spec.functionName}/${spec.endpointName}`,
|
|
182
211
|
);
|
|
183
|
-
} else if (!routed) {
|
|
212
|
+
} else if (!routed || !scaled) {
|
|
184
213
|
await lw.send(
|
|
185
214
|
new UpdateWebFunctionEndpointCommand({
|
|
186
215
|
functionName: spec.functionName,
|
|
187
216
|
endpointName: spec.endpointName,
|
|
188
217
|
revisionWeights: weights,
|
|
218
|
+
...scaling,
|
|
189
219
|
}),
|
|
190
220
|
);
|
|
191
221
|
}
|
|
@@ -232,31 +262,92 @@ export async function getEndpoint(ctx: EngineContext, functionName: string, endp
|
|
|
232
262
|
);
|
|
233
263
|
}
|
|
234
264
|
|
|
235
|
-
|
|
236
|
-
|
|
265
|
+
const pinnedTo = (
|
|
266
|
+
e: { revisionWeights?: Array<{ revisionId?: string; weight?: number }> },
|
|
267
|
+
revisionId: string,
|
|
268
|
+
) =>
|
|
269
|
+
e.revisionWeights?.length === 1 &&
|
|
270
|
+
e.revisionWeights[0]?.revisionId === revisionId &&
|
|
271
|
+
e.revisionWeights[0]?.weight === 100;
|
|
272
|
+
|
|
273
|
+
export interface RevisionEndpoint {
|
|
274
|
+
domainName: string;
|
|
275
|
+
/** Every revision an endpoint routes to afterwards (keep these when pruning). */
|
|
276
|
+
pinned: string[];
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* An endpoint that routes 100% to `revisionId`, never changing the one the
|
|
281
|
+
* live route uses (`liveDomain`): edges that haven't picked up a new route
|
|
282
|
+
* keep reaching the revision they had. Reuses an endpoint already pinned to
|
|
283
|
+
* the revision (a function's first revision, or a rollback to the previous
|
|
284
|
+
* deployment), else repoints the other endpoint. Then lets the router invoke
|
|
285
|
+
* every endpoint.
|
|
286
|
+
*/
|
|
287
|
+
export async function endpointForRevision(
|
|
237
288
|
ctx: EngineContext,
|
|
238
|
-
spec: {
|
|
239
|
-
|
|
240
|
-
|
|
289
|
+
spec: {
|
|
290
|
+
functionName: string;
|
|
291
|
+
functionArn: string;
|
|
292
|
+
endpointNames: readonly [string, string];
|
|
293
|
+
revisionId: string;
|
|
294
|
+
liveDomain?: string;
|
|
295
|
+
distributionArn?: string;
|
|
296
|
+
/** The endpoint's cap on environments; unchanged when absent. */
|
|
297
|
+
maxEnvironments?: number;
|
|
298
|
+
},
|
|
299
|
+
): Promise<RevisionEndpoint> {
|
|
300
|
+
const { functionName, revisionId } = spec;
|
|
301
|
+
const read = () =>
|
|
302
|
+
Promise.all(
|
|
303
|
+
spec.endpointNames.map(async (name) => ({ name, e: await getEndpoint(ctx, functionName, name) })),
|
|
304
|
+
);
|
|
305
|
+
const before = await read();
|
|
306
|
+
const reuse = before.find((c) => c.e && pinnedTo(c.e, revisionId))?.name;
|
|
307
|
+
const live = before.find((c) => c.e?.domainName && c.e.domainName === spec.liveDomain)?.name;
|
|
308
|
+
const endpointName = reuse ?? spec.endpointNames.find((n) => n !== live)!;
|
|
309
|
+
const endpoint = await ensureEndpoint(ctx, {
|
|
310
|
+
functionName,
|
|
311
|
+
endpointName,
|
|
312
|
+
revisionId,
|
|
313
|
+
...(spec.maxEnvironments ? { maxEnvironments: spec.maxEnvironments } : {}),
|
|
314
|
+
});
|
|
315
|
+
if (!reuse) {
|
|
316
|
+
ctx.log('info', `endpoint ${endpointName} → revision ${revisionId}`, `web-function ${functionName}`);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const after = (await read()).flatMap((c) => (c.e ? [c.e] : []));
|
|
320
|
+
if (spec.distributionArn) {
|
|
321
|
+
await ensureRouterAccess(ctx, {
|
|
322
|
+
functionArn: spec.functionArn,
|
|
323
|
+
endpointArns: after.map((e) => e.endpointArn!),
|
|
324
|
+
distributionArn: spec.distributionArn,
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
return {
|
|
328
|
+
domainName: endpoint.domainName,
|
|
329
|
+
pinned: after.flatMap((e) => (e.revisionWeights ?? []).map((w) => w.revisionId!)),
|
|
330
|
+
};
|
|
241
331
|
}
|
|
242
332
|
|
|
243
333
|
/**
|
|
244
|
-
* Allow only the platform's CloudFront distribution to invoke the
|
|
334
|
+
* Allow only the platform's CloudFront distribution to invoke the endpoints
|
|
245
335
|
* (OAC signs origin requests). A function has one resource policy, so this
|
|
246
336
|
* is read-modify-write guarded by the policy revision id.
|
|
247
337
|
*/
|
|
248
338
|
export async function ensureRouterAccess(
|
|
249
339
|
ctx: EngineContext,
|
|
250
|
-
spec: { functionArn: string;
|
|
340
|
+
spec: { functionArn: string; endpointArns: string[]; distributionArn: string },
|
|
251
341
|
): Promise<void> {
|
|
252
342
|
const lw = ctx.clients.lambdaWeb;
|
|
253
343
|
const sid = 'AllowPlatformRouter';
|
|
344
|
+
const arns = spec.endpointArns.toSorted();
|
|
254
345
|
const statement = {
|
|
255
346
|
Sid: sid,
|
|
256
347
|
Effect: 'Allow',
|
|
257
348
|
Principal: { Service: 'cloudfront.amazonaws.com' },
|
|
258
349
|
Action: 'lambda:InvokeWebFunctionEndpoint',
|
|
259
|
-
Resource:
|
|
350
|
+
Resource: arns.length === 1 ? arns[0] : arns,
|
|
260
351
|
Condition: { StringEquals: { 'aws:SourceArn': spec.distributionArn } },
|
|
261
352
|
};
|
|
262
353
|
await retry(
|
package/src/emulator.ts
CHANGED
|
@@ -96,7 +96,7 @@ export async function startEmulator(opts: StartEmulatorOptions = {}): Promise<Em
|
|
|
96
96
|
opts.onLog?.(line);
|
|
97
97
|
let parsed: { fields?: Record<string, string> } | undefined;
|
|
98
98
|
try {
|
|
99
|
-
parsed = JSON.parse(line);
|
|
99
|
+
parsed = JSON.parse(line) as { fields?: Record<string, string> };
|
|
100
100
|
} catch {
|
|
101
101
|
return;
|
|
102
102
|
}
|
|
@@ -107,8 +107,8 @@ export async function startEmulator(opts: StartEmulatorOptions = {}): Promise<Em
|
|
|
107
107
|
resolve({ endpoint: f.endpoint_url, caFile: f.ca_file, credentialsFile });
|
|
108
108
|
}
|
|
109
109
|
};
|
|
110
|
-
createInterface({ input: child.stdout
|
|
111
|
-
createInterface({ input: child.stderr
|
|
110
|
+
createInterface({ input: child.stdout }).on('line', onLine);
|
|
111
|
+
createInterface({ input: child.stderr }).on('line', onLine);
|
|
112
112
|
child.once('exit', (code) => {
|
|
113
113
|
clearTimeout(timer);
|
|
114
114
|
reject(new Error(`AWS Emulator exited during startup (code ${code})`));
|
package/src/images.ts
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OCI image assembly without Docker: a layer is a deterministic tarball of
|
|
3
|
+
* files, an image is a base image's layers plus that layer, described by a
|
|
4
|
+
* config and a manifest. Pure functions; the registry calls live in
|
|
5
|
+
* `drivers/ecr.ts`.
|
|
6
|
+
*
|
|
7
|
+
* Determinism matters: the same files on the same base give byte-identical
|
|
8
|
+
* blobs, so redeploying unchanged code pushes nothing new and the image
|
|
9
|
+
* digest says whether a build changed.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { gzipSync } from 'fflate';
|
|
14
|
+
|
|
15
|
+
export const MEDIA_TYPES = {
|
|
16
|
+
ociManifest: 'application/vnd.oci.image.manifest.v1+json',
|
|
17
|
+
ociIndex: 'application/vnd.oci.image.index.v1+json',
|
|
18
|
+
ociConfig: 'application/vnd.oci.image.config.v1+json',
|
|
19
|
+
ociLayerGzip: 'application/vnd.oci.image.layer.v1.tar+gzip',
|
|
20
|
+
dockerManifest: 'application/vnd.docker.distribution.manifest.v2+json',
|
|
21
|
+
dockerManifestList: 'application/vnd.docker.distribution.manifest.list.v2+json',
|
|
22
|
+
} as const;
|
|
23
|
+
|
|
24
|
+
/** Single-platform manifest types a base image may have. */
|
|
25
|
+
export const IMAGE_MANIFEST_TYPES: readonly string[] = [MEDIA_TYPES.ociManifest, MEDIA_TYPES.dockerManifest];
|
|
26
|
+
|
|
27
|
+
export interface Descriptor {
|
|
28
|
+
mediaType: string;
|
|
29
|
+
digest: string;
|
|
30
|
+
size: number;
|
|
31
|
+
annotations?: Record<string, string>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ImageManifest {
|
|
35
|
+
schemaVersion: 2;
|
|
36
|
+
mediaType?: string;
|
|
37
|
+
config: Descriptor;
|
|
38
|
+
layers: Descriptor[];
|
|
39
|
+
annotations?: Record<string, string>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The parts of an OCI image config the platform reads or writes; the rest passes through. */
|
|
43
|
+
export interface ImageConfig {
|
|
44
|
+
architecture: string;
|
|
45
|
+
os: string;
|
|
46
|
+
created?: string;
|
|
47
|
+
config?: {
|
|
48
|
+
Env?: string[];
|
|
49
|
+
Entrypoint?: string[] | null;
|
|
50
|
+
Cmd?: string[] | null;
|
|
51
|
+
WorkingDir?: string;
|
|
52
|
+
User?: string;
|
|
53
|
+
[key: string]: unknown;
|
|
54
|
+
};
|
|
55
|
+
rootfs: { type: 'layers'; diff_ids: string[] };
|
|
56
|
+
history?: Array<{ created?: string; created_by?: string; comment?: string; empty_layer?: boolean }>;
|
|
57
|
+
[key: string]: unknown;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface ImageFile {
|
|
61
|
+
/** Absolute path inside the image (`/app/index.mjs`). */
|
|
62
|
+
path: string;
|
|
63
|
+
content: Uint8Array;
|
|
64
|
+
/** Default 0o644. */
|
|
65
|
+
mode?: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface Layer {
|
|
69
|
+
/** The gzipped tarball as pushed. */
|
|
70
|
+
blob: Uint8Array;
|
|
71
|
+
/** sha256 of `blob`: the layer's digest in the manifest. */
|
|
72
|
+
digest: string;
|
|
73
|
+
/** sha256 of the uncompressed tarball: the layer's entry in the config's `rootfs.diff_ids`. */
|
|
74
|
+
diffId: string;
|
|
75
|
+
size: number;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function sha256Digest(bytes: Uint8Array): string {
|
|
79
|
+
return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* A ustar archive of `files` plus an entry for every parent directory,
|
|
84
|
+
* sorted by path, owned by root with mtime 0, so equal input gives equal
|
|
85
|
+
* bytes.
|
|
86
|
+
*/
|
|
87
|
+
export function tarFiles(files: readonly ImageFile[]): Uint8Array {
|
|
88
|
+
const entries = new Map<string, { type: 'dir' } | { type: 'file'; content: Uint8Array; mode: number }>();
|
|
89
|
+
for (const f of files) {
|
|
90
|
+
const rel = normalizePath(f.path);
|
|
91
|
+
const parts = rel.split('/');
|
|
92
|
+
for (let i = 1; i < parts.length; i++) entries.set(`${parts.slice(0, i).join('/')}/`, { type: 'dir' });
|
|
93
|
+
if (entries.has(rel)) throw new Error(`duplicate file in layer: ${f.path}`);
|
|
94
|
+
entries.set(rel, { type: 'file', content: f.content, mode: f.mode ?? 0o644 });
|
|
95
|
+
}
|
|
96
|
+
const blocks: Uint8Array[] = [];
|
|
97
|
+
for (const name of [...entries.keys()].toSorted()) {
|
|
98
|
+
const e = entries.get(name)!;
|
|
99
|
+
if (e.type === 'dir') {
|
|
100
|
+
blocks.push(tarHeader({ name, mode: 0o755, size: 0, type: '5' }));
|
|
101
|
+
} else {
|
|
102
|
+
blocks.push(tarHeader({ name, mode: e.mode, size: e.content.length, type: '0' }), e.content);
|
|
103
|
+
const pad = (512 - (e.content.length % 512)) % 512;
|
|
104
|
+
if (pad) blocks.push(new Uint8Array(pad));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
blocks.push(new Uint8Array(1024));
|
|
108
|
+
return concat(blocks);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** A gzipped layer of `files` with its digests. */
|
|
112
|
+
export function buildLayer(files: readonly ImageFile[]): Layer {
|
|
113
|
+
const tar = tarFiles(files);
|
|
114
|
+
// mtime 0 keeps the gzip header (and so the digest) stable.
|
|
115
|
+
const blob = gzipSync(tar, { level: 9, mtime: 0 });
|
|
116
|
+
return { blob, digest: sha256Digest(blob), diffId: sha256Digest(tar), size: blob.length };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface ImageConfigSpec {
|
|
120
|
+
entrypoint: string[];
|
|
121
|
+
/** Replaces the base image's Cmd; none when omitted (the base's would be appended to the entrypoint). */
|
|
122
|
+
cmd?: string[];
|
|
123
|
+
/** Merged over the base image's environment. */
|
|
124
|
+
env?: Record<string, string>;
|
|
125
|
+
workingDir?: string;
|
|
126
|
+
user?: string;
|
|
127
|
+
/** History line for the added layer. */
|
|
128
|
+
createdBy?: string;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The base image's config with `layer` on top and the process settings of `spec`. */
|
|
132
|
+
export function imageConfig(base: ImageConfig, layer: Layer, spec: ImageConfigSpec): ImageConfig {
|
|
133
|
+
const env = new Map<string, string>();
|
|
134
|
+
for (const kv of base.config?.Env ?? []) {
|
|
135
|
+
const i = kv.indexOf('=');
|
|
136
|
+
env.set(i === -1 ? kv : kv.slice(0, i), i === -1 ? '' : kv.slice(i + 1));
|
|
137
|
+
}
|
|
138
|
+
for (const [k, v] of Object.entries(spec.env ?? {})) env.set(k, v);
|
|
139
|
+
const { Cmd: _cmd, ...baseProcess } = base.config ?? {};
|
|
140
|
+
return {
|
|
141
|
+
...base,
|
|
142
|
+
config: {
|
|
143
|
+
...baseProcess,
|
|
144
|
+
Env: [...env].map(([k, v]) => `${k}=${v}`),
|
|
145
|
+
Entrypoint: spec.entrypoint,
|
|
146
|
+
...(spec.cmd ? { Cmd: spec.cmd } : {}),
|
|
147
|
+
...(spec.workingDir ? { WorkingDir: spec.workingDir } : {}),
|
|
148
|
+
...(spec.user ? { User: spec.user } : {}),
|
|
149
|
+
},
|
|
150
|
+
rootfs: { type: 'layers', diff_ids: [...base.rootfs.diff_ids, layer.diffId] },
|
|
151
|
+
history: [
|
|
152
|
+
...(base.history ?? []),
|
|
153
|
+
{ ...(base.created ? { created: base.created } : {}), created_by: spec.createdBy ?? 'platform' },
|
|
154
|
+
],
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** An OCI image manifest (serialized: its bytes are what the digest covers). */
|
|
159
|
+
export function imageManifest(
|
|
160
|
+
config: { digest: string; size: number },
|
|
161
|
+
layers: readonly Descriptor[],
|
|
162
|
+
): string {
|
|
163
|
+
const manifest: ImageManifest = {
|
|
164
|
+
schemaVersion: 2,
|
|
165
|
+
mediaType: MEDIA_TYPES.ociManifest,
|
|
166
|
+
config: { mediaType: MEDIA_TYPES.ociConfig, digest: config.digest, size: config.size },
|
|
167
|
+
layers: layers.map((l) => ({ mediaType: l.mediaType, digest: l.digest, size: l.size })),
|
|
168
|
+
};
|
|
169
|
+
return JSON.stringify(manifest);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function layerDescriptor(layer: Layer): Descriptor {
|
|
173
|
+
return { mediaType: MEDIA_TYPES.ociLayerGzip, digest: layer.digest, size: layer.size };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Parse a registry manifest, refusing multi-platform indexes (a base must be pinned to one platform). */
|
|
177
|
+
export function parseImageManifest(raw: string, fallbackMediaType?: string): ImageManifest {
|
|
178
|
+
const m = JSON.parse(raw) as Partial<ImageManifest> & { manifests?: unknown };
|
|
179
|
+
const mediaType = m.mediaType ?? fallbackMediaType;
|
|
180
|
+
if (m.manifests || mediaType === MEDIA_TYPES.ociIndex || mediaType === MEDIA_TYPES.dockerManifestList) {
|
|
181
|
+
throw new Error('expected a single-platform image manifest, got a multi-platform index');
|
|
182
|
+
}
|
|
183
|
+
if (m.schemaVersion !== 2 || !m.config?.digest || !Array.isArray(m.layers)) {
|
|
184
|
+
throw new Error('not an image manifest (schema version 2 with a config and layers)');
|
|
185
|
+
}
|
|
186
|
+
return m as ImageManifest;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function normalizePath(path: string): string {
|
|
190
|
+
const rel = path.replace(/^\/+/, '');
|
|
191
|
+
if (!rel || rel.endsWith('/') || rel.split('/').some((p) => p === '' || p === '.' || p === '..')) {
|
|
192
|
+
throw new Error(`invalid file path in layer: ${path}`);
|
|
193
|
+
}
|
|
194
|
+
return rel;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const encoder = new TextEncoder();
|
|
198
|
+
|
|
199
|
+
function tarHeader(e: { name: string; mode: number; size: number; type: '0' | '5' }): Uint8Array {
|
|
200
|
+
const h = new Uint8Array(512);
|
|
201
|
+
const [prefix, name] = splitName(e.name);
|
|
202
|
+
writeString(h, 0, 100, name);
|
|
203
|
+
writeOctal(h, 100, 8, e.mode);
|
|
204
|
+
writeOctal(h, 108, 8, 0); // uid
|
|
205
|
+
writeOctal(h, 116, 8, 0); // gid
|
|
206
|
+
writeOctal(h, 124, 12, e.size);
|
|
207
|
+
writeOctal(h, 136, 12, 0); // mtime
|
|
208
|
+
h.fill(0x20, 148, 156); // checksum is computed with its own field as spaces
|
|
209
|
+
h[156] = e.type.charCodeAt(0);
|
|
210
|
+
writeString(h, 257, 6, 'ustar');
|
|
211
|
+
writeString(h, 263, 2, '00');
|
|
212
|
+
writeString(h, 265, 32, 'root');
|
|
213
|
+
writeString(h, 297, 32, 'root');
|
|
214
|
+
writeString(h, 345, 155, prefix);
|
|
215
|
+
const sum = h.reduce((a, b) => a + b, 0);
|
|
216
|
+
writeString(h, 148, 8, `${sum.toString(8).padStart(6, '0')}\0 `);
|
|
217
|
+
return h;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** ustar keeps names ≤ 100 bytes, or a ≤ 155-byte prefix plus a ≤ 100-byte name split at a `/`. */
|
|
221
|
+
function splitName(path: string): [string, string] {
|
|
222
|
+
const bytes = encoder.encode(path);
|
|
223
|
+
if (bytes.length <= 100) return ['', path];
|
|
224
|
+
// A directory entry's trailing slash stays with the name part.
|
|
225
|
+
for (let i = path.length - 2; i > 0; i--) {
|
|
226
|
+
if (path[i] !== '/') continue;
|
|
227
|
+
const prefix = path.slice(0, i);
|
|
228
|
+
const name = path.slice(i + 1);
|
|
229
|
+
if (encoder.encode(prefix).length <= 155 && encoder.encode(name).length <= 100) return [prefix, name];
|
|
230
|
+
}
|
|
231
|
+
throw new Error(`path too long for a ustar layer: ${path}`);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function writeString(h: Uint8Array, offset: number, length: number, value: string): void {
|
|
235
|
+
const bytes = encoder.encode(value);
|
|
236
|
+
if (bytes.length > length) throw new Error(`tar header field too long: ${value}`);
|
|
237
|
+
h.set(bytes, offset);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function writeOctal(h: Uint8Array, offset: number, length: number, value: number): void {
|
|
241
|
+
const digits = value.toString(8);
|
|
242
|
+
if (digits.length > length - 1) throw new Error(`tar header value too large: ${value}`);
|
|
243
|
+
writeString(h, offset, length, `${digits.padStart(length - 1, '0')}\0`);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function concat(parts: readonly Uint8Array[]): Uint8Array {
|
|
247
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
248
|
+
let at = 0;
|
|
249
|
+
for (const p of parts) {
|
|
250
|
+
out.set(p, at);
|
|
251
|
+
at += p.length;
|
|
252
|
+
}
|
|
253
|
+
return out;
|
|
254
|
+
}
|