@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.
Files changed (98) hide show
  1. package/dist/clients.d.ts +8 -0
  2. package/dist/clients.js +22 -1
  3. package/dist/clients.js.map +1 -1
  4. package/dist/compat.d.ts +21 -9
  5. package/dist/compat.js +27 -7
  6. package/dist/compat.js.map +1 -1
  7. package/dist/drivers/appsync.d.ts +49 -0
  8. package/dist/drivers/appsync.js +155 -0
  9. package/dist/drivers/appsync.js.map +1 -0
  10. package/dist/drivers/ecr.d.ts +109 -0
  11. package/dist/drivers/ecr.js +303 -0
  12. package/dist/drivers/ecr.js.map +1 -0
  13. package/dist/drivers/ecs.d.ts +163 -0
  14. package/dist/drivers/ecs.js +447 -0
  15. package/dist/drivers/ecs.js.map +1 -0
  16. package/dist/drivers/events.d.ts +10 -0
  17. package/dist/drivers/events.js +13 -1
  18. package/dist/drivers/events.js.map +1 -1
  19. package/dist/drivers/index.d.ts +5 -0
  20. package/dist/drivers/index.js +5 -0
  21. package/dist/drivers/index.js.map +1 -1
  22. package/dist/drivers/kvs.d.ts +3 -0
  23. package/dist/drivers/kvs.js +14 -7
  24. package/dist/drivers/kvs.js.map +1 -1
  25. package/dist/drivers/lambda.d.ts +22 -0
  26. package/dist/drivers/lambda.js +74 -3
  27. package/dist/drivers/lambda.js.map +1 -1
  28. package/dist/drivers/request-function.d.ts +60 -0
  29. package/dist/drivers/request-function.js +167 -0
  30. package/dist/drivers/request-function.js.map +1 -0
  31. package/dist/drivers/s3.d.ts +7 -0
  32. package/dist/drivers/s3.js +31 -0
  33. package/dist/drivers/s3.js.map +1 -1
  34. package/dist/drivers/scheduler.d.ts +24 -0
  35. package/dist/drivers/scheduler.js +60 -5
  36. package/dist/drivers/scheduler.js.map +1 -1
  37. package/dist/drivers/ses.d.ts +77 -0
  38. package/dist/drivers/ses.js +181 -0
  39. package/dist/drivers/ses.js.map +1 -0
  40. package/dist/drivers/sqs.d.ts +11 -0
  41. package/dist/drivers/sqs.js +67 -1
  42. package/dist/drivers/sqs.js.map +1 -1
  43. package/dist/drivers/ssm.d.ts +1 -0
  44. package/dist/drivers/ssm.js +23 -3
  45. package/dist/drivers/ssm.js.map +1 -1
  46. package/dist/drivers/web-function.d.ts +41 -11
  47. package/dist/drivers/web-function.js +62 -8
  48. package/dist/drivers/web-function.js.map +1 -1
  49. package/dist/emulator.js.map +1 -1
  50. package/dist/images.d.ts +104 -0
  51. package/dist/images.js +182 -0
  52. package/dist/images.js.map +1 -0
  53. package/dist/index.d.ts +132 -7
  54. package/dist/index.js +11 -2
  55. package/dist/index.js.map +1 -1
  56. package/dist/local.js +222 -7
  57. package/dist/local.js.map +1 -1
  58. package/dist/policy.d.ts +47 -4
  59. package/dist/policy.js +369 -15
  60. package/dist/policy.js.map +1 -1
  61. package/dist/services.d.ts +155 -0
  62. package/dist/services.js +464 -0
  63. package/dist/services.js.map +1 -0
  64. package/dist/stage.d.ts +44 -4
  65. package/dist/stage.js +681 -138
  66. package/dist/stage.js.map +1 -1
  67. package/dist/static.d.ts +1 -1
  68. package/dist/static.js +2 -36
  69. package/dist/static.js.map +1 -1
  70. package/dist/util.d.ts +22 -0
  71. package/dist/util.js +18 -2
  72. package/dist/util.js.map +1 -1
  73. package/package.json +20 -14
  74. package/src/clients.ts +25 -1
  75. package/src/compat.ts +34 -11
  76. package/src/drivers/appsync.ts +220 -0
  77. package/src/drivers/ecr.ts +457 -0
  78. package/src/drivers/ecs.ts +661 -0
  79. package/src/drivers/events.ts +29 -2
  80. package/src/drivers/index.ts +5 -0
  81. package/src/drivers/kvs.ts +21 -12
  82. package/src/drivers/lambda.ts +103 -2
  83. package/src/drivers/request-function.ts +295 -0
  84. package/src/drivers/s3.ts +46 -0
  85. package/src/drivers/scheduler.ts +88 -5
  86. package/src/drivers/ses.ts +267 -0
  87. package/src/drivers/sqs.ts +95 -0
  88. package/src/drivers/ssm.ts +23 -2
  89. package/src/drivers/web-function.ts +108 -17
  90. package/src/emulator.ts +3 -3
  91. package/src/images.ts +254 -0
  92. package/src/index.ts +131 -8
  93. package/src/local.ts +251 -7
  94. package/src/policy.ts +450 -26
  95. package/src/services.ts +663 -0
  96. package/src/stage.ts +839 -153
  97. package/src/static.ts +2 -37
  98. package/src/util.ts +38 -4
