@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 435 lines 15.9 KB
Raw
1 import { Docker } from "@alchemy.run/docker/Docker";
2 import { isInlineDockerfile } from "@alchemy.run/docker/Dockerfile";
3 import { validateDockerfileBuild } from "@alchemy.run/docker/ImageSource";
4 import { AlchemyContext } from "alchemy/AlchemyContext";
5 import * as Bundle from "alchemy/Bundle/Bundle";
6 import { findCwdForBundle, getStableContextDir, resolveMainPath } from "alchemy/Bundle/TempRoot";
7 import * as Output from "alchemy/Output";
8 import { createPhysicalName } from "alchemy/PhysicalName";
9 import { Stack } from "alchemy/Stack";
10 import { sha256Object } from "alchemy/Util/sha256";
11 import * as Effect from "effect/Effect";
12 import * as Path from "effect/Path";
13 import * as Redacted from "effect/Redacted";
14 import type * as rolldown from "rolldown";
15 import type { AnyContainerApplicationProps } from "./ContainerApplication.ts";
16
17 /**
18 * Fold the runtime-context `env` map (populated by `Binding.Service`s and
19 * `Config` injection — see `ContainerPlatform.set`) into the application's
20 * `environmentVariables`.
21 *
22 * Unlike Cloudflare Workers, container `secrets` are *references to the
23 * account Secrets Store by name* — they cannot carry an inline value — so
24 * runtime-bound values (e.g. a minted API token) must travel as plain
25 * `environmentVariables`. The value is the JSON-encoded payload produced by
26 * `ContainerPlatform.set` (a `{_tag:"Redacted",value}` marker for secrets,
27 * a JSON string otherwise), which `ContainerPlatform.get` parses back into
28 * the original `Redacted`/plain value at runtime.
29 *
30 * `precreate` receives the raw, unevaluated props (the engine only resolves
31 * Output expressions for the real `reconcile`/create), so env values that
32 * reference other resources are still unresolved `Output`s there — skip them.
33 * They are applied when reconcile runs against the resolved props.
34 *
35 * When `accountId` is provided it is injected as `ALCHEMY_CLOUDFLARE_ACCOUNT_ID`
36 * (mirroring the Worker runtime) so the container bootstrap can build
37 * `CloudflareEnvironment` for HTTP capability bindings (R2/KV/Queue `*Http`).
38 *
39 * `bindings` carries the resource's binding contract — the `{ env }` a
40 * `Binding.Service` attaches with ``host.bind`${resource}`({ env })`` when the
41 * container is the host (`Prisma.Connect`, and any other capability whose
42 * runtime config travels as environment variables). Bindings are resolved by
43 * the engine before `reconcile`, so they land here already evaluated. They are
44 * applied FIRST, at the lowest precedence: an explicitly declared `env` or
45 * `environmentVariables` entry always wins over a capability-injected one.
46 */
47 export const makeContainerEnv = (
48 props: AnyContainerApplicationProps,
49 accountId: string,
50 bindings: readonly {
51 data?: { env?: Record<string, any> } | undefined;
52 }[] = [],
53 ) => {
54 const env: Record<string, string | Redacted.Redacted<string>> = {};
55 for (const binding of bindings) {
56 for (const [name, value] of Object.entries(binding.data?.env ?? {})) {
57 if (Output.isOutput(value) || value === undefined) {
58 continue;
59 }
60 env[name] = value;
61 }
62 }
63 for (const [name, value] of Object.entries(props.env ?? {})) {
64 if (Output.isOutput(value) || value === undefined) {
65 continue;
66 }
67 env[name] = value;
68 }
69 for (const value of props.environmentVariables ?? []) {
70 env[value.name] = value.value;
71 }
72 if (!env.ALCHEMY_CLOUDFLARE_ACCOUNT_ID) {
73 env.ALCHEMY_CLOUDFLARE_ACCOUNT_ID = accountId;
74 }
75 return env;
76 };
77
78 /**
79 * Derive the physical name for a container application. Shared between the
80 * live and local providers so they agree on the deterministic name.
81 */
82 export const createContainerApplicationName = (id: string, name: string | undefined) =>
83 Effect.suspend(() => {
84 if (name) return Effect.succeed(name);
85 return createPhysicalName({
86 id,
87 lowercase: true,
88 });
89 });
90
91 /**
92 * Validate the image-source composition on container props. Exactly one
93 * environment/source may be declared:
94 *
95 * - `main` + optional `image` (environment base) OR inline `dockerfile`
96 * (environment preamble) — never both, and never a `context`.
97 * - `image` alone — a pre-built remote image, exclusive with `dockerfile`
98 * and `context`.
99 * - `dockerfile` (string path against `context`, or inline content with no
100 * `context`) — the user-Dockerfile build. Only this source takes
101 * `build.args` / `build.secrets`.
102 *
103 * Invalid combinations are programmer errors, surfaced as plan-time defects
104 * (`Effect.die`) rather than typed errors.
105 */
106 export const validateContainerImageProps = (
107 id: string,
108 props: Pick<AnyContainerApplicationProps, "main" | "image" | "dockerfile" | "context" | "build">,
109 ): Effect.Effect<void> =>
110 validateImageSources(props).pipe(
111 Effect.andThen(
112 // An empty `main` declares no program, as in `validateImageSources`.
113 validateDockerfileBuild(id, { ...props, main: props.main || undefined }),
114 ),
115 );
116
117 const validateImageSources = (
118 props: Pick<AnyContainerApplicationProps, "main" | "image" | "dockerfile" | "context">,
119 ): Effect.Effect<void> => {
120 const df = props.dockerfile;
121 const hasInline = df !== undefined && isInlineDockerfile(df);
122 if (props.main) {
123 if (props.image !== undefined && df !== undefined) {
124 return Effect.die(
125 new Error(
126 "`image` and `dockerfile` are mutually exclusive with `main` — both pick the environment for the bundled program; declare one.",
127 ),
128 );
129 }
130 if (df !== undefined && !hasInline) {
131 return Effect.die(
132 new Error(
133 "A `dockerfile` PATH cannot be combined with `main` on Cloudflare containers — use `Dockerfile.inline` content or `image` to pick the bundled program's environment.",
134 ),
135 );
136 }
137 if (props.context !== undefined) {
138 return Effect.die(
139 new Error(
140 "`context` cannot be combined with `main` — the build context for a bundled program is generated by Alchemy.",
141 ),
142 );
143 }
144 return Effect.void;
145 }
146 if (props.image !== undefined && df !== undefined) {
147 return Effect.die(
148 new Error(
149 "`image` (pre-built remote image) and `dockerfile` (build your own) are mutually exclusive — declare one.",
150 ),
151 );
152 }
153 if (props.image !== undefined && props.context !== undefined) {
154 return Effect.die(
155 new Error(
156 "`image` (pre-built remote image) and `context` (Dockerfile build) are mutually exclusive — declare one.",
157 ),
158 );
159 }
160 if (hasInline && props.context !== undefined) {
161 return Effect.die(
162 new Error(
163 "Inline `dockerfile` content cannot be combined with `context` — inline content has no build context; use a `dockerfile` PATH for context-relative builds.",
164 ),
165 );
166 }
167 return Effect.void;
168 };
169
170 /**
171 * Resolve the environment preamble for a generated (Effect-native) container
172 * Dockerfile from the props' `image` / inline `dockerfile` composition:
173 *
174 * - inline `dockerfile` content → used verbatim as the preamble (it carries
175 * its own `FROM` and any extra build steps),
176 * - `image` → a synthesized `FROM <image>` line,
177 * - neither → `undefined` (callers fall back to the runtime default base).
178 */
179 export const containerEnvPreamble = (
180 props: Pick<AnyContainerApplicationProps, "image" | "dockerfile">,
181 ): Effect.Effect<string | undefined> => {
182 const df = props.dockerfile;
183 if (df !== undefined && isInlineDockerfile(df)) {
184 const content = df.content;
185 if (typeof content !== "string") {
186 return Effect.die(
187 new Error(
188 "Inline `dockerfile` content is an unresolved Output at image-build time. " +
189 "Outputs in `Dockerfile.inline` resolve during a normal deploy; this container is being built before its dependencies resolved (e.g. during precreate of a circular binding). Break the cycle or inline the resolved value.",
190 ),
191 );
192 }
193 return Effect.succeed(content.trimEnd());
194 }
195 const ref = props.image?.trim();
196 if (ref) {
197 if (/\s/.test(ref)) {
198 // A registry reference never contains whitespace — catch Dockerfile
199 // content early with an actionable message instead of producing a
200 // broken build.
201 return Effect.die(
202 new Error(
203 `\`image\` must be a plain image reference (e.g. "oven/bun:latest"), got: ${JSON.stringify(props.image)}. ` +
204 "For inline Dockerfile content use `dockerfile: Dockerfile.inline`.",
205 ),
206 );
207 }
208 return Effect.succeed(`FROM ${ref}`);
209 }
210 return Effect.undefined;
211 };
212
213 /**
214 * Build the final Dockerfile used for a generated (Effect-native) container
215 * image. Starts from the environment preamble (see
216 * {@link containerEnvPreamble}) — or a runtime-appropriate default base —
217 * then appends the statements that copy the bundled program and set the
218 * entrypoint.
219 */
220 export const buildFinalDockerfile = (
221 envPreamble: string | undefined,
222 runtime: "bun" | "node",
223 external: string[] = [],
224 autoInstallExternals = true,
225 ): string => {
226 const base = envPreamble ?? (runtime === "bun" ? "FROM oven/bun:1" : "FROM node:22-slim");
227 const runtimeBin = runtime === "bun" ? "bun" : "node";
228 const installCmd = runtime === "bun" ? "bun add" : "npm install";
229 const installStep =
230 autoInstallExternals && external.length > 0 ? `RUN ${installCmd} ${external.join(" ")}` : "";
231 return [
232 base,
233 "",
234 "WORKDIR /app",
235 ...(installStep ? [installStep, ""] : []),
236 // Linked copies don't depend on the layers below them, so the registry
237 // exporter reuses cached base layers instead of downloading them first.
238 "COPY --link index.mjs /app/index.mjs",
239 // Copy any additional rolldown chunks (`chunk-XXX.js`,
240 // `BunServices-YYY.js`, …). The glob matches zero or more files;
241 // non-trivial bundles always emit at least one chunk, minimal
242 // bundles emit none and the COPY no-ops.
243 "COPY --link *.js /app/",
244 "EXPOSE 3000",
245 `ENTRYPOINT ["${runtimeBin}", "/app/index.mjs"]`,
246 "",
247 ].join("\n");
248 };
249
250 /**
251 * Materialize resolved inline `dockerfile` content into a stable,
252 * deterministic build-context directory (containing only the Dockerfile) so
253 * both the live provider and the local dev runtime can `docker build` it.
254 * Shared by the live and local providers so they agree on the path.
255 */
256 export const materializeInlineDockerfileContext = Effect.fn(function* (
257 id: string,
258 content: string,
259 ) {
260 const { dotAlchemy } = yield* AlchemyContext;
261 const docker = yield* Docker;
262 const path = yield* Path.Path;
263 const context = yield* getStableContextDir(dotAlchemy, dotAlchemy, `${id}-dockerfile`);
264 yield* docker.materialize({ context, dockerfile: content, files: [] });
265 return { context, dockerfile: path.join(context, "Dockerfile") };
266 });
267
268 /**
269 * Bundle the container entrypoint program with rolldown. Returns every emitted
270 * file (entry chunk plus shared chunks) so the full set can be materialized
271 * into the Docker build context, along with a content hash of the bundle.
272 *
273 * Shared between the live provider (which builds + pushes a Cloudflare image)
274 * and the local provider (which writes the context to disk for the runtime to
275 * `docker build`).
276 */
277 export const bundleContainerProgram = Effect.fn(function* ({
278 main,
279 runtime,
280 handler = "default",
281 isExternal = false,
282 external = [],
283 outdir,
284 build,
285 }: {
286 id: string;
287 main: string;
288 runtime: "bun" | "node";
289 handler?: string | undefined;
290 isExternal?: boolean;
291 external?: string[];
292 outdir?: string;
293 build?: Bundle.BundleConfig;
294 }) {
295 const stack = yield* Stack;
296 const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin;
297
298 const realMain = yield* resolveMainPath(main);
299 const cwd = yield* findCwdForBundle(realMain);
300
301 const buildBundle = Effect.fn(function* (entry: string, plugins?: rolldown.RolldownPluginOption) {
302 return yield* Bundle.build(
303 {
304 ...build?.input,
305 input: entry,
306 cwd,
307 external: [
308 "cloudflare:workers",
309 "cloudflare:workflows",
310 ...(runtime === "bun" ? ["bun", "bun:*"] : []),
311 ...external,
312 ...((build?.input?.external as string[] | undefined) ?? []),
313 ],
314 platform: "node",
315 resolve: {
316 conditionNames:
317 runtime === "bun" ? [...Bundle.BUN_CONDITION_NAMES] : [...Bundle.NODE_CONDITION_NAMES],
318 ...build?.input?.resolve,
319 },
320 plugins: [build?.input?.plugins, plugins],
321 treeshake: true,
322 },
323 {
324 ...build?.output,
325 format: "esm",
326 sourcemap: build?.output?.sourcemap ?? false,
327 minify: build?.output?.minify ?? false,
328 dir: outdir,
329 entryFileNames: "index.mjs",
330 },
331 build,
332 );
333 });
334
335 const bundleOutput = isExternal
336 ? yield* buildBundle(realMain)
337 : yield* buildBundle(
338 realMain,
339 virtualEntryPlugin(
340 (importPath) => `
341 import { bootstrap } from ${JSON.stringify(
342 runtime === "bun"
343 ? "@alchemy.run/cloudflare/Bootstrap/ContainerBun"
344 : "@alchemy.run/cloudflare/Bootstrap/ContainerNode",
345 )};
346 import ${handler === "default" ? "entrypoint" : `{ ${handler} as entrypoint }`} from ${JSON.stringify(importPath)};
347
348 await bootstrap(entrypoint, ${JSON.stringify({
349 stack: { name: stack.name, stage: stack.stage },
350 })});
351 `,
352 ),
353 );
354
355 // Rolldown can emit multiple chunk files (entry + shared chunks).
356 // Return every file so downstream code can materialize all of them
357 // into the Docker build context — dropping any of them produces a
358 // `Cannot find module './chunk-XXX.js'` runtime crash inside the
359 // container (with zero stdout, because it crashes before any user
360 // code runs).
361 const files = bundleOutput.files.map((f) => ({
362 path: f.path,
363 content: typeof f.content === "string" ? new TextEncoder().encode(f.content) : f.content,
364 }));
365
366 return { files, hash: bundleOutput.hash };
367 });
368
369 /**
370 * Bundle an Effect-native container `main` and materialize it (plus the
371 * generated Dockerfile) into a stable Docker build context directory, then
372 * return the paths + content hash of that context.
373 *
374 * This is the local-dev image shape (`ContainerImage.Build`) that
375 * `@alchemy.run/cloudflare-runtime/core` consumes: it `docker build`s the
376 * `dockerfile` against the `context` directory. Shared between the local
377 * provider (which serves this context to the runtime as the `dev` image) and
378 * the live provider (which persists the same deterministic context path as
379 * `dev` so a subsequent `alchemy dev` run has an image to build even though the
380 * live deploy pushed to Cloudflare's registry instead).
381 *
382 * The context directory is deterministic for a given resource id, so live and
383 * local agree on the path. Callers that want to skip re-bundling on an
384 * unchanged resource should wrap this in {@link Artifacts.cached}.
385 */
386 export const prepareContainerBuildContext = Effect.fn(function* (
387 id: string,
388 news: AnyContainerApplicationProps,
389 ) {
390 const { dotAlchemy } = yield* AlchemyContext;
391 const docker = yield* Docker;
392 const path = yield* Path.Path;
393
394 const main = news.main;
395 if (!main) {
396 return yield* Effect.die(new Error("Container requires a `main` entrypoint."));
397 }
398 yield* validateContainerImageProps(id, news);
399 const runtime = news.runtime ?? "bun";
400 const context = yield* getStableContextDir(process.cwd(), dotAlchemy, `${id}-container`);
401 const dockerfileContent = buildFinalDockerfile(
402 yield* containerEnvPreamble(news),
403 runtime,
404 news.external,
405 news.autoInstallExternals,
406 );
407 const [bundle] = yield* Effect.all(
408 [
409 bundleContainerProgram({
410 id,
411 main,
412 runtime,
413 handler: news.handler,
414 isExternal: news.isExternal,
415 external: news.external,
416 outdir: context,
417 build: news.build,
418 }),
419 docker.materialize({
420 context,
421 dockerfile: dockerfileContent,
422 files: [],
423 }),
424 ],
425 { concurrency: "unbounded" },
426 );
427 return {
428 context,
429 dockerfile: path.join(context, "Dockerfile"),
430 hash: yield* sha256Object({
431 bundle: bundle.hash,
432 dockerfileContent,
433 }),
434 };
435 });