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

main
ts 209 lines 7.33 KB
Raw
1 import {
2 makeContainerImageSource,
3 type ImageRegistryTarget,
4 type ImageSourceLike,
5 } from "@alchemy.run/docker/ImageSource";
6 import * as ecr from "@distilled.cloud/aws/ecr";
7 import * as Effect from "effect/Effect";
8 import { roleHostBundle } from "../AWSBindings.ts";
9 import { getEcrRegistryCredentials } from "./Image.ts";
10
11 /**
12 * INTERNAL — the ECR target for the shared container image-source machinery
13 * ([Docker/ImageSource.ts](../../Docker/ImageSource.ts)), used by the AWS
14 * container platforms (`AWS.ECS.Task`, `AWS.ECS.Service`, `AWS.EKS.*`).
15 *
16 * NOT exported from the AWS barrel or `ECR/index.ts`. Consumers import the
17 * module path directly.
18 *
19 * Every source lands in an auto-created (caller-named) private ECR
20 * repository so the compute platform pulls from a registry that is reliable
21 * from private VPCs and IAM-authenticated.
22 */
23
24 export {
25 computeStaticSourceHash,
26 imageSourceKind,
27 validateImageSource,
28 type BundledImageSource,
29 type DockerfileImageSource,
30 type ImageSourceKind,
31 type ImageSourceLike,
32 type ImageSourceProps,
33 type RegistryImageSource,
34 } from "@alchemy.run/docker/ImageSource";
35
36 /** The resolved (built/mirrored + pushed) image. */
37 export interface ResolvedImage {
38 /** Full image reference, `<repositoryUri>:<codeHash>`. */
39 imageUri: string;
40 /** Name of the ECR repository the image was pushed to. */
41 repositoryName: string;
42 /** URI of the ECR repository the image was pushed to. */
43 repositoryUri: string;
44 /** Content hash identifying the image (also the image tag). */
45 codeHash: string;
46 }
47
48 export interface ResolveImageOptions {
49 /** Logical resource id — keys the stable build-context directory. */
50 id: string;
51 /**
52 * The props bag carrying the image source fields (`main` / `context` /
53 * `image` plus their modifiers).
54 */
55 source: ImageSourceLike;
56 /** Name of the ECR repository to (auto-create and) push into. */
57 repositoryName: string;
58 /**
59 * Known repository URI (from prior Attributes). When provided, repository
60 * creation is skipped.
61 */
62 repositoryUri?: string;
63 /** Tags applied to the auto-created repository. */
64 tags?: Record<string, string>;
65 /**
66 * Target image platform.
67 * @default "linux/amd64"
68 */
69 platform?: string;
70 /**
71 * Port the generated Dockerfile should `ENV PORT=` + `EXPOSE`
72 * (`main` source only).
73 */
74 port?: number;
75 /**
76 * True when the resource was declared without an inline Effect impl —
77 * `main` is then bundled as-is without the virtual-entry bootstrap.
78 */
79 isExternal?: boolean;
80 /**
81 * The virtual-entry bootstrap wrapped around `main` for Effect-native
82 * programs: receives the resolved entry import path and returns the
83 * generated entry module source. Platform-specific (server vs one-shot
84 * differ per platform), so the caller supplies it.
85 */
86 bootstrap: (importPath: string) => string;
87 /** Plan-status session used to emit build/push progress notes. */
88 session: { note: (message: string) => Effect.Effect<void> };
89 }
90
91 /**
92 * The generated entry for `AWS.ECS.Task` / `AWS.ECS.Service` containers: a
93 * shim importing only `@alchemy.run/aws/Bootstrap/Ecs` (resolvable from any
94 * consumer — `alchemy` is its direct dependency) plus the user's `main`.
95 * Everything the runtime needs lives in that real module, so the virtual
96 * entry never imports alchemy's own dependencies (`@distilled.cloud/*`,
97 * `@effect/platform-bun`), which an isolated install cannot resolve from
98 * the consumer's project.
99 */
100 export const makeBunBootstrap =
101 (handler: string) =>
102 (importPath: string): string =>
103 `
104 import { bootstrap } from "@alchemy.run/aws/Bootstrap/Ecs";
105 import { ${handler} as entrypoint } from ${JSON.stringify(importPath)};
106
107 await bootstrap(entrypoint);
108 `;
109
110 /**
111 * An ECR image runs on ECS or EKS, as an IAM role, so a bundled `main` is
112 * built with {@link roleHostBundle}.
113 */
114 const onRoleHost = <S extends ImageSourceLike>(source: S): S =>
115 source.main === undefined
116 ? source
117 : { ...source, build: { ...source.build, input: roleHostBundle(source.build?.input ?? {}) } };
118
119 /**
120 * Init-time constructor for the ECR image-source resolver: the shared
121 * container image pipeline pushing into an auto-created ECR repository.
122 */
123 export const makeImageSource = Effect.gen(function* () {
124 const images = yield* makeContainerImageSource;
125
126 /**
127 * Ensure the target ECR repository exists. Idempotent: tolerates
128 * `RepositoryAlreadyExistsException` as a race / re-run and re-describes.
129 */
130 const ensureRepository = Effect.fn(function* (options: {
131 repositoryName: string;
132 tags?: Record<string, string>;
133 }) {
134 const created = yield* ecr
135 .createRepository({
136 repositoryName: options.repositoryName,
137 imageTagMutability: "MUTABLE",
138 imageScanningConfiguration: { scanOnPush: true },
139 tags: Object.entries(options.tags ?? {}).map(([Key, Value]) => ({ Key, Value })),
140 })
141 .pipe(
142 Effect.catchTag("RepositoryAlreadyExistsException", () =>
143 Effect.gen(function* () {
144 const existing = yield* ecr.describeRepositories({
145 repositoryNames: [options.repositoryName],
146 });
147 return { repository: existing.repositories?.[0] };
148 }),
149 ),
150 );
151 const repository = created.repository;
152 if (!repository?.repositoryUri) {
153 return yield* Effect.die(
154 new Error(`Failed to resolve ECR repository '${options.repositoryName}'`),
155 );
156 }
157 return repository.repositoryUri;
158 });
159
160 /** Observe a pushed tag in ECR. Missing repository or tag → false. */
161 const hasTag = (repositoryName: string) =>
162 Effect.fn(function* (imageTag: string) {
163 const described = yield* ecr
164 .describeImages({ repositoryName, imageIds: [{ imageTag }] })
165 .pipe(
166 Effect.catchTag(
167 ["ImageNotFoundException", "RepositoryNotFoundException"],
168 () => Effect.undefined,
169 ),
170 );
171 return described?.imageDetails?.[0] !== undefined;
172 });
173
174 /**
175 * Resolve the image for a props bag: ensure the repository, compute the
176 * content-addressed tag, then build/mirror + push only when that exact
177 * tag is not already in ECR (crash-safe convergence).
178 */
179 const resolve = Effect.fn(function* (options: ResolveImageOptions) {
180 const target = {
181 repositoryUri:
182 options.repositoryUri !== undefined
183 ? Effect.succeed(options.repositoryUri)
184 : ensureRepository({ repositoryName: options.repositoryName, tags: options.tags }),
185 hasTag: hasTag(options.repositoryName),
186 credentials: getEcrRegistryCredentials,
187 } satisfies ImageRegistryTarget<any>;
188 const resolved = yield* images.resolve(
189 { ...options, source: onRoleHost(options.source) },
190 target,
191 );
192 return {
193 imageUri: resolved.imageUri,
194 repositoryName: options.repositoryName,
195 repositoryUri: resolved.repositoryUri,
196 codeHash: resolved.codeHash,
197 } satisfies ResolvedImage;
198 });
199
200 const hash = (options: Parameters<typeof images.hash>[0]) =>
201 images.hash({ ...options, source: onRoleHost(options.source) });
202 const watchMain = (options: Parameters<typeof images.watchMain>[0]) =>
203 images.watchMain({ ...options, source: onRoleHost(options.source) });
204
205 return { resolve, hash, watchMain };
206 });
207
208 /** The resolver service returned by {@link makeImageSource}. */
209 export interface ImageSource extends Effect.Success<typeof makeImageSource> {}