@@ -0,0 +1,220 @@
1
+ import {
2
+ type Api,
3
+ type ApiKey,
4
+ type AuthMode,
5
+ type ChannelNamespace,
6
+ CreateApiKeyCommand,
7
+ CreateChannelNamespaceCommand,
8
+ DeleteChannelNamespaceCommand,
9
+ GetChannelNamespaceCommand,
10
+ ListApiKeysCommand,
11
+ ListApisCommand,
12
+ UpdateApiKeyCommand,
13
+ UpdateChannelNamespaceCommand,
14
+ } from '@aws-sdk/client-appsync';
15
+ import {
16
+ type PlatformRuntimeConfig,
17
+ platformNames,
18
+ REALTIME_KVS_KEY,
19
+ type RealtimeEdgeEntry,
20
+ type RealtimeSubscribe,
21
+ } from '@ericminassian/platform-core';
22
+ import { type EngineContext, errorName, ignoreNotFound } from '../util.ts';
23
+ import { getKey, putKey } from './kvs.ts';
24
+
25
+ /**
26
+ * AppSync Events: each stage with `realtime` gets a channel namespace in the
27
+ * platform's one Event API (the foundation stack creates the API; the
28
+ * emulator's is created by `ensureLocal`). Namespaces are named, not tagged
29
+ * state, like everything else the engine owns.
30
+ */
31
+
32
+ /**
33
+ * How a namespace authorizes. Browsers never publish: only the stage role
34
+ * (IAM, `appsync:EventPublish` on this namespace) can. Public stages
35
+ * subscribe with the platform's API key; signed-in stages with a token the
36
+ * platform's Lambda authorizer checks.
37
+ */
38
+ export function namespaceAuthModes(subscribe: RealtimeSubscribe): {
39
+ publishAuthModes: AuthMode[];
40
+ subscribeAuthModes: AuthMode[];
41
+ } {
42
+ return {
43
+ publishAuthModes: [{ authType: 'AWS_IAM' }],
44
+ subscribeAuthModes: [{ authType: subscribe === 'public' ? 'API_KEY' : 'AWS_LAMBDA' }],
45
+ };
46
+ }
47
+
48
+ const QUOTA_NAME = 'Event APIs - Channel namespaces per API';
49
+
50
+ /** The Event API with this name (the platform's is `platformNames.realtimeApi`), if it exists. */
51
+ export async function findEventApi(ctx: EngineContext, name: string): Promise<Api | undefined> {
52
+ let nextToken: string | undefined;
53
+ do {
54
+ const res = await ctx.clients.appsync.send(new ListApisCommand(nextToken ? { nextToken } : {}));
55
+ const found = (res.apis ?? []).find((a) => a.name === name && a.eventConfig);
56
+ if (found) return found;
57
+ nextToken = res.nextToken;
58
+ } while (nextToken);
59
+ return undefined;
60
+ }
61
+
62
+ export async function getChannelNamespace(
63
+ ctx: EngineContext,
64
+ apiId: string,
65
+ name: string,
66
+ ): Promise<ChannelNamespace | undefined> {
67
+ const res = await ignoreNotFound(ctx.clients.appsync.send(new GetChannelNamespaceCommand({ apiId, name })));
68
+ return res?.channelNamespace;
69
+ }
70
+
71
+ /** Create the stage's namespace, or bring an existing one's auth modes in line. */
72
+ export async function ensureChannelNamespace(
73
+ ctx: EngineContext,
74
+ spec: { apiId: string; name: string; subscribe: RealtimeSubscribe; tags: Record<string, string> },
75
+ ): Promise<{ name: string; arn?: string }> {
76
+ const modes = namespaceAuthModes(spec.subscribe);
77
+ const existing = await getChannelNamespace(ctx, spec.apiId, spec.name);
78
+ if (existing) {
79
+ if (
80
+ !sameModes(existing.subscribeAuthModes, modes.subscribeAuthModes) ||
81
+ !sameModes(existing.publishAuthModes, modes.publishAuthModes)
82
+ ) {
83
+ await ctx.clients.appsync.send(
84
+ new UpdateChannelNamespaceCommand({ apiId: spec.apiId, name: spec.name, ...modes }),
85
+ );
86
+ ctx.log('info', `subscribers now ${spec.subscribe}`, `channel-namespace ${spec.name}`);
87
+ }
88
+ return {
89
+ name: spec.name,
90
+ ...(existing.channelNamespaceArn ? { arn: existing.channelNamespaceArn } : {}),
91
+ };
92
+ }
93
+ try {
94
+ const res = await ctx.clients.appsync.send(
95
+ new CreateChannelNamespaceCommand({ apiId: spec.apiId, name: spec.name, ...modes, tags: spec.tags }),
96
+ );
97
+ ctx.log('info', 'created channel namespace', `channel-namespace ${spec.name}`);
98
+ const arn = res.channelNamespace?.channelNamespaceArn;
99
+ return { name: spec.name, ...(arn ? { arn } : {}) };
100
+ } catch (e) {
101
+ if (errorName(e) === 'ServiceQuotaExceededException') {
102
+ throw new Error(
103
+ `The platform's realtime API has no room for another channel namespace. Every stage with ` +
104
+ `realtime (preview stages too) has one; destroy unused previews or raise the "${QUOTA_NAME}" ` +
105
+ 'quota (default 50, adjustable) in Service Quotas.',
106
+ { cause: e },
107
+ );
108
+ }
109
+ throw e;
110
+ }
111
+ }
112
+
113
+ export async function deleteChannelNamespace(
114
+ ctx: EngineContext,
115
+ apiId: string,
116
+ name: string,
117
+ ): Promise<boolean> {
118
+ const res = await ignoreNotFound(
119
+ ctx.clients.appsync.send(new DeleteChannelNamespaceCommand({ apiId, name })),
120
+ );
121
+ if (res === undefined) return false;
122
+ ctx.log('info', 'deleted channel namespace', `channel-namespace ${name}`);
123
+ return true;
124
+ }
125
+
126
+ function sameModes(a: AuthMode[] | undefined, b: AuthMode[]): boolean {
127
+ const key = (m: AuthMode[] | undefined) =>
128
+ (m ?? [])
129
+ .map((x) => x.authType ?? '')
130
+ .toSorted((p, q) => (p < q ? -1 : p > q ? 1 : 0))
131
+ .join(',');
132
+ return key(a) === key(b);
133
+ }
134
+
135
+ // ---------------------------------------------------------------- public API key
136
+
137
+ const DAY = 86_400;
138
+ /**
139
+ * AppSync caps a key's life at 365 days from now (rounded down to the hour);
140
+ * a day less keeps clear of that edge. The key is extended, never replaced,
141
+ * so its value (what public browsers subscribe with) stays the same.
142
+ */
143
+ const KEY_LIFETIME = 364 * DAY;
144
+ /** Extend once fewer days than this remain: about monthly with a daily caller. */
145
+ const KEY_RENEW_BELOW = 335 * DAY;
146
+
147
+ /**
148
+ * The API's subscribe-only key for `public` stages, found by its description.
149
+ * Created when missing (or expired); extended when it has under 335 days
150
+ * left. The control plane calls this nightly and on every realtime deploy.
151
+ * Returns the key (its id is the value browsers send).
152
+ */
153
+ export async function ensurePublicApiKey(
154
+ ctx: EngineContext,
155
+ apiId: string,
156
+ nowSeconds = Math.floor(Date.now() / 1000),
157
+ ): Promise<string> {
158
+ const keys: ApiKey[] = [];
159
+ let nextToken: string | undefined;
160
+ do {
161
+ const res = await ctx.clients.appsync.send(
162
+ new ListApiKeysCommand({ apiId, ...(nextToken ? { nextToken } : {}) }),
163
+ );
164
+ keys.push(...(res.apiKeys ?? []));
165
+ nextToken = res.nextToken;
166
+ } while (nextToken);
167
+ const live = keys
168
+ .filter((k) => k.description === platformNames.realtimePublicKey && k.id && (k.expires ?? 0) > nowSeconds)
169
+ .toSorted((a, b) => (b.expires ?? 0) - (a.expires ?? 0))[0];
170
+ if (live?.id) {
171
+ if ((live.expires ?? 0) - nowSeconds < KEY_RENEW_BELOW) {
172
+ await ctx.clients.appsync.send(
173
+ new UpdateApiKeyCommand({ apiId, id: live.id, expires: nowSeconds + KEY_LIFETIME }),
174
+ );
175
+ ctx.log('info', 'extended the public subscribe key', `api-key ${platformNames.realtimePublicKey}`);
176
+ }
177
+ return live.id;
178
+ }
179
+ const created = await ctx.clients.appsync.send(
180
+ new CreateApiKeyCommand({
181
+ apiId,
182
+ description: platformNames.realtimePublicKey,
183
+ expires: nowSeconds + KEY_LIFETIME,
184
+ }),
185
+ );
186
+ const id = created.apiKey?.id;
187
+ if (!id) throw new Error('AppSync created an API key without an id');
188
+ // A new value only reaches browsers through the route-store entry; public
189
+ // stages' open connections keep working, new ones pick up the new key.
190
+ ctx.log('warn', 'created a new public subscribe key', `api-key ${platformNames.realtimePublicKey}`);
191
+ return id;
192
+ }
193
+
194
+ // ---------------------------------------------------------------- platform entry
195
+
196
+ /**
197
+ * Make the platform's realtime usable: the public key exists and is far from
198
+ * expiry, and the router's entry (`REALTIME_KVS_KEY`) names AppSync's domains
199
+ * and that key. Written only when it changed, so the nightly call is a read.
200
+ * Returns the entry (what `plat dev`'s local router serves), or undefined on
201
+ * a platform without realtime. Without a route store (the emulator) nothing
202
+ * is written.
203
+ */
204
+ export async function ensureRealtimePlatform(
205
+ ctx: EngineContext,
206
+ platform: PlatformRuntimeConfig,
207
+ ): Promise<RealtimeEdgeEntry | undefined> {
208
+ const rt = platform.realtime;
209
+ if (!rt) return undefined;
210
+ const key = await ensurePublicApiKey(ctx, rt.apiId);
211
+ const entry: RealtimeEdgeEntry = { v: 1, o: rt.realtimeDomain, h: rt.httpDomain, k: key };
212
+ if (platform.kvsArn) {
213
+ const value = JSON.stringify(entry);
214
+ if ((await getKey(ctx, platform.kvsArn, REALTIME_KVS_KEY)) !== value) {
215
+ await putKey(ctx, platform.kvsArn, REALTIME_KVS_KEY, value);
216
+ ctx.log('info', 'updated the realtime route entry', `route ${REALTIME_KVS_KEY}`);
217
+ }
218
+ }
219
+ return entry;
220
+ }
@@ -0,0 +1,457 @@
1
+ import {
2
+ BatchCheckLayerAvailabilityCommand,
3
+ BatchDeleteImageCommand,
4
+ BatchGetImageCommand,
5
+ CompleteLayerUploadCommand,
6
+ CreateRepositoryCommand,
7
+ DescribeImagesCommand,
8
+ DescribeRepositoriesCommand,
9
+ GetDownloadUrlForLayerCommand,
10
+ InitiateLayerUploadCommand,
11
+ PutImageCommand,
12
+ UploadLayerPartCommand,
13
+ } from '@aws-sdk/client-ecr';
14
+ import {
15
+ buildLayer,
16
+ type Descriptor,
17
+ IMAGE_MANIFEST_TYPES,
18
+ type ImageConfig,
19
+ type ImageFile,
20
+ type ImageManifest,
21
+ imageConfig,
22
+ imageManifest,
23
+ layerDescriptor,
24
+ MEDIA_TYPES,
25
+ parseImageManifest,
26
+ sha256Digest,
27
+ } from '../images.ts';
28
+ import { type EngineContext, errorName, ignoreNotFound, mapLimit, sendRaw, tagList } from '../util.ts';
29
+
30
+ /**
31
+ * Container images through the ECR API alone (no Docker daemon, no registry
32
+ * login): blobs go up with the layer-upload calls and images are manifests
33
+ * written with PutImage. Every call is IAM-authorized on the repository.
34
+ */
35
+
36
+ export interface RepositoryState {
37
+ name: string;
38
+ arn: string;
39
+ registryId: string;
40
+ }
41
+
42
+ export async function ensureRepository(
43
+ ctx: EngineContext,
44
+ spec: { name: string; tags?: Record<string, string> },
45
+ ): Promise<RepositoryState> {
46
+ const ecr = ctx.clients.ecr;
47
+ const existing = await ignoreNotFound(
48
+ ecr.send(new DescribeRepositoriesCommand({ repositoryNames: [spec.name] })),
49
+ );
50
+ const repo =
51
+ existing?.repositories?.[0] ??
52
+ (
53
+ await ecr.send(
54
+ new CreateRepositoryCommand({
55
+ repositoryName: spec.name,
56
+ imageTagMutability: 'MUTABLE',
57
+ ...(spec.tags ? { tags: tagList(spec.tags) } : {}),
58
+ }),
59
+ )
60
+ ).repository;
61
+ if (!existing?.repositories?.[0]) ctx.log('info', 'created repository', `repository ${spec.name}`);
62
+ return { name: spec.name, arn: repo!.repositoryArn!, registryId: repo!.registryId! };
63
+ }
64
+
65
+ /** An image in a registry other than the platform's, pinned by manifest digest. */
66
+ export interface ImageRef {
67
+ /** `public.ecr.aws`. */
68
+ registry: string;
69
+ /** `docker/library/node`. */
70
+ repository: string;
71
+ digest: string;
72
+ tag?: string;
73
+ }
74
+
75
+ /** Where a base image comes from the first time a repository needs it. */
76
+ export interface ImageSource {
77
+ /** The manifest's raw bytes (its digest is checked against the ref). */
78
+ manifest(ref: ImageRef): Promise<{ bytes: Uint8Array; mediaType?: string }>;
79
+ blob(ref: ImageRef, digest: string): Promise<Uint8Array>;
80
+ }
81
+
82
+ /** Anonymous pulls from a public registry that speaks the distribution API with token auth (ECR Public). */
83
+ export function publicRegistrySource(fetchImpl: typeof fetch = fetch): ImageSource {
84
+ const tokens = new Map<string, Promise<string>>();
85
+ const token = (ref: ImageRef) => {
86
+ const key = `${ref.registry}/${ref.repository}`;
87
+ let t = tokens.get(key);
88
+ if (!t) {
89
+ t = (async () => {
90
+ const url = `https://${ref.registry}/token/?scope=repository:${ref.repository}:pull&service=${ref.registry}`;
91
+ const res = await fetchImpl(url);
92
+ if (!res.ok) throw new Error(`${ref.registry} refused an anonymous pull token (${res.status})`);
93
+ return ((await res.json()) as { token: string }).token;
94
+ })();
95
+ tokens.set(key, t);
96
+ }
97
+ return t;
98
+ };
99
+ const get = async (ref: ImageRef, path: string, accept?: string) => {
100
+ const res = await fetchImpl(`https://${ref.registry}/v2/${ref.repository}/${path}`, {
101
+ headers: { Authorization: `Bearer ${await token(ref)}`, ...(accept ? { Accept: accept } : {}) },
102
+ redirect: 'follow',
103
+ });
104
+ if (!res.ok) throw new Error(`GET ${ref.registry}/${ref.repository}/${path} failed (${res.status})`);
105
+ return res;
106
+ };
107
+ return {
108
+ async manifest(ref) {
109
+ const res = await get(ref, `manifests/${ref.digest}`, IMAGE_MANIFEST_TYPES.join(', '));
110
+ const mediaType = res.headers.get('content-type') ?? undefined;
111
+ return { bytes: new Uint8Array(await res.arrayBuffer()), ...(mediaType ? { mediaType } : {}) };
112
+ },
113
+ async blob(ref, digest) {
114
+ return new Uint8Array(await (await get(ref, `blobs/${digest}`)).arrayBuffer());
115
+ },
116
+ };
117
+ }
118
+
119
+ /** A base image as held in the platform's repository. */
120
+ export interface BaseImage {
121
+ /** Manifest digest (the ref's). */
122
+ digest: string;
123
+ tag: string;
124
+ manifest: ImageManifest;
125
+ config: ImageConfig;
126
+ }
127
+
128
+ /** Tag a base image is kept under: `base--<first 12 hex of its digest>`. */
129
+ export function baseImageTag(digest: string): string {
130
+ return `base--${digest.replace(/^sha256:/, '').slice(0, 12)}`;
131
+ }
132
+
133
+ /**
134
+ * Make `repository` hold `base` (copying it from its registry the first
135
+ * time) and return its manifest and config. The copy is tagged: ECR
136
+ * reclaims layers no image references, so the base's layers stay only
137
+ * while an image of their own points at them.
138
+ */
139
+ export async function ensureBaseImage(
140
+ ctx: EngineContext,
141
+ spec: { repository: string; base: ImageRef; source?: ImageSource },
142
+ ): Promise<BaseImage> {
143
+ const tag = baseImageTag(spec.base.digest);
144
+ const held = await getImage(ctx, spec.repository, { tag });
145
+ if (held) {
146
+ const manifest = parseImageManifest(held.manifest, held.mediaType);
147
+ const config = await readBlob(ctx, spec.repository, manifest.config.digest);
148
+ return {
149
+ digest: held.digest,
150
+ tag,
151
+ manifest,
152
+ config: JSON.parse(new TextDecoder().decode(config)) as ImageConfig,
153
+ };
154
+ }
155
+
156
+ const source = spec.source ?? publicRegistrySource();
157
+ const name = `${spec.base.registry}/${spec.base.repository}@${spec.base.digest}`;
158
+ const fetched = await source.manifest(spec.base);
159
+ if (sha256Digest(fetched.bytes) !== spec.base.digest)
160
+ throw new Error(`${name}: the registry returned a manifest with a different digest`);
161
+ const raw = new TextDecoder().decode(fetched.bytes);
162
+ const manifest = parseImageManifest(raw, fetched.mediaType);
163
+ const blobs = [manifest.config, ...manifest.layers];
164
+ const total = blobs.reduce((n, b) => n + b.size, 0);
165
+ ctx.log(
166
+ 'info',
167
+ `copying base image ${name} (${(total / 1e6).toFixed(0)} MB)`,
168
+ `image ${spec.repository}:${tag}`,
169
+ );
170
+ let config: Uint8Array | undefined;
171
+ const missing = new Set(await missingBlobs(ctx, spec.repository, blobs));
172
+ await mapLimit(blobs, 3, async (b) => {
173
+ if (!missing.has(b.digest) && b !== manifest.config) return;
174
+ const bytes = await source.blob(spec.base, b.digest);
175
+ if (sha256Digest(bytes) !== b.digest || bytes.length !== b.size)
176
+ throw new Error(`${name}: blob ${b.digest} doesn't match its digest`);
177
+ if (b === manifest.config) config = bytes;
178
+ if (missing.has(b.digest)) await uploadBlob(ctx, spec.repository, bytes, b.digest);
179
+ });
180
+ await putImage(ctx, {
181
+ repository: spec.repository,
182
+ manifest: raw,
183
+ mediaType: manifest.mediaType ?? fetched.mediaType ?? MEDIA_TYPES.ociManifest,
184
+ tag,
185
+ });
186
+ if (!config) throw new Error(`${name}: its config blob wasn't fetched`);
187
+ return {
188
+ digest: spec.base.digest,
189
+ tag,
190
+ manifest,
191
+ config: JSON.parse(new TextDecoder().decode(config)) as ImageConfig,
192
+ };
193
+ }
194
+
195
+ export interface PushImageSpec {
196
+ repository: string;
197
+ /** `<registry>/<repository>`: the pushed image is referenced as `<repositoryUri>@<digest>`. */
198
+ repositoryUri: string;
199
+ /** From {@link ensureBaseImage}, in the same repository. */
200
+ base: BaseImage;
201
+ /** Files of the one layer added on top of the base. */
202
+ files: readonly ImageFile[];
203
+ entrypoint: string[];
204
+ cmd?: string[];
205
+ env?: Record<string, string>;
206
+ workingDir?: string;
207
+ user?: string;
208
+ tag: string;
209
+ }
210
+
211
+ /**
212
+ * Build an image (the base plus one layer of `files`) and push it under
213
+ * `tag`. Idempotent: blobs the repository has are skipped and pushing the
214
+ * same image under the same tag again is a no-op.
215
+ */
216
+ export async function pushImage(
217
+ ctx: EngineContext,
218
+ spec: PushImageSpec,
219
+ ): Promise<{ digest: string; image: string }> {
220
+ const layer = buildLayer(spec.files);
221
+ const config = imageConfig(spec.base.config, layer, {
222
+ entrypoint: spec.entrypoint,
223
+ ...(spec.cmd ? { cmd: spec.cmd } : {}),
224
+ ...(spec.env ? { env: spec.env } : {}),
225
+ ...(spec.workingDir ? { workingDir: spec.workingDir } : {}),
226
+ ...(spec.user ? { user: spec.user } : {}),
227
+ createdBy: `platform: ${spec.files.map((f) => f.path).join(' ')}`,
228
+ });
229
+ const configBytes = new TextEncoder().encode(JSON.stringify(config));
230
+ const configDigest = sha256Digest(configBytes);
231
+ const manifest = imageManifest({ digest: configDigest, size: configBytes.length }, [
232
+ ...spec.base.manifest.layers,
233
+ layerDescriptor(layer),
234
+ ]);
235
+ const uploads = new Map([
236
+ [layer.digest, layer.blob],
237
+ [configDigest, configBytes],
238
+ ]);
239
+ const missing = await missingBlobs(
240
+ ctx,
241
+ spec.repository,
242
+ [...uploads].map(([digest, b]) => ({ digest, size: b.length, mediaType: '' })),
243
+ );
244
+ for (const digest of missing) await uploadBlob(ctx, spec.repository, uploads.get(digest)!, digest);
245
+ const digest = await putImage(ctx, {
246
+ repository: spec.repository,
247
+ manifest,
248
+ mediaType: MEDIA_TYPES.ociManifest,
249
+ tag: spec.tag,
250
+ });
251
+ ctx.log('info', `pushed image ${digest.slice(7, 19)}`, `image ${spec.repository}:${spec.tag}`);
252
+ return { digest, image: `${spec.repositoryUri}@${digest}` };
253
+ }
254
+
255
+ export interface ImageListing {
256
+ tag: string;
257
+ digest: string;
258
+ pushedAt?: Date;
259
+ }
260
+
261
+ /** Tagged images whose tag starts with `tagPrefix`, one entry per tag. */
262
+ export async function listImages(
263
+ ctx: EngineContext,
264
+ repository: string,
265
+ tagPrefix = '',
266
+ ): Promise<ImageListing[]> {
267
+ const out: ImageListing[] = [];
268
+ let nextToken: string | undefined;
269
+ do {
270
+ const res = await ignoreNotFound(
271
+ ctx.clients.ecr.send(
272
+ new DescribeImagesCommand({
273
+ repositoryName: repository,
274
+ filter: { tagStatus: 'TAGGED' },
275
+ maxResults: 1000,
276
+ nextToken,
277
+ }),
278
+ ),
279
+ );
280
+ if (!res) return out;
281
+ for (const d of res.imageDetails ?? []) {
282
+ for (const tag of d.imageTags ?? []) {
283
+ if (tag.startsWith(tagPrefix))
284
+ out.push({
285
+ tag,
286
+ digest: d.imageDigest!,
287
+ ...(d.imagePushedAt ? { pushedAt: d.imagePushedAt } : {}),
288
+ });
289
+ }
290
+ }
291
+ nextToken = res.nextToken;
292
+ } while (nextToken);
293
+ return out;
294
+ }
295
+
296
+ /**
297
+ * Delete images by tag or digest. A tag removes only that tag (the image
298
+ * goes with its last tag); a digest removes the image under every tag.
299
+ */
300
+ export async function deleteImages(
301
+ ctx: EngineContext,
302
+ repository: string,
303
+ ids: ReadonlyArray<{ tag: string } | { digest: string }>,
304
+ ): Promise<void> {
305
+ for (let i = 0; i < ids.length; i += 100) {
306
+ const batch = ids.slice(i, i + 100);
307
+ const res = await ignoreNotFound(
308
+ ctx.clients.ecr.send(
309
+ new BatchDeleteImageCommand({
310
+ repositoryName: repository,
311
+ imageIds: batch.map((id) => ('tag' in id ? { imageTag: id.tag } : { imageDigest: id.digest })),
312
+ }),
313
+ ),
314
+ );
315
+ const failed = (res?.failures ?? []).filter((f) => f.failureCode !== 'ImageNotFound');
316
+ if (failed.length) {
317
+ const f = failed[0]!;
318
+ throw new Error(
319
+ `couldn't delete ${f.imageId?.imageTag ?? f.imageId?.imageDigest} from ${repository}: ${f.failureReason}`,
320
+ );
321
+ }
322
+ for (const id of batch)
323
+ ctx.log('info', 'deleted image', `image ${repository}:${'tag' in id ? id.tag : id.digest}`);
324
+ }
325
+ }
326
+
327
+ /** An image's manifest by tag or digest, or undefined when the repository doesn't hold it. */
328
+ export async function getImage(
329
+ ctx: EngineContext,
330
+ repository: string,
331
+ id: { tag: string } | { digest: string },
332
+ ): Promise<{ digest: string; manifest: string; mediaType?: string } | undefined> {
333
+ const res = await ignoreNotFound(
334
+ ctx.clients.ecr.send(
335
+ new BatchGetImageCommand({
336
+ repositoryName: repository,
337
+ imageIds: ['tag' in id ? { imageTag: id.tag } : { imageDigest: id.digest }],
338
+ acceptedMediaTypes: [...IMAGE_MANIFEST_TYPES],
339
+ }),
340
+ ),
341
+ );
342
+ const image = res?.images?.[0];
343
+ if (!image?.imageManifest || !image.imageId?.imageDigest) return undefined;
344
+ return {
345
+ digest: image.imageId.imageDigest,
346
+ manifest: image.imageManifest,
347
+ ...(image.imageManifestMediaType ? { mediaType: image.imageManifestMediaType } : {}),
348
+ };
349
+ }
350
+
351
+ /** Digests of `blobs` the repository doesn't have yet. */
352
+ async function missingBlobs(
353
+ ctx: EngineContext,
354
+ repository: string,
355
+ blobs: readonly Descriptor[],
356
+ ): Promise<string[]> {
357
+ const digests = [...new Set(blobs.map((b) => b.digest))];
358
+ const missing: string[] = [];
359
+ for (let i = 0; i < digests.length; i += 100) {
360
+ const res = await ctx.clients.ecr.send(
361
+ new BatchCheckLayerAvailabilityCommand({
362
+ repositoryName: repository,
363
+ layerDigests: digests.slice(i, i + 100),
364
+ }),
365
+ );
366
+ const available = new Set(
367
+ (res.layers ?? []).filter((l) => l.layerAvailability === 'AVAILABLE').map((l) => l.layerDigest),
368
+ );
369
+ for (const d of digests.slice(i, i + 100)) if (!available.has(d)) missing.push(d);
370
+ }
371
+ return missing;
372
+ }
373
+
374
+ /** Upload one blob in the part size ECR asks for. ECR checks the digest on completion. */
375
+ export async function uploadBlob(
376
+ ctx: EngineContext,
377
+ repository: string,
378
+ bytes: Uint8Array,
379
+ digest: string,
380
+ ): Promise<void> {
381
+ const ecr = ctx.clients.ecr;
382
+ const init = await ecr.send(new InitiateLayerUploadCommand({ repositoryName: repository }));
383
+ const partSize = init.partSize || 10 * 1024 * 1024;
384
+ for (let first = 0; first < bytes.length; first += partSize) {
385
+ const end = Math.min(first + partSize, bytes.length);
386
+ await ecr.send(
387
+ new UploadLayerPartCommand({
388
+ repositoryName: repository,
389
+ uploadId: init.uploadId,
390
+ partFirstByte: first,
391
+ partLastByte: end - 1,
392
+ layerPartBlob: bytes.subarray(first, end),
393
+ }),
394
+ );
395
+ }
396
+ try {
397
+ await ecr.send(
398
+ new CompleteLayerUploadCommand({
399
+ repositoryName: repository,
400
+ uploadId: init.uploadId,
401
+ layerDigests: [digest],
402
+ }),
403
+ );
404
+ } catch (e) {
405
+ // Uploaded concurrently by another deploy: the blob is there either way.
406
+ if (errorName(e) !== 'LayerAlreadyExistsException') throw e;
407
+ }
408
+ }
409
+
410
+ /** Write a manifest under a tag; returns its digest. Writing the same manifest and tag again is fine. */
411
+ async function putImage(
412
+ ctx: EngineContext,
413
+ spec: { repository: string; manifest: string; mediaType: string; tag: string },
414
+ ): Promise<string> {
415
+ try {
416
+ const res = await ctx.clients.ecr.send(
417
+ new PutImageCommand({
418
+ repositoryName: spec.repository,
419
+ imageManifest: spec.manifest,
420
+ imageManifestMediaType: spec.mediaType,
421
+ imageTag: spec.tag,
422
+ }),
423
+ );
424
+ return res.image?.imageId?.imageDigest ?? sha256Digest(new TextEncoder().encode(spec.manifest));
425
+ } catch (e) {
426
+ if (errorName(e) !== 'ImageAlreadyExistsException') throw e;
427
+ return sha256Digest(new TextEncoder().encode(spec.manifest));
428
+ }
429
+ }
430
+
431
+ /**
432
+ * A blob's bytes. ECR hands out a short-lived download URL; it is fetched
433
+ * with the ECR client's own HTTP handler so the emulator's TLS settings apply.
434
+ */
435
+ async function readBlob(ctx: EngineContext, repository: string, digest: string): Promise<Uint8Array> {
436
+ const ecr = ctx.clients.ecr;
437
+ const { downloadUrl } = await ecr.send(
438
+ new GetDownloadUrlForLayerCommand({ repositoryName: repository, layerDigest: digest }),
439
+ );
440
+ if (!downloadUrl) throw new Error(`ECR returned no download URL for ${digest}`);
441
+ const url = new URL(downloadUrl);
442
+ const res = await sendRaw(ecr, {
443
+ method: 'GET',
444
+ protocol: url.protocol,
445
+ hostname: url.hostname,
446
+ ...(url.port ? { port: Number(url.port) } : {}),
447
+ path: url.pathname,
448
+ query: Object.fromEntries(url.searchParams),
449
+ headers: { host: url.host },
450
+ });
451
+ const bytes = res.body;
452
+ if (res.statusCode !== 200)
453
+ throw new Error(`downloading ${digest} from ${repository} failed (${res.statusCode})`);
454
+ if (sha256Digest(bytes) !== digest)
455
+ throw new Error(`blob ${digest} in ${repository} doesn't match its digest`);
456
+ return bytes;
457
+ }