@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 993 lines 37.6 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import type { InputProps } from "alchemy/Input";
3 import type { Named } from "alchemy/Named";
4 import type { ResourceClass, ResourceClassLike } from "alchemy/Resource";
5 import type { Rpc } from "alchemy/Rpc";
6 import { effectClass } from "alchemy/Util/effect";
7 import * as Config from "effect/Config";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Layer from "effect/Layer";
11 import type { Providers } from "../Providers.ts";
12 import { type WorkerShape } from "../Workers/Worker.ts";
13 import type { ContainerApplication } from "./ContainerApplication.ts";
14 import {
15 makeContainerHandle,
16 type ContainerClient,
17 type ReservedContainerKey,
18 } from "./ContainerClient.ts";
19 import { ContainerPlatform } from "./ContainerPlatform.ts";
20
21 export const ContainerTypeId = "Cloudflare.Container";
22 export type ContainerTypeId = typeof ContainerTypeId;
23
24 export const isContainer = <T>(value: T): value is T & Container =>
25 typeof value === "object" && value !== null && "Type" in value && value.Type === ContainerTypeId;
26
27 export class ContainerError extends Data.TaggedError("ContainerError")<{
28 readonly message: string;
29 readonly cause?: unknown;
30 }> {}
31
32 /**
33 * No container instance could be allocated within the start budget — the
34 * account is at its concurrent-instance cap (`maxInstances`) or the platform
35 * is still provisioning. Mirrors `@cloudflare/containers`'
36 * `NO_CONTAINER_INSTANCE_ERROR` (surfaced as HTTP 503 by native).
37 */
38 export class NoContainerInstanceError extends Data.TaggedError("NoContainerInstanceError")<{
39 readonly message: string;
40 readonly cause?: unknown;
41 }> {}
42
43 /**
44 * Cloudflare is rate limiting container starts ("too many containers per
45 * second"). Mirrors `@cloudflare/containers`' `RATE_LIMITED_ERROR` (HTTP 429).
46 * Hammering `start()` while rate limited only prolongs it, so callers should
47 * back off rather than retry tightly.
48 */
49 export class ContainerRateLimitedError extends Data.TaggedError("ContainerRateLimitedError")<{
50 readonly message: string;
51 readonly cause?: unknown;
52 }> {}
53
54 /**
55 * The container instance exited/crashed while we were waiting for its port —
56 * the entrypoint failed to bind or died. Mirrors native's "container exited"
57 * detection (`!this.container.running` mid-wait); not curable by continuing to
58 * poll the same instance.
59 */
60 export class ContainerCrashedError extends Data.TaggedError("ContainerCrashedError")<{
61 readonly message: string;
62 readonly cause?: unknown;
63 }> {}
64
65 /**
66 * The container is not running. Ports and RPC methods never start it; call
67 * `start()` first.
68 */
69 export class ContainerNotRunningError extends Data.TaggedError("ContainerNotRunningError")<{
70 readonly message: string;
71 readonly cause?: unknown;
72 }> {}
73
74 // Upstream changed ContainerStartupOptions to an intersection with an
75 // image/containerSnapshot union, which an interface cannot extend.
76 export type ContainerStartupOptions = cf.ContainerStartupOptions;
77
78 import type {
79 DurableObjectContainerProps,
80 EffectfulContainerProps,
81 ExternalContainerProps,
82 RemoteContainerProps,
83 } from "./ContainerApplication.ts";
84
85 export type {
86 DurableObjectContainerProps,
87 EffectfulContainerProps,
88 ExternalContainerProps,
89 RemoteContainerProps,
90 };
91
92 /**
93 * Props for an image-backed container declaration — either the plain props
94 * object, or an Effect that produces it.
95 *
96 * The Effect form is how a container reaches another resource's outputs. A
97 * class body is module scope, so there is nowhere to `yield*` a database,
98 * queue, or bucket; wrapping the props in `Effect.gen` moves the declaration
99 * into an Effect where sibling resources resolve normally and their
100 * attributes can be threaded into `env`:
101 *
102 * ```typescript
103 * export class Api extends Cloudflare.Container<Api>()(
104 * "Api",
105 * Effect.gen(function* () {
106 * const { connection } = yield* Db;
107 * return {
108 * context: `${import.meta.dirname}/api`,
109 * env: { DATABASE_URL: connection.databaseUrl },
110 * };
111 * }),
112 * ) {}
113 * ```
114 *
115 * A plain props object cannot do this: a module-scope resource declaration
116 * is an Effect, not a resolved handle, so `Db.connectionString` is
117 * `undefined` until something yields it.
118 */
119 export type ImageContainerProps<Req = never> =
120 | InputProps<ExternalContainerProps>
121 | InputProps<RemoteContainerProps>
122 | InputProps<DurableObjectContainerProps>
123 | Effect.Effect<
124 | InputProps<ExternalContainerProps>
125 | InputProps<RemoteContainerProps>
126 | InputProps<DurableObjectContainerProps>,
127 Config.ConfigError,
128 Req
129 >;
130
131 /**
132 * The handle `yield* MyContainer` returns inside a Durable Object. See
133 * {@link ContainerClient}.
134 */
135 export type Container<Id extends string = string> = Named<Id> & ContainerClient;
136
137 /** An RPC shape may not redeclare the container handle's own methods. */
138 type ContainerShape<Shape> = {
139 [K in keyof Shape]: K extends ReservedContainerKey ? never : Shape[K];
140 };
141
142 /**
143 * A Cloudflare Container that runs a long-lived process alongside a
144 * Durable Object.
145 *
146 * Containers always use the **Container Layer** pattern — the class
147 * and `.make()` must live in separate files. A Container must be
148 * bound to a Durable Object, and the DO imports the class to get a
149 * typed handle. If the class and `.make()` lived in the same file,
150 * the DO's bundle would pull in all of the container's runtime
151 * dependencies (process spawners, Node APIs, SDKs, etc.), which
152 * would bloat the bundle and likely break the Cloudflare Workers
153 * runtime. Keeping them separate ensures the bundler only includes
154 * the tiny class in the DO's output.
155 *
156 * See the [Runtime concept](/infrastructure-as-effects/runtime)
157 * page for how this fits into the async / effect / layer
158 * progression.
159 * ### Container Layer
160 * Define the class and `.make()` in separate files. The class
161 * declares the container's identity, configuration, and typed
162 * shape. `.make()` provides the runtime implementation as a
163 * default export. Use `Container.of` to construct the typed
164 * shape — it ensures your implementation matches the methods
165 * declared on the class.
166 *
167 * **Example:** Container class
168 * ```typescript
169 * // src/Sandbox.ts — the tag carries only the name + typed shape;
170 * // configuration lives on `.make()`.
171 * export class Sandbox extends Cloudflare.Container<
172 * Sandbox,
173 * {
174 * shell: (cmd: string) => Effect.Effect<{
175 * exitCode: number;
176 * stdout: string;
177 * stderr: string;
178 * }>;
179 * }
180 * >()("Sandbox") {}
181 * ```
182 *
183 * **Example:** Container .make()
184 * ```typescript
185 * // src/Sandbox.runtime.ts — props are the first argument to `.make()`
186 * export default Sandbox.make(
187 * { main: import.meta.url },
188 * Effect.gen(function* () {
189 * const cp = yield* ChildProcessSpawner;
190 *
191 * return Sandbox.of({
192 * shell: (command) =>
193 * cp.spawn(ChildProcess.make(command, { shell: true })).pipe(
194 * Effect.flatMap(({ exitCode, stdout, stderr }) =>
195 * Effect.all({
196 * exitCode,
197 * stdout: stdout.pipe(Stream.decodeText, Stream.mkString),
198 * stderr: stderr.pipe(Stream.decodeText, Stream.mkString),
199 * }),
200 * ),
201 * Effect.scoped,
202 * ),
203 * fetch: Effect.succeed(
204 * HttpServerResponse.text("Hello from container!"),
205 * ),
206 * });
207 * }),
208 * );
209 * ```
210 *
211 * ### Async Workers
212 * An async Worker can host a container-backed Durable Object class that
213 * ships as plain JavaScript — `@cloudflare/sandbox`'s `Sandbox`, or your
214 * own class extending `@cloudflare/containers`' `Container`. The class
215 * lives in the worker script; `Container` (the npm one) handles the
216 * lifecycle and forwards `fetch` to the port inside the container.
217 *
218 * **Example:** The worker script exports the container-backed class
219 * ```typescript
220 * // src/worker.ts
221 * import { Container } from "@cloudflare/containers";
222 *
223 * export class Sandbox extends Container {
224 * defaultPort = 8080;
225 * }
226 * ```
227 *
228 * Declare it in the stack by binding a `Cloudflare.Container` in the
229 * Worker's `env` — the Container **is** the Durable Object binding and its
230 * ContainerApplication together. Alchemy emits the
231 * `durable_object_namespace` binding, marks the class as container-backed
232 * in the script metadata, provisions the ContainerApplication, and attaches
233 * it to the class's namespace. The Durable Object class name defaults to
234 * the binding name (the `env` key); set `className` when the exported class
235 * is named differently.
236 *
237 * **Example:** Binding the container-backed class in the stack
238 * ```typescript
239 * // alchemy.run.ts
240 * import type { Sandbox } from "./src/worker.ts";
241 *
242 * export const Worker = Cloudflare.Worker("Worker", {
243 * main: "./src/worker.ts",
244 * env: {
245 * Sandbox: Cloudflare.Container<Sandbox>("Sandbox", {
246 * image: "docker.io/cloudflare/sandbox:0.1.3",
247 * }),
248 * },
249 * });
250 * ```
251 *
252 * The type parameter (`Container<Sandbox>`) is the class from `worker.ts` —
253 * it types `env.Sandbox` as `DurableObjectNamespace<Sandbox>` via
254 * `Cloudflare.InferEnv`, so the handler reaches the container with full
255 * types.
256 *
257 * **Example:** Reaching the container from the async handler
258 * ```typescript
259 * // src/worker.ts
260 * import { getContainer } from "@cloudflare/containers";
261 * import type * as Cloudflare from "@alchemy.run/cloudflare";
262 * import type { Worker } from "../alchemy.run.ts";
263 *
264 * export default {
265 * async fetch(request: Request, env: Cloudflare.InferEnv<typeof Worker>) {
266 * return getContainer(env.Sandbox, "default").fetch(request);
267 * },
268 * };
269 * ```
270 *
271 * ### Native Durable Object Containers
272 * Use `schedulingPolicy: "durable_object"` to let a Durable Object pick its
273 * image and instance size at runtime. One Container is one image: `image`
274 * copies a registry image, `context`/`dockerfile` builds one. Alchemy pins the
275 * image to a digest and prepares it before the Worker is uploaded.
276 *
277 * `yield* Node` returns the container's handle without starting it.
278 * `start()` starts the Container's own image. Its `exec` takes an argument
279 * vector and returns a scoped process with streams, an exit code, and an
280 * `output()` collector.
281 *
282 * **Example:** Execute a command in a Container's image
283 * ```typescript
284 * export class Node extends Cloudflare.Container<Node>()("Node", {
285 * schedulingPolicy: "durable_object",
286 * image: "node:24-slim",
287 * }) {}
288 *
289 * export class Agent extends Cloudflare.DurableObject<Agent>()(
290 * "Agent",
291 * Effect.gen(function* () {
292 * const node = yield* Node;
293 * return Effect.succeed({
294 * exec: (args: string[]) =>
295 * Effect.gen(function* () {
296 * // Starts the Node image; a no-op when the container is running.
297 * yield* node.start({
298 * instance: "lite",
299 * entrypoint: ["sleep", "infinity"],
300 * enableInternet: false,
301 * });
302 * const process = yield* node.exec(args);
303 * const result = yield* process.output();
304 * return { text: new TextDecoder().decode(result.stdout), exitCode: result.exitCode };
305 * }).pipe(Effect.scoped),
306 * });
307 * }),
308 * ) {}
309 * ```
310 *
311 * ### Several Images in One Durable Object
312 * Cloudflare gives each Durable Object class one container application and
313 * each object one container instance. Bind several Containers to choose
314 * between their images. Every binding adds its image to the class's
315 * application under the Container's id. Each handle's `start()` starts its
316 * own image; start one at a time and `destroy()` before switching.
317 *
318 * **Example:** A Durable Object with Node and Python images
319 * ```typescript
320 * export class Node extends Cloudflare.Container<Node>()("Node", {
321 * schedulingPolicy: "durable_object",
322 * image: "node:24-slim",
323 * }) {}
324 *
325 * export class Python extends Cloudflare.Container<Python>()("Python", {
326 * schedulingPolicy: "durable_object",
327 * context: "./python",
328 * }) {}
329 *
330 * export class Agent extends Cloudflare.DurableObject<Agent>()(
331 * "Agent",
332 * Effect.gen(function* () {
333 * const node = yield* Node;
334 * const python = yield* Python;
335 * const run = (cmd: string[]) =>
336 * Effect.scoped(Effect.flatMap(node.exec(cmd), (process) => process.output()));
337 * return Effect.succeed({
338 * node: (cmd: string[]) =>
339 * node
340 * .start({ entrypoint: ["sleep", "infinity"], enableInternet: false })
341 * .pipe(Effect.andThen(run(cmd))),
342 * python: (cmd: string[]) =>
343 * Effect.gen(function* () {
344 * // Every handle controls the same instance: switch images explicitly.
345 * if (yield* node.running) yield* node.destroy();
346 * yield* python.start({ entrypoint: ["sleep", "infinity"], enableInternet: false });
347 * return yield* Effect.scoped(
348 * Effect.flatMap(python.exec(cmd), (process) => process.output()),
349 * );
350 * }),
351 * });
352 * }),
353 * ) {}
354 * ```
355 *
356 * Application-wide settings (`ssh`, `authorizedKeys`, `observability`) may be
357 * declared on any of the class's Containers. Two Containers declaring
358 * different values fail the deploy with `ContainerApplicationSettingsConflict`.
359 *
360 * **Example:** Save and restore the writable filesystem
361 * ```typescript
362 * const snapshot = yield* node.snapshotContainer({ name: "workspace" });
363 * // Persist this handle in Durable Object storage before stopping the instance.
364 * yield* state.storage.put("snapshot", snapshot);
365 * yield* node.destroy();
366 * yield* node.start({
367 * containerSnapshot: snapshot,
368 * entrypoint: ["sleep", "infinity"],
369 * enableInternet: false,
370 * });
371 * ```
372 *
373 * Snapshots capture the writable root filesystem, not memory, processes, or
374 * mounted filesystems. Restoring starts a new entrypoint process. Snapshot
375 * handles expire after 30 days without a restore. `exec` does not start a
376 * stopped container or invoke a shell; pass `['sh', '-c', command]` explicitly
377 * when needed. Scope closure kills an unfinished exec process, but does not
378 * signal its descendants. Use an Effect timeout to bound a command's lifetime.
379 *
380 * ### Native Durable Objects on Async Workers
381 * A plain Durable Object class on an async Worker attaches its Containers
382 * through its Durable Object binding:
383 * `Cloudflare.DurableObject(className, { containers })`. Each Container adds
384 * its image to the class's application, and the class reads it from
385 * `ctx.container.images` under the Container's id. A Container may be listed
386 * by several classes; each class gets its own copy of the image key.
387 *
388 * **Example:** Two classes sharing the Node image
389 * ```typescript
390 * // alchemy.run.ts
391 * const Node = Cloudflare.Container("Node", {
392 * schedulingPolicy: "durable_object",
393 * image: "node:24-slim",
394 * });
395 * const Python = Cloudflare.Container("Python", {
396 * schedulingPolicy: "durable_object",
397 * image: "python:3.13-slim",
398 * });
399 * const Rust = Cloudflare.Container("Rust", {
400 * schedulingPolicy: "durable_object",
401 * image: "rust:1.90-slim",
402 * });
403 * export const Worker = Cloudflare.Worker("App", {
404 * main: "./src/worker.ts",
405 * env: {
406 * AGENT: Cloudflare.DurableObject("Agent", { containers: [Node, Python] }),
407 * REVIEWER: Cloudflare.DurableObject("Reviewer", { containers: [Node, Rust] }),
408 * },
409 * });
410 * ```
411 *
412 * A Durable Object-managed Container placed directly in `env` fails with
413 * `DurableObjectContainerBindingError`; only fleet Containers bind that way.
414 *
415 * **Example:** Starting an image from the class
416 * ```typescript
417 * // src/worker.ts
418 * import { DurableObject } from "cloudflare:workers";
419 *
420 * export class Agent extends DurableObject {
421 * async run(cmd: string[]) {
422 * const container = this.ctx.container!;
423 * if (!container.running) {
424 * container.start({
425 * image: container.images.Node,
426 * entrypoint: ["sleep", "infinity"],
427 * enableInternet: false,
428 * });
429 * }
430 * return (await container.exec(cmd)).output();
431 * }
432 * }
433 * ```
434 *
435 * Local development runs every image through workerd and Docker.
436 *
437 * Switching an existing application to this scheduling policy requires a new
438 * application and a new Durable Object class/namespace. Alchemy rejects an
439 * in-place policy change; existing Durable Object storage is not transferred.
440 * Replacing only a wrapper with the native API while retaining the original
441 * policy and class preserves the namespace. Deployment properties such as
442 * `maxInstances`, `instanceType`, `env`, and `rollout` are not valid with the
443 * new policy; pass per-instance settings to `start()`.
444 *
445 * ### Image Sources
446 * A container's image comes from one of three sources, picked by which
447 * prop you set:
448 *
449 * - `main` — bundle your Effect program into a generated image.
450 * - `context` (+ optional `dockerfile`) — build your own Dockerfile.
451 * - `image` — pull a pre-built image and re-push it.
452 *
453 * Only the `main` source bundles and injects an Effect runtime — so it
454 * has a typed shape and a `.make(props, impl)` runtime. The other two
455 * ship an arbitrary image as-is: they have no runtime to provide, so
456 * you declare the class with its props inline and bind it with
457 * `yield* MyContainer` from the hosting Durable Object.
458 *
459 * **Example:** Effect-native image (`main`)
460 * ```typescript
461 * // Alchemy bundles this file's Effect program and bakes it into a
462 * // generated image as the entrypoint.
463 * export class Sandbox extends Cloudflare.Container<
464 * Sandbox,
465 * { ping: () => Effect.Effect<string> }
466 * >()("Sandbox") {}
467 *
468 * export default Sandbox.make(
469 * { main: import.meta.url },
470 * Effect.gen(function* () {
471 * return Sandbox.of({
472 * ping: () => Effect.succeed("pong"),
473 * fetch: Effect.succeed(HttpServerResponse.text("hello")),
474 * });
475 * }),
476 * );
477 * ```
478 *
479 * **Example:** Build your own Dockerfile (`context` / `dockerfile`)
480 * ```typescript
481 * // Alchemy builds the Dockerfile against the context directory — no
482 * // Effect bundling, no `.make()`. `dockerfile` defaults to
483 * // `<context>/Dockerfile`. The props are declared inline on the tag.
484 * export class Web extends Cloudflare.Container<Web>()("Web", {
485 * context: `${import.meta.dirname}/context`,
486 * }) {}
487 * ```
488 *
489 * **Example:** Build args and secrets
490 * ```typescript
491 * // Dockerfile:
492 * // ARG NODE_ENV
493 * // RUN --mount=type=secret,id=NPM_TOKEN,env=NPM_TOKEN npm ci
494 * export class Api extends Cloudflare.Container<Api>()("Api", {
495 * context: `${import.meta.dirname}/api`,
496 * build: {
497 * args: { NODE_ENV: "production" },
498 * // Resolved at deploy time; mounted only into the `RUN` step that asks
499 * // for it, never written to a layer or the build history.
500 * secrets: { NPM_TOKEN: Config.Redacted("NPM_TOKEN") },
501 * },
502 * }) {}
503 * ```
504 *
505 * `build.args` are part of the image hash, so changing one rebuilds the
506 * image. `build.secrets` are not: rotating a token reuses the published image.
507 *
508 * Builds are cached by default at
509 * `registry.cloudflare.com/<account-id>/<application-physical-name>`.
510 * The generated physical name includes the stage and resource instance, so
511 * subsequent updates in that stage can reuse matching images. Replacement or
512 * destroy/recreate can change the name and start a new cache. This does not
513 * automatically share one repository across every container in the stage.
514 * The same defaults apply to inline Dockerfiles and Effect-native `main` builds.
515 *
516 * **Example:** Reuse builds across stages
517 * ```typescript
518 * export class Web extends Cloudflare.Container<Web>()("Web", {
519 * context: `${import.meta.dirname}/context`,
520 * publish: { repository: "web" },
521 * }) {}
522 * ```
523 *
524 * `repository: "web"` names the destination repository, not a source image or
525 * the container application. With the default registry host, Alchemy lowercases
526 * the name and expands it to `registry.cloudflare.com/<account-id>/web`.
527 * Supply only the repository name, without a registry host, account ID, tag,
528 * or digest. A build produces these references:
529 *
530 * ```text
531 * Published build: registry.cloudflare.com/<account-id>/web:<build-hash>
532 * Build cache: registry.cloudflare.com/<account-id>/web:buildcache
533 * Deployed image: registry.cloudflare.com/<account-id>/web@sha256:<manifest-digest>
534 * ```
535 *
536 * The build hash identifies the inputs; the manifest digest identifies the
537 * published artifact. Applications and stages in the same account can use
538 * `publish: { repository: "web" }` to reuse matching published builds. Changed
539 * inputs produce another hash tag in the same repository. Builds targeting
540 * that repository import reusable layers from its shared `:buildcache` tag,
541 * including when full input hashes differ. This mutable tag points to the
542 * latest exported inline cache, not a combined cache of every historical
543 * image. Reusing a finished image does not move the layer-cache tag.
544 *
545 * Pin base images and downloaded dependencies: changes outside the build
546 * context cannot invalidate the input hash. Each stage still has its own
547 * Container application, runtime settings, and instances; only images and
548 * build layers are shared.
549 *
550 * **Example:** Publish an existing image into a named repository
551 * ```typescript
552 * export class Proxy extends Cloudflare.Container<Proxy>()("Proxy", {
553 * image: "nginx:alpine",
554 * publish: { repository: "web-proxy" },
555 * }) {}
556 * // Re-publishes nginx into registry.cloudflare.com/<account-id>/web-proxy
557 * // and deploys registry.cloudflare.com/<account-id>/web-proxy@sha256:<manifest-digest>.
558 * ```
559 *
560 * Remote images are re-published without building them. An image already in
561 * the target registry keeps its existing repository; `publish.repository`
562 * does not copy it into another one.
563 *
564 * **Example:** Remote image (`image`)
565 * ```typescript
566 * // Alchemy pulls the public image and re-pushes it to Cloudflare's
567 * // registry — no build, no bundling, no `.make()`.
568 * export class Echo extends Cloudflare.Container<Echo>()("Echo", {
569 * image: "mendhak/http-https-echo:latest",
570 * }) {}
571 * ```
572 *
573 * Alchemy pulls an `image` as `linux/amd64` on every deploy and every
574 * `alchemy dev` start, so a mutable tag like `:latest` picks up a newly
575 * pushed image. A private registry needs a `docker login` first.
576 *
577 * **Example:** Image built on this machine
578 * ```typescript
579 * // docker build --platform linux/amd64 -t local-only/app:dev .
580 * export class App extends Cloudflare.Container<App>()("App", {
581 * image: "local-only/app:dev",
582 * }) {}
583 * ```
584 *
585 * An image only in the local Docker, built on this machine or loaded with
586 * `docker load`, has no registry to pull from. When the pull fails and the
587 * image is present locally, Alchemy uses the local copy, in `alchemy dev`
588 * and on deploy. Build it with `--platform linux/amd64`, the platform
589 * Cloudflare runs: deploy fails on an image built only for another
590 * platform. When the image can be neither pulled nor found locally,
591 * Alchemy fails with the image name and the commands that fix it. The
592 * image name alone is the identity, so rebuilding under the same tag does
593 * not redeploy; give each build its own tag.
594 *
595 * **Example:** Reaching an arbitrary image's port from a Durable Object
596 * ```typescript
597 * // `external` and `remote` images expose no RPC methods, so the DO
598 * // talks to them purely over their TCP port via `getTcpPort`.
599 * export class WebObject extends Cloudflare.DurableObject<WebObject>()(
600 * "WebObject",
601 * Effect.gen(function* () {
602 * const web = yield* Web;
603 * return Effect.gen(function* () {
604 * const { fetch } = yield* web.getTcpPort(8080);
605 * return {
606 * hello: () =>
607 * Effect.gen(function* () {
608 * yield* web.start();
609 * const res = yield* fetch(HttpClientRequest.get("http://container/"));
610 * return yield* res.text;
611 * }),
612 * };
613 * });
614 * }),
615 * ) {}
616 * ```
617 *
618 * ### Bundling & Tree-shaking
619 * `main` is bundled with rolldown at deploy time. Unused code is
620 * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked
621 * pure so unused parts prune more aggressively. Your app is not
622 * marked pure.
623 *
624 * **Example:** Mark additional packages as pure
625 * Only list packages with no top-level side effects.
626 * ```typescript
627 * {
628 * main: import.meta.url,
629 * build: {
630 * pure: { packages: ["my-lib", "@my-scope/*"] },
631 * },
632 * }
633 * ```
634 *
635 * **Example:** Turn it off
636 * ```typescript
637 * {
638 * main: import.meta.url,
639 * build: { pure: false },
640 * }
641 * ```
642 *
643 * ### Configuration
644 * The props object — the first argument to `.make()` — accepts `main`
645 * (entrypoint file), `instanceType` (compute size), `runtime`
646 * (`"bun"` or `"node"`), and `observability` settings. Use
647 * `Stack.useSync` to read the surrounding stack and pick a beefier
648 * `instanceType` in prod while keeping the cheap `dev` instance for
649 * preview environments.
650 *
651 * **Example:** Stage-dependent configuration
652 * ```typescript
653 * export const SandboxLive = Sandbox.make(
654 * Stack.useSync((stack) => ({
655 * main: import.meta.url,
656 * instanceType: stack.stage === "prod" ? "standard-1" : "dev",
657 * observability: { logs: { enabled: true } },
658 * })),
659 * Effect.gen(function* () {
660 * return Sandbox.of({ shell: (cmd) => ... });
661 * }),
662 * );
663 * ```
664 *
665 * ### Environment Variables
666 * A container is a process, not a Worker: it has no bindings, so every
667 * piece of configuration reaches it through `env`. Each entry lands on
668 * the deployment and shows up in `process.env` inside the image —
669 * generated (`main`), built (`context`), or pre-built (`image`) alike.
670 * Wrap a secret in `Redacted` to keep it encrypted in state and out of
671 * plan output; the container still reads a plain string.
672 *
673 * **Example:** Plain and secret env values
674 * ```typescript
675 * export class Api extends Cloudflare.Container<Api>()("Api", {
676 * context: `${import.meta.dirname}/api`,
677 * ports: [{ name: "http", port: 8080 }],
678 * env: {
679 * PORT: "8080",
680 * SESSION_KEY: Redacted.make(process.env.SESSION_KEY!),
681 * },
682 * }) {}
683 * ```
684 *
685 * ### Props from Other Resources
686 * A class body is module scope, so there is nowhere to `yield*` the
687 * database, queue, or bucket whose output you need — and a bare
688 * declaration is an Effect, not a resolved handle, so
689 * `Uploads.bucketName` reads as `undefined`. Pass the props as an
690 * `Effect.gen` instead: inside it sibling resources resolve normally,
691 * and the reference orders the deploy.
692 *
693 * **Example:** Threading a sibling resource's output into `env`
694 * ```typescript
695 * export const Uploads = Cloudflare.R2.Bucket("Uploads");
696 *
697 * export class Api extends Cloudflare.Container<Api>()(
698 * "Api",
699 * Effect.gen(function* () {
700 * const uploads = yield* Uploads;
701 * return {
702 * context: `${import.meta.dirname}/api`,
703 * env: { BUCKET_NAME: uploads.bucketName },
704 * };
705 * }),
706 * ) {}
707 * ```
708 *
709 * ### Database Connections
710 * An effectful (`main`) container runs your Effect program, so it
711 * resolves a database capability the same way a Worker does — you never
712 * name `DATABASE_URL`. The container has no bindings (it is a process,
713 * not a Worker), so `Prisma.Connect` writes the connection's outputs
714 * onto the deployment as environment variables and reads them back at
715 * runtime; the capability owns both ends.
716 *
717 * **Example:** Binding a Prisma connection inside the container runtime
718 * ```typescript
719 * export default Api.make(
720 * { main: import.meta.url },
721 * Effect.gen(function* () {
722 * const db = yield* Prisma.Connect(Connection);
723 * const sql = yield* SQL.Postgres({ url: db.databaseUrl });
724 *
725 * return Api.of({
726 * fetch: Effect.gen(function* () {
727 * const users = yield* sql`SELECT * FROM users`;
728 * return yield* HttpServerResponse.json(users);
729 * }),
730 * });
731 * }).pipe(Effect.provide(Prisma.ConnectBinding)),
732 * );
733 * ```
734 *
735 * An image you brought yourself knows nothing about alchemy, so there is
736 * no capability to bind — name the variable and hand it the provider's
737 * **pooled** connection string.
738 *
739 * **Example:** Passing a pooled database URL to an arbitrary image
740 * ```typescript
741 * export class Web extends Cloudflare.Container<Web>()(
742 * "Web",
743 * Effect.gen(function* () {
744 * const connection = yield* Connection;
745 * return {
746 * context: `${import.meta.dirname}/web`,
747 * env: { DATABASE_URL: connection.databaseUrl },
748 * };
749 * }),
750 * ) {}
751 * ```
752 *
753 * Either way, start it with `api.start({ enableInternet: true })` — without
754 * outbound networking the container never reaches the database.
755 * `Cloudflare.Hyperdrive.Connect` is the one that cannot work here: it
756 * *is* a workerd binding, so no container process can resolve it.
757 *
758 * ### Stack-level wiring
759 * The `.make()` `export default` is the side-effect that registers
760 * the container's runtime. It must be reachable from your
761 * `alchemy.run.ts` so the bundler emits the runtime entrypoint.
762 * Provide it on the Stack's generator with `Effect.provide`.
763 *
764 * **Example:** Wiring SandboxLive into the Stack
765 * ```typescript
766 * // alchemy.run.ts
767 * import SandboxLive from "./src/Sandbox.runtime.ts";
768 *
769 * export default Alchemy.Stack(
770 * "MyApp",
771 * { providers: Cloudflare.providers(), state: Cloudflare.state() },
772 * Effect.gen(function* () {
773 * const worker = yield* Worker;
774 * return { url: worker.url };
775 * }).pipe(Effect.provide(SandboxLive)),
776 * );
777 * ```
778 *
779 * ### Calling from a Durable Object
780 * `yield* Sandbox` binds the container to the Durable Object and returns
781 * its handle: every method declared on the container's shape, plus
782 * `start`, `running`, `destroy`, `getTcpPort`, `exec` and the rest of the
783 * native container API. Binding never starts the container. Because only
784 * the class is imported, the runtime implementation in
785 * `Sandbox.runtime.ts` is tree-shaken out of the DO's bundle.
786 *
787 * `start()` is idempotent: it starts the container unless it is already
788 * running, and concurrent calls start it once. Call it at the top of each
789 * operation. Its options apply only when that call actually starts the
790 * container. RPC methods and ports wait until the container's port accepts
791 * connections, but never start it: a stopped container fails with
792 * `ContainerNotRunningError`.
793 *
794 * **Example:** Starting a container from a DO
795 * ```typescript
796 * export default class Agent extends Cloudflare.DurableObject<Agent>()(
797 * "Agents",
798 * Effect.gen(function* () {
799 * const sandbox = yield* Sandbox;
800 *
801 * return Effect.gen(function* () {
802 * // An Effect is a lazy value: define "start" once, run it per call.
803 * const start = sandbox.start({ enableInternet: true });
804 * return {
805 * shell: (cmd: string) => start.pipe(Effect.andThen(sandbox.shell(cmd))),
806 * };
807 * });
808 * }),
809 * ) {}
810 * ```
811 *
812 * A container's shape cannot declare a method the handle already has
813 * (`start`, `exec`, `image`, `getTcpPort`, …); declaring one is a type
814 * error, because the handle's method would shadow the RPC call.
815 *
816 * ### Using a Container from a Layer
817 * A Layer can `yield*` a container like any other service. It runs in the
818 * Durable Object that hosts it, and starts the container when an operation
819 * needs it. Layers never stop a shared container; let it sleep through
820 * `setInactivityTimeout`, or stop it from the Durable Object that owns it.
821 *
822 * **Example:** A service backed by a container
823 * ```typescript
824 * export const WriteFileLive = Layer.effect(
825 * WriteFile,
826 * Effect.gen(function* () {
827 * const devBox = yield* DevBox;
828 * const start = devBox.start({ enableInternet: true });
829 *
830 * return ({ path, contents }) =>
831 * start.pipe(Effect.andThen(devBox.writeFile(path, contents)));
832 * }),
833 * );
834 * ```
835 *
836 * ### HTTP Requests to Container Ports
837 * Use `getTcpPort` to get a `fetch` handle for a port inside the
838 * container. Each request waits until the port accepts connections, then
839 * is sent once.
840 *
841 * **Example:** Fetching from a container port
842 * ```typescript
843 * export default class Agent extends Cloudflare.DurableObject<Agent>()(
844 * "Agents",
845 * Effect.gen(function* () {
846 * const sandbox = yield* Sandbox;
847 *
848 * return Effect.gen(function* () {
849 * const { fetch } = yield* sandbox.getTcpPort(3000);
850 *
851 * return {
852 * health: () =>
853 * Effect.gen(function* () {
854 * yield* sandbox.start({ enableInternet: true });
855 * const response = yield* fetch(
856 * HttpClientRequest.get("http://container/health"),
857 * );
858 * return yield* response.text;
859 * }),
860 * };
861 * });
862 * }),
863 * ) {}
864 * ```
865 *
866 * @resource
867 * @product Containers
868 * @category Workers & Compute
869 */
870 export const Container: ResourceClassLike<ContainerApplication> &
871 Pick<ResourceClass<ContainerApplication>, "ref"> & {
872 <DOShape = unknown, const Id extends string = string, PropsReq = never>(
873 id: Id,
874 props: ImageContainerProps<PropsReq>,
875 ): Container.Decl<Container<Id>, {}, Id, PropsReq, DOShape>;
876 <Self>(): {
877 <const Id extends string, PropsReq = never>(
878 id: Id,
879 props: ImageContainerProps<PropsReq>,
880 ): Container.Decl<Self, {}, Id, PropsReq>;
881 };
882 <Self, Shape extends ContainerShape<Shape>>(): {
883 <const Id extends string>(
884 id: Id,
885 ): Container.Decl<Self, Shape, Id, Container.Application<Self>>;
886 };
887 } = Object.assign(
888 (...args: any[]) => {
889 if (args.length === 0) {
890 return (...args: any[]) => {
891 if (args.length === 1) {
892 const [id] = args as [string];
893 const tag = ContainerPlatform()(id);
894 // `yield* MyContainer` binds the container to the hosting Durable
895 // Object and returns its handle. It never starts the container.
896 // NOTE: no `~alchemy/Container/ClassName` marker here — an
897 // effectful (`main`) container is not bindable on an async
898 // Worker's `env` (its application is created by the `.make()`
899 // Layer inside an Effect-native Durable Object host), so it must
900 // not be picked up by bindWorkerAsyncBindings' container branch.
901 return Object.assign(effectClass(makeContainerHandle(id, ContainerPlatform.bind(tag))), {
902 "~alchemy/Id": id,
903 make: (props: any, impl: any) => tag.make(props, impl),
904 // yield* MyContainer.Application to get the ContainerApplication Resource Outputs
905 Application: tag,
906 of: (shape: any) => shape,
907 });
908 } else {
909 return Container(...(args as [string, any]));
910 }
911 };
912 } else {
913 const [id, props] = args as [string, any];
914 const resource = ContainerPlatform(id, props);
915 return Object.assign(effectClass(makeContainerHandle(id, ContainerPlatform.bind(resource))), {
916 "~alchemy/Id": id,
917 // The Durable Object class name this container backs when bound on
918 // an async Worker's `env` (see bindWorkerAsyncBindings). Defaults to
919 // the binding name at bind time when no explicit `className` is set.
920 // Effect-valued props cannot be read synchronously here, so carry
921 // the unresolved lookup and let `bindContainerClass` await it.
922 "~alchemy/Container/ClassName": Effect.isEffect(props)
923 ? Effect.map(
924 // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- props are untyped; Effect-valued props are resolved by the engine
925 props as Effect.Effect<{ className?: string } | undefined>,
926 (resolved) => resolved?.className,
927 )
928 : (props as { className?: string })?.className,
929 // yield* MyContainer.Application to get the ContainerApplication Resource Outputs
930 Application: resource,
931 of: (shape: any) => shape,
932 });
933 }
934 },
935 {
936 Type: ContainerTypeId,
937 // Read `ContainerPlatform` lazily: this module and ContainerPlatform.ts
938 // import each other, so it may not be initialized at module load.
939 ref: (id: string, options?: { stage?: string; stack?: string }) =>
940 (ContainerPlatform as unknown as Pick<ResourceClass<ContainerApplication>, "ref">).ref(
941 id,
942 options,
943 ),
944 },
945 ) as any;
946
947 export declare namespace Container {
948 export interface Decl<
949 Self = any,
950 Shape = any,
951 Id extends string = string,
952 Req = never,
953 DOShape = unknown,
954 >
955 extends Effect.Effect<Self, never, Providers | Req>, Rpc<Shape>, Named<Id> {
956 new (): Container<Id> & Shape;
957 /**
958 * @internal phantom — the Durable Object class type backing this
959 * container when it is bound on an async Worker's `env`. Drives
960 * `InferEnv` (`env.NAME` becomes `DurableObjectNamespace<DOShape>`).
961 */
962 readonly "~alchemy/Container/Shape": DOShape;
963 /**
964 * @internal — the explicit `className` from props (`undefined` defaults
965 * to the binding name at bind time). Doubles as the runtime marker that
966 * identifies an async-bindable Container declaration in a Worker's `env`
967 * (see `bindWorkerAsyncBindings`).
968 */
969 readonly "~alchemy/Container/ClassName": string | undefined | Effect.Effect<string | undefined>;
970 /**
971 * The underlying {@link ContainerApplication} resource declaration —
972 * `yield*` it to get the application's Output attributes.
973 */
974 Application: Effect.Effect<ContainerApplication<Self>, never, Providers | Req>;
975 make: <InitReq = never, WorkerReq = never, PropsReq = never>(
976 props:
977 | InputProps<EffectfulContainerProps>
978 | Effect.Effect<InputProps<EffectfulContainerProps>, Config.ConfigError, PropsReq>,
979 impl: Effect.Effect<Shape & WorkerShape<WorkerReq>, Config.ConfigError, InitReq>,
980 ) => Layer.Layer<Application<Self>, never, Providers>;
981 of(shape: Shape & WorkerShape): Shape;
982 }
983 export namespace Decl {
984 export type Any = Decl<any, any, string, any, any>;
985 }
986
987 export interface Application<Self> {
988 "~alchemy/Kind": "ContainerApplication";
989 "~alchemy/Self": Self;
990 }
991
992 export type Instance<Shape = any> = Container & Shape;
993 }