@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 632 lines 24.4 KB
Raw
1 import type { ValidationException } from "@distilled.cloud/aws/Errors";
2 import * as microvms from "@distilled.cloud/aws/lambda-microvms";
3 import * as Artifacts from "alchemy/Artifacts";
4 import { isResolved } from "alchemy/Diff";
5 import type { Input, InputProps } from "alchemy/Input";
6 import { createPhysicalName } from "alchemy/PhysicalName";
7 import * as Provider from "alchemy/Provider";
8 import type { ScopedPlanStatusSession } from "alchemy/Report";
9 import { createInternalTags, diffTags } from "alchemy/Tags";
10 import { sha256 } from "alchemy/Util/sha256";
11 import * as Data from "effect/Data";
12 import * as Effect from "effect/Effect";
13 import * as FileSystem from "effect/FileSystem";
14 import * as Path from "effect/Path";
15 import * as Redacted from "effect/Redacted";
16 import * as Schedule from "effect/Schedule";
17 import * as Stream from "effect/Stream";
18 import { Assets } from "../Assets.ts";
19 import {
20 buildMicrovmDockerfile,
21 bundleMicrovmProgram,
22 DEFAULT_MICROVM_PORT,
23 readContextDirectory,
24 zipFiles,
25 } from "./MicrovmBundle.ts";
26 import { MicrovmImage, type MicrovmImageProps } from "./MicrovmImage.ts";
27
28 // Fold the `env` map (user-provided + capability-binding contributions) into the
29 // MicroVM API's `environmentVariables` (a `Record<string, string>`). Redacted
30 // values are unwrapped; non-string values are JSON-encoded.
31 const foldEnv = (env: Record<string, any> | undefined): Record<string, string> | undefined => {
32 if (!env) return undefined;
33 const out: Record<string, string> = {};
34 for (const [key, value] of Object.entries(env)) {
35 if (value === undefined) continue;
36 const v = Redacted.isRedacted(value) ? Redacted.value(value) : value;
37 out[key] = typeof v === "string" ? v : JSON.stringify(v);
38 }
39 return Object.keys(out).length > 0 ? out : undefined;
40 };
41
42 const READY_STATES = new Set<string>(["CREATED", "UPDATED"]);
43 const FAILED_STATES = new Set<string>(["CREATE_FAILED", "UPDATE_FAILED", "DELETE_FAILED"]);
44
45 const toIso = (value: Date | string | undefined): string | undefined =>
46 value instanceof Date ? value.toISOString() : value;
47
48 // Resolve `buildRole` / `baseImage` (each a string ARN or a materialized
49 // resource reference) to a plain ARN string. The engine materializes a
50 // whole-resource prop into its stable attributes (see Plan.ts `resolveInput`),
51 // so the instance's `.roleArn` / `.imageArn` is a plain string at reconcile.
52 const resolveBuildRoleArn = (news: MicrovmImageProps): string | undefined =>
53 news.buildRole === undefined
54 ? undefined
55 : typeof news.buildRole === "string"
56 ? news.buildRole
57 : (news.buildRole.roleArn as unknown as string);
58
59 const resolveBaseImageArn = (news: MicrovmImageProps): string | undefined =>
60 news.baseImage === undefined
61 ? undefined
62 : typeof news.baseImage === "string"
63 ? news.baseImage
64 : (news.baseImage.imageArn as unknown as string);
65
66 // Properties (besides the artifact content) that affect the built image.
67 const buildPropsIdentity = (news: MicrovmImageProps) =>
68 JSON.stringify({
69 baseImageArn: resolveBaseImageArn(news) ?? null,
70 baseImageVersion: news.baseImageVersion ?? null,
71 description: news.description ?? null,
72 logging: news.logging ?? null,
73 egressNetworkConnectors: [...(news.egressNetworkConnectors ?? [])].sort(),
74 cpuConfigurations: news.cpuConfigurations ?? [],
75 resources: news.resources ?? [],
76 additionalOsCapabilities: [...(news.additionalOsCapabilities ?? [])].sort(),
77 hooks: news.hooks ?? null,
78 env: news.env ?? {},
79 });
80
81 interface ResolvedArtifact {
82 uri: string;
83 hash: string;
84 contentHash: string;
85 }
86
87 /**
88 * The content half of an image's artifact identity, before any upload: the
89 * bundled program (or packaged context) plus the hash that names THAT —
90 * independent of the props, which fold into the full `hash` later.
91 */
92 type ArtifactContent = {
93 /** Stored on the attrs; compared by `diff`. */
94 readonly contentHash: string;
95 /**
96 * The raw content identity the full `hash` is derived from — kept
97 * separate so that formula stays byte-identical to what deployed images
98 * already carry (`sha256(identity + ":" + propsId)`).
99 */
100 readonly identity: string;
101 } & ({ readonly archive: Uint8Array } | { readonly uri: string });
102
103 /** The props that decide what the artifact's CONTENT is. */
104 type ContentInputs = Pick<
105 MicrovmImageProps,
106 | "main"
107 | "context"
108 | "codeArtifact"
109 | "runtime"
110 | "port"
111 | "dockerfile"
112 | "isExternal"
113 | "external"
114 | "build"
115 >;
116
117 /**
118 * Pick the content inputs off the plan-time props, or `undefined` when they
119 * cannot be read yet. At plan time the props may be unresolved — the build
120 * role, env, … are Outputs, and the whole object may itself be an
121 * Output/Effect/Config — so only a plain object whose content inputs have
122 * all resolved qualifies.
123 */
124 const resolvedContentInputs = (news: Input<MicrovmImageProps>): ContentInputs | undefined => {
125 if (typeof news !== "object" || news === null) return undefined;
126 const n = news as InputProps<MicrovmImageProps>;
127 const picked: Input<ContentInputs> = {
128 main: n.main,
129 context: n.context,
130 codeArtifact: n.codeArtifact,
131 runtime: n.runtime,
132 port: n.port,
133 dockerfile: n.dockerfile,
134 isExternal: n.isExternal,
135 external: n.external,
136 build: n.build,
137 };
138 if (!isResolved(picked)) return undefined;
139 // `isResolved` has verified every field; the cast only re-states that
140 // for a type the guard cannot express on a mapped `Input<…>` object.
141 const resolved = picked as ContentInputs;
142 // An Effect/Config-shaped props object has none of these set.
143 if (!resolved.main && !resolved.context && !resolved.codeArtifact?.uri) {
144 return undefined;
145 }
146 return resolved;
147 };
148
149 const resolveName = (id: string, name?: string) =>
150 name ? Effect.succeed(name) : createPhysicalName({ id, maxLength: 64, delimiter: "-" });
151
152 // `getMicrovmImage` requires an ARN or ID — it rejects a plain name with a
153 // `ValidationException` ("Invalid ARN format"). Only call it with an
154 // ARN/ID.
155 const getImage = (identifier: string) =>
156 microvms
157 .getMicrovmImage({ imageIdentifier: identifier })
158 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
159
160 // Look an image up by its (name-only) identifier via the name filter, since
161 // `getMicrovmImage` won't accept a name. Returns the full image or undefined.
162 const findImageByName = Effect.fn(function* (name: string) {
163 const summaries = yield* microvms.listMicrovmImages.items({ nameFilter: name }).pipe(
164 Stream.runCollect,
165 Effect.map((chunk) => Array.from(chunk)),
166 );
167 const match = summaries.find((summary) => summary.name === name);
168 return match ? yield* getImage(match.imageArn) : undefined;
169 });
170
171 const defaultBaseImageArn = Effect.fn(function* () {
172 const items = yield* microvms.listManagedMicrovmImages.items({}).pipe(
173 Stream.runCollect,
174 Effect.map((c) => Array.from(c)),
175 );
176 const base = items.find((i) => i.imageArn.includes("al2023")) ?? items[0];
177 if (!base) {
178 return yield* Effect.die("No managed MicroVM base images available; set `baseImage`.");
179 }
180 return base.imageArn;
181 });
182
183 /**
184 * Bundle (or package) the image's code and hash the result. Nothing is
185 * uploaded here and no prop outside {@link contentInputs} is read: `diff`
186 * calls this before the props have resolved (the build role is an Output
187 * at plan time) to see a content-only edit of the in-VM program, and
188 * `reconcile` calls it again for the archive to upload. Memoized per
189 * resource for the run so a diff→reconcile cycle bundles once.
190 */
191 const artifactContent = (
192 id: string,
193 news: ContentInputs,
194 note: (message: string) => Effect.Effect<void>,
195 ) =>
196 Effect.gen(function* () {
197 if (news.main) {
198 const runtime = news.runtime ?? "node";
199 const port = news.port ?? DEFAULT_MICROVM_PORT;
200 yield* note("Bundling MicroVM program...");
201 const { files, hash: bundleHash } = yield* bundleMicrovmProgram({
202 main: news.main,
203 runtime,
204 isExternal: news.isExternal ?? false,
205 external: news.external,
206 port,
207 build: news.build,
208 });
209 const dockerfile = buildMicrovmDockerfile(news.dockerfile, runtime, port, {
210 sourceMaps: files.some((f) => f.path.endsWith(".map")),
211 });
212 const identity = `${bundleHash}:${dockerfile}`;
213 const contentHash = yield* sha256(identity);
214 const archive = yield* zipFiles([{ path: "Dockerfile", content: dockerfile }, ...files]);
215 return { contentHash, identity, archive } satisfies ArtifactContent;
216 }
217
218 if (news.context) {
219 const path = yield* Path.Path;
220 const fs = yield* FileSystem.FileSystem;
221 yield* note("Packaging MicroVM build context...");
222 const files = yield* readContextDirectory(news.context);
223 // Ensure a Dockerfile is present (resolve from `dockerfile` path or default).
224 const dockerfileName = news.dockerfile ?? "Dockerfile";
225 const hasDockerfile = files.some((f) => f.path === dockerfileName);
226 if (!hasDockerfile) {
227 const dockerfilePath = path.join(news.context, dockerfileName);
228 const content = yield* fs
229 .readFile(dockerfilePath)
230 .pipe(Effect.orElseSucceed(() => undefined));
231 if (content) files.push({ path: "Dockerfile", content });
232 }
233 // Hash the BYTES, not `path:byteLength` — a same-length edit (a
234 // flipped version string, a swapped constant) must count as a change.
235 const contentId = (yield* Effect.forEach(
236 [...files].sort((a, b) => (a.path < b.path ? -1 : 1)),
237 (f) => Effect.map(sha256(f.content), (hash) => `${f.path}:${hash}`),
238 )).join("|");
239 const archive = yield* zipFiles(files);
240 return {
241 contentHash: yield* sha256(contentId),
242 identity: contentId,
243 archive,
244 } satisfies ArtifactContent;
245 }
246
247 if (news.codeArtifact?.uri) {
248 const uri: string = news.codeArtifact.uri;
249 return { contentHash: yield* sha256(uri), identity: uri, uri } satisfies ArtifactContent;
250 }
251
252 return yield* Effect.die(
253 "MicrovmImage requires one of `main`, `context`, or `codeArtifact.uri`.",
254 );
255 }).pipe(
256 // Re-widen: inference normalizes the object-literal union (adding
257 // `uri?: undefined`), which defeats `"uri" in content` narrowing.
258 Effect.map((content): ArtifactContent => content),
259 Artifacts.cached(`microvm-image-content:${id}`),
260 );
261
262 // Materialize + upload the code artifact and compute its build identity hash
263 // (content + props). The `hash` formulas are unchanged from before
264 // `contentHash` existed, so images deployed earlier are not rebuilt once.
265 const resolveArtifact = Effect.fn(function* (
266 id: string,
267 news: MicrovmImageProps,
268 session: ScopedPlanStatusSession,
269 ) {
270 const propsId = buildPropsIdentity(news);
271 const content = yield* artifactContent(id, news, session.note);
272 const hash = yield* sha256(`${content.identity}:${propsId}`);
273 if ("uri" in content) {
274 return { uri: content.uri, hash, contentHash: content.contentHash } satisfies ResolvedArtifact;
275 }
276 const assets = yield* Assets;
277 const key = yield* assets.uploadAsset(hash, content.archive);
278 const bucket = yield* assets.bucketName;
279 return {
280 uri: `s3://${bucket}/${key}`,
281 hash,
282 contentHash: content.contentHash,
283 } satisfies ResolvedArtifact;
284 });
285
286 const toAttrs = (
287 image: microvms.GetMicrovmImageOutput,
288 artifact?: ResolvedArtifact,
289 ): MicrovmImage["Attributes"] => ({
290 imageArn: image.imageArn,
291 name: image.name,
292 state: image.state,
293 imageVersion: image.latestActiveImageVersion ?? image.latestFailedImageVersion,
294 latestActiveImageVersion: image.latestActiveImageVersion,
295 latestFailedImageVersion: image.latestFailedImageVersion,
296 createdAt: toIso(image.createdAt),
297 updatedAt: toIso(image.updatedAt),
298 codeArtifact: artifact
299 ? { uri: artifact.uri, hash: artifact.hash, contentHash: artifact.contentHash }
300 : undefined,
301 });
302
303 const requireBuildRole = (news: MicrovmImageProps) => {
304 const arn = resolveBuildRoleArn(news);
305 return arn
306 ? Effect.succeed(arn)
307 : Effect.die("MicrovmImage requires `buildRole` to build the image.");
308 };
309
310 const createImage = Effect.fn(function* (
311 name: string,
312 news: MicrovmImageProps,
313 artifact: ResolvedArtifact,
314 baseImageArn: string,
315 desiredTags: Record<string, string>,
316 session: ScopedPlanStatusSession,
317 ) {
318 const buildRoleArn = yield* requireBuildRole(news);
319 yield* session.note(`Creating MicroVM image ${name}...`);
320 const created = yield* microvms
321 .createMicrovmImage({
322 name,
323 baseImageArn,
324 baseImageVersion: news.baseImageVersion,
325 buildRoleArn,
326 codeArtifact: { uri: artifact.uri },
327 description: news.description,
328 logging: news.logging,
329 egressNetworkConnectors: news.egressNetworkConnectors,
330 cpuConfigurations: news.cpuConfigurations,
331 resources: news.resources,
332 additionalOsCapabilities: news.additionalOsCapabilities,
333 hooks: news.hooks,
334 environmentVariables: foldEnv(news.env),
335 tags: desiredTags,
336 })
337 .pipe(
338 Effect.catchTag("ConflictException", () =>
339 getImage(name).pipe(
340 Effect.flatMap((existing) =>
341 existing
342 ? Effect.succeed({ imageArn: existing.imageArn })
343 : Effect.die(`MicroVM image ${name} conflicted but was not found.`),
344 ),
345 ),
346 ),
347 );
348 return yield* waitForReady(created.imageArn, session);
349 });
350
351 const updateImage = Effect.fn(function* (
352 imageArn: string,
353 news: MicrovmImageProps,
354 artifact: ResolvedArtifact,
355 baseImageArn: string,
356 session: ScopedPlanStatusSession,
357 ) {
358 const buildRoleArn = yield* requireBuildRole(news);
359 yield* session.note(`Updating MicroVM image ${news.name ?? imageArn}...`);
360 const updated = yield* microvms.updateMicrovmImage({
361 imageIdentifier: imageArn,
362 baseImageArn,
363 baseImageVersion: news.baseImageVersion,
364 buildRoleArn,
365 codeArtifact: { uri: artifact.uri },
366 description: news.description,
367 logging: news.logging,
368 egressNetworkConnectors: news.egressNetworkConnectors,
369 cpuConfigurations: news.cpuConfigurations,
370 resources: news.resources,
371 additionalOsCapabilities: news.additionalOsCapabilities,
372 hooks: news.hooks,
373 environmentVariables: foldEnv(news.env),
374 });
375 return yield* waitForReady(updated.imageArn, session);
376 });
377
378 const syncTags = Effect.fn(function* (
379 imageArn: string,
380 observedTags: Record<string, string>,
381 desiredTags: Record<string, string>,
382 ) {
383 const { removed, upsert } = diffTags(observedTags, desiredTags);
384 if (removed.length > 0) {
385 yield* microvms.untagResource({ Resource: imageArn, TagKeys: removed });
386 }
387 if (upsert.length > 0) {
388 yield* microvms.tagResource({
389 Resource: imageArn,
390 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
391 });
392 }
393 });
394
395 export const MicrovmImageProvider = () =>
396 Provider.succeed(MicrovmImage, {
397 stables: ["imageArn", "name"],
398
399 diff: Effect.fn(function* ({ id, olds, news, output }) {
400 // A content-only edit of the in-VM program changes none of the props,
401 // so the engine's structural diff would call it a noop and the image
402 // would never rebuild. Bundle (memoized for the run) and compare the
403 // CONTENT hash, exactly as the Lambda Function diff does. This runs
404 // before the props resolve — the build role is an Output at plan
405 // time — which is fine because only the plain content inputs are
406 // read. Rows persisted before `contentHash` existed skip the check
407 // until their next reconcile stamps it.
408 const previousContentHash = output?.codeArtifact?.contentHash;
409 const content = resolvedContentInputs(news);
410 if (previousContentHash !== undefined && content !== undefined) {
411 const { contentHash } = yield* artifactContent(id, content, () => Effect.void);
412 if (contentHash !== previousContentHash) {
413 return { action: "update" } as const;
414 }
415 }
416 if (!isResolved(news)) return;
417 const oldName = yield* resolveName(id, olds.name);
418 const newName = yield* resolveName(id, news.name);
419 if (oldName !== newName) {
420 return { action: "replace" } as const;
421 }
422 }),
423
424 read: Effect.fn(function* ({ id, olds, output }) {
425 // Prefer the cached ARN; otherwise look up by name (getMicrovmImage
426 // rejects names).
427 const image = output?.imageArn
428 ? yield* getImage(output.imageArn)
429 : yield* findImageByName(output?.name ?? (yield* resolveName(id, olds?.name)));
430 return image
431 ? toAttrs(image, output?.codeArtifact as ResolvedArtifact | undefined)
432 : undefined;
433 }),
434
435 list: () =>
436 Effect.gen(function* () {
437 const summaries = yield* microvms.listMicrovmImages.items({}).pipe(
438 Stream.runCollect,
439 Effect.map((chunk) => Array.from(chunk)),
440 );
441 const images = yield* Effect.forEach(summaries, (summary) => getImage(summary.imageArn), {
442 concurrency: 10,
443 });
444 return images.flatMap((image) => (image ? [toAttrs(image)] : []));
445 }),
446
447 reconcile: Effect.fn(function* ({ id, news, output, session }) {
448 const name = yield* resolveName(id, news.name);
449 const internalTags = yield* createInternalTags(id);
450 const desiredTags = { ...internalTags, ...news.tags };
451 const baseImageArn = resolveBaseImageArn(news) ?? (yield* defaultBaseImageArn());
452
453 // Resolve + upload the artifact and compute its build identity.
454 const artifact = yield* resolveArtifact(id, news, session);
455
456 // Observe — prefer the cached ARN; otherwise look up by name (a name
457 // is not a valid `getMicrovmImage` identifier).
458 const observed = output?.imageArn
459 ? yield* getImage(output.imageArn)
460 : yield* findImageByName(name);
461
462 // Ensure + sync: rebuild only when the build identity changed.
463 const image = !observed
464 ? yield* createImage(name, news, artifact, baseImageArn, desiredTags, session)
465 : output?.codeArtifact?.hash === artifact.hash
466 ? observed
467 : yield* updateImage(observed.imageArn, news, artifact, baseImageArn, session);
468
469 yield* syncTags(image.imageArn, (image.tags ?? {}) as Record<string, string>, desiredTags);
470
471 yield* session.note(`MicroVM image ${name} is ${image.state}`);
472 return toAttrs(image, artifact);
473 }),
474
475 delete: Effect.fn(function* ({ output, session }) {
476 // An image can't be deleted while it still has MicroVMs running — tear
477 // them down first and wait for them to disappear.
478 yield* terminateRunningMicrovms(output.imageArn, session);
479 yield* session.note(`Deleting MicroVM image ${output.name}...`);
480
481 yield* microvms.deleteMicrovmImage({ imageIdentifier: output.imageArn }).pipe(
482 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
483 // A MicroVM caught mid-termination still blocks the delete; retry
484 // briefly until the instances are fully gone.
485 Effect.retry({
486 while: (e): e is ValidationException =>
487 e._tag === "ValidationException" && e.message.includes("running MicroVMs"),
488 schedule: Schedule.max([Schedule.fixed(5_000), Schedule.recurs(12)]),
489 }),
490 );
491 yield* waitForDeleted(output.imageArn, session);
492 }),
493 });
494
495 class ImageBuilding extends Data.TaggedError("ImageBuilding")<{
496 imageArn: string;
497 state: string;
498 }> {}
499
500 class ImageFailed extends Data.TaggedError("ImageFailed")<{
501 imageArn: string;
502 state: string;
503 reason?: string;
504 }> {}
505
506 class MicrovmsActive extends Data.TaggedError("MicrovmsActive")<{ count: number }> {}
507
508 // MicroVM states that still hold a slot on the image and block its deletion.
509 const ACTIVE_MICROVM_STATES = new Set<string>(["PENDING", "RUNNING", "SUSPENDING", "SUSPENDED"]);
510
511 const listActiveMicrovms = (imageArn: string) =>
512 microvms.listMicrovms.items({ imageIdentifier: imageArn }).pipe(
513 Stream.runCollect,
514 Effect.map((chunk) => Array.from(chunk).filter((m) => ACTIVE_MICROVM_STATES.has(m.state))),
515 Effect.catchTag("ResourceNotFoundException", () =>
516 Effect.succeed([] as microvms.MicrovmItem[]),
517 ),
518 );
519
520 // Terminate every running MicroVM launched from this image and wait until none
521 // remain active — a prerequisite for deleting the image.
522 const terminateRunningMicrovms = Effect.fn(function* (
523 imageArn: string,
524 session: ScopedPlanStatusSession,
525 ) {
526 const active = yield* listActiveMicrovms(imageArn);
527 if (active.length === 0) return;
528 yield* session.note(`Terminating ${active.length} running MicroVM(s)...`);
529 yield* Effect.forEach(
530 active,
531 (m) =>
532 microvms.terminateMicrovm({ microvmIdentifier: m.microvmId }).pipe(
533 // Already gone or mid-transition — the wait below converges anyway.
534 Effect.catchTag(
535 ["ResourceNotFoundException", "ConflictException", "ValidationException"],
536 () => Effect.void,
537 ),
538 ),
539 { concurrency: 5, discard: true },
540 );
541 yield* listActiveMicrovms(imageArn).pipe(
542 Effect.flatMap((remaining) =>
543 remaining.length === 0 ? Effect.void : new MicrovmsActive({ count: remaining.length }),
544 ),
545 Effect.retry({
546 while: (e) => e._tag === "MicrovmsActive",
547 schedule: Schedule.max([Schedule.fixed(5_000), Schedule.recurs(24)]).pipe(
548 Schedule.tap(() => session.note("Waiting for MicroVMs to terminate...")),
549 ),
550 }),
551 );
552 });
553
554 // Drill into the failed version's `stateReason` (and per-architecture build
555 // state reasons) so a build failure surfaces an actionable message instead of
556 // just `CREATE_FAILED`.
557 const buildFailureReason = Effect.fn(function* (
558 imageArn: string,
559 imageVersion: string | undefined,
560 ) {
561 if (!imageVersion) return undefined;
562 const version = yield* microvms
563 .getMicrovmImageVersion({ imageIdentifier: imageArn, imageVersion })
564 .pipe(Effect.orElseSucceed(() => undefined));
565 // A version fans out to one build per architecture/chipset; report the reason
566 // from each build that actually FAILED (keyed by architecture so multi-platform
567 // failures are distinguishable). `buildState` is the reliable signal — don't
568 // guess via timestamps.
569 const builds = yield* microvms.listMicrovmImageBuilds
570 .items({ imageIdentifier: imageArn, imageVersion })
571 .pipe(
572 Stream.runCollect,
573 Effect.map((chunk) => Array.from(chunk)),
574 Effect.orElseSucceed(() => [] as microvms.MicrovmImageBuildSummary[]),
575 );
576 const failedBuildReasons = builds
577 .filter((b) => b.buildState === "FAILED" && b.stateReason)
578 .map((b) => `${b.architecture}: ${b.stateReason}`);
579 // Prefer the per-build failure reasons; fall back to the version-level reason.
580 const reasons =
581 failedBuildReasons.length > 0
582 ? [...new Set(failedBuildReasons)]
583 : [version?.stateReason].filter((r): r is string => !!r);
584 return reasons.join("; ");
585 });
586
587 const waitForReady = (imageArn: string, session: ScopedPlanStatusSession) =>
588 Effect.gen(function* () {
589 const image = yield* microvms.getMicrovmImage({ imageIdentifier: imageArn });
590 if (READY_STATES.has(image.state)) return image;
591 if (FAILED_STATES.has(image.state)) {
592 const reason = yield* buildFailureReason(imageArn, image.latestFailedImageVersion);
593 yield* session.note(
594 `MicroVM image build ${image.state}: ${reason ?? "(no reason reported)"}`,
595 );
596 yield* Effect.logError(
597 `MicroVM image ${imageArn} build ${image.state}: ${reason ?? "(no reason reported)"}`,
598 );
599 return yield* new ImageFailed({ imageArn, state: image.state, reason });
600 }
601 return yield* new ImageBuilding({ imageArn, state: image.state });
602 }).pipe(
603 Effect.retry({
604 while: (e) => e._tag === "ImageBuilding",
605 schedule: Schedule.max([Schedule.fixed(10_000), Schedule.recurs(72)]).pipe(
606 Schedule.tap(({ attempt }) =>
607 session.note(`Waiting for MicroVM image build... (${attempt * 10}s)`),
608 ),
609 ),
610 }),
611 );
612
613 const waitForDeleted = (imageArn: string, session: ScopedPlanStatusSession) =>
614 Effect.gen(function* () {
615 const image = yield* microvms
616 .getMicrovmImage({ imageIdentifier: imageArn })
617 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
618 if (!image || image.state === "DELETED") return;
619 if (image.state === "DELETE_FAILED") {
620 return yield* new ImageFailed({ imageArn, state: image.state });
621 }
622 return yield* new ImageBuilding({ imageArn, state: image.state });
623 }).pipe(
624 Effect.retry({
625 while: (e) => e._tag === "ImageBuilding",
626 schedule: Schedule.max([Schedule.fixed(10_000), Schedule.recurs(72)]).pipe(
627 Schedule.tap(({ attempt }) =>
628 session.note(`Waiting for MicroVM image deletion... (${attempt * 10}s)`),
629 ),
630 ),
631 }),
632 );