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

main
ts 252 lines 9.33 KB
Raw
1 import { AlchemyContext } from "alchemy/AlchemyContext";
2 import * as Bundle from "alchemy/Bundle/Bundle";
3 import { findCwdForBundle, getStableContextDir, resolveMainPath } from "alchemy/Bundle/TempRoot";
4 import { sha256Object } from "alchemy/Util/sha256";
5 import * as Effect from "effect/Effect";
6 import type * as rolldown from "rolldown";
7 import { Docker } from "./Docker.ts";
8
9 /**
10 * INTERNAL — image machinery for the effectful `Docker.Service` platform.
11 *
12 * NOT exported from the Docker barrel. Bundles a `main` Effect program with
13 * rolldown, bakes it into a generated bun Dockerfile, and builds the image
14 * with the Docker CLI against the service's Docker context — so the image is
15 * present in the exact engine the Swarm service schedules from. There is no
16 * registry push: the built image is content-addressed (`<name>:<hash>`) and
17 * only rebuilt when the bundle, Dockerfile, or environment image changes.
18 *
19 * Multi-node swarms need the image on every node; for those, build with
20 * `Docker.Image` + a `registry` and pass the pushed ref as `image` instead.
21 */
22
23 /** The props subset that describes a bundled `main` service image. */
24 export interface BundledServiceSource {
25 main: string;
26 image?: string;
27 handler?: string;
28 port?: number;
29 /**
30 * Bundler configuration for `main`. Unused code is tree-shaken.
31 * `effect`, alchemy, and `@distilled.cloud` are marked pure so unused
32 * parts prune more aggressively. List extra packages with
33 * `pure.packages`, or disable with `pure: false`.
34 */
35 build?: Bundle.BundleConfig;
36 }
37
38 /** The resolved (built) local image. */
39 export interface ResolvedServiceImage {
40 /** Full image reference, `<name>:<codeHash>`. */
41 imageRef: string;
42 /** Content hash identifying the image (also the image tag). */
43 codeHash: string;
44 }
45
46 /**
47 * The generated entry for `Docker.Service` containers: a shim importing only
48 * `@alchemy.run/docker/Bootstrap` plus the user's `main` — see that
49 * module for why the entry never imports alchemy's own dependencies.
50 */
51 export const makeServiceBunBootstrap =
52 (handler: string) =>
53 (importPath: string): string =>
54 `
55 import { bootstrap } from "@alchemy.run/docker/Bootstrap";
56 import { ${handler} as entrypoint } from ${JSON.stringify(importPath)};
57
58 await bootstrap(entrypoint);
59 `;
60
61 /**
62 * Init-time constructor for the service-image resolver. Resolves the services
63 * that are only available at provider-layer construction (Docker, the
64 * `.alchemy` directory, the rolldown virtual-entry plugin) and returns
65 * `resolve` (build the image if its content hash isn't present in the target
66 * engine) and `hash` (content hash only, for `diff`).
67 */
68 export const makeServiceImage = Effect.gen(function* () {
69 const docker = yield* Docker;
70 const { dotAlchemy } = yield* AlchemyContext;
71 const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
72
73 /** Bundle the Effect program behind a `main` source. */
74 const bundleProgram = Effect.fn(function* (options: {
75 source: BundledServiceSource;
76 isExternal?: boolean;
77 }) {
78 const { source } = options;
79 const realMain = yield* resolveMainPath(source.main);
80 const cwd = yield* findCwdForBundle(realMain);
81 const bootstrap = makeServiceBunBootstrap(source.handler ?? "default");
82
83 const buildBundle = Effect.fn(function* (
84 entry: string,
85 plugins?: rolldown.RolldownPluginOption,
86 ) {
87 return yield* Bundle.build(
88 {
89 ...source.build?.input,
90 input: entry,
91 cwd,
92 platform: "node",
93 // The container runs on `bun`; keep `bun`/`bun:*` external (the
94 // runtime provides them) and resolve the `bun` export condition
95 // so `@effect/platform-bun` picks its Bun implementations.
96 external: [
97 "bun",
98 "bun:*",
99 ...((source.build?.input?.external as string[] | undefined) ?? []),
100 ],
101 resolve: {
102 conditionNames: [...Bundle.BUN_CONDITION_NAMES],
103 ...source.build?.input?.resolve,
104 },
105 plugins: [source.build?.input?.plugins, plugins],
106 },
107 {
108 ...source.build?.output,
109 format: "esm",
110 sourcemap: source.build?.output?.sourcemap ?? false,
111 minify: source.build?.output?.minify ?? false,
112 entryFileNames: "index.mjs",
113 },
114 source.build,
115 );
116 });
117
118 const bundleOutput = options.isExternal
119 ? yield* buildBundle(realMain)
120 : yield* buildBundle(realMain, virtualEntryPlugin(bootstrap));
121
122 // Return every emitted file (entry + shared chunks). Dynamic imports in
123 // the Bun HTTP server split into chunks; dropping any of them crashes the
124 // container with `Cannot find module './chunk-XXX.js'`.
125 const files = bundleOutput.files.map((file) => ({
126 path: file.path,
127 content:
128 typeof file.content === "string" ? new TextEncoder().encode(file.content) : file.content,
129 }));
130
131 return { files, hash: bundleOutput.hash };
132 });
133
134 /**
135 * Generated Dockerfile for a bundled `main` program. The environment
136 * preamble is the `image` ref or the default bun base (`oven/bun` is
137 * Docker-Hub only).
138 */
139 const generateDockerfile = (source: BundledServiceSource) => {
140 const lines = [
141 `FROM ${source.image ?? "oven/bun:1"}`,
142 `WORKDIR /app`,
143 `COPY index.mjs /app/index.mjs`,
144 // Copy any additional rolldown chunks (`chunk-XXX.js`, …). Non-trivial
145 // bundles always emit at least one; minimal bundles emit none and the
146 // COPY no-ops.
147 `COPY *.js /app/`,
148 ];
149 if (source.port !== undefined) {
150 lines.push(`ENV PORT=${String(source.port)}`, `EXPOSE ${String(source.port)}`);
151 }
152 lines.push(`ENTRYPOINT ["bun", "/app/index.mjs"]`);
153 return `${lines.join("\n")}\n`;
154 };
155
156 /**
157 * Bundle a `main` source and compute its content-addressed code hash. The
158 * hash covers the full image identity — the bundle output (bootstrap entry
159 * included, so bootstrap-template changes invalidate it) and the generated
160 * Dockerfile — so `diff` and `resolve` always agree.
161 */
162 const computeCodeHash = Effect.fn(function* (options: {
163 source: BundledServiceSource;
164 isExternal?: boolean;
165 }) {
166 const bundled = yield* bundleProgram(options);
167 const dockerfile = generateDockerfile(options.source);
168 const codeHash = (yield* sha256Object({
169 bundleHash: bundled.hash,
170 dockerfile,
171 })).slice(0, 16);
172 return { bundled, dockerfile, codeHash };
173 });
174
175 /** Observe a locally-present tag in the target engine. Missing → undefined. */
176 const imageExists = (imageRef: string, context: string | undefined) =>
177 docker.image.inspect(imageRef, context).pipe(
178 Effect.map(() => true),
179 Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
180 );
181
182 /**
183 * Resolve the image for a bundled service: compute the content-addressed
184 * tag, then build only when that exact tag is not already present in the
185 * target Docker context (crash-safe convergence).
186 */
187 const resolve = Effect.fn(function* (options: {
188 /** Logical resource id — keys the stable build-context directory. */
189 id: string;
190 source: BundledServiceSource;
191 /** Image repository name (the service's physical name). */
192 name: string;
193 /** Docker context the swarm service is deployed to. */
194 context: string | undefined;
195 isExternal?: boolean;
196 /** Plan-status session used to emit build progress notes. */
197 session: { note: (message: string) => Effect.Effect<void> };
198 }) {
199 const { id, source, session } = options;
200 yield* session.note(`Bundling ${id} program...`);
201 const { bundled, dockerfile, codeHash } = yield* computeCodeHash({
202 source,
203 isExternal: options.isExternal,
204 });
205 const imageRef = `${options.name}:${codeHash}`;
206
207 if (yield* imageExists(imageRef, options.context)) {
208 return { imageRef, codeHash } satisfies ResolvedServiceImage;
209 }
210
211 const realMain = yield* resolveMainPath(source.main);
212 const contextDir = yield* getStableContextDir(realMain, dotAlchemy, `${id}-image`);
213 yield* docker.materialize({
214 context: contextDir,
215 dockerfile,
216 // Entry chunk becomes `index.mjs`; all other chunks keep their emitted
217 // `*.js` names so the entry's relative imports resolve.
218 files: bundled.files.map((file, index) => ({
219 path: index === 0 ? "index.mjs" : file.path,
220 content: file.content,
221 })),
222 });
223 yield* session.note(`Building container image ${imageRef}...`);
224 yield* docker.image.build({
225 context: contextDir,
226 tag: imageRef,
227 engineContext: options.context,
228 });
229 yield* session.note(`Built ${imageRef}`);
230 return { imageRef, codeHash } satisfies ResolvedServiceImage;
231 });
232
233 /**
234 * Content hash without building the image. Runs the bundler (bootstrap
235 * entry included) so the hash reflects the exact image `resolve` would
236 * build — bootstrap-template changes and user-code edits both surface as
237 * drift. The provider calls this from `diff` and compares against
238 * `output.code.hash`.
239 */
240 const hash = Effect.fn(function* (options: {
241 source: BundledServiceSource;
242 isExternal?: boolean;
243 }) {
244 const { codeHash } = yield* computeCodeHash(options);
245 return codeHash;
246 });
247
248 return { resolve, hash };
249 });
250
251 /** The resolver service returned by {@link makeServiceImage}. */
252 export interface ServiceImage extends Effect.Success<typeof makeServiceImage> {}