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, 06:00 UTC
| 1 | --- |
| 2 | title: Run a Container |
| 3 | description: Run a long-lived container alongside a Durable Object, expose RPC methods, and proxy HTTP requests to ports inside the container. |
| 4 | sidebar: |
| 5 | order: 11 |
| 6 | --- |
| 7 | |
| 8 | Some workloads need a long-lived process — a sandboxed shell, a |
| 9 | database client, a binary you can't compile to wasm. In this part |
| 10 | you'll add a **Cloudflare Container** that runs alongside a Durable |
| 11 | Object instance, and call into it to execute shell commands. |
| 12 | |
| 13 | ## Declare the Sandbox class |
| 14 | |
| 15 | Create `src/Sandbox.ts`. A Container is declared with the **tagged |
| 16 | shape** — a second type parameter that pins the public RPC surface, |
| 17 | analogous to declaring an Effect `Context.Service`. The type lists |
| 18 | every method callers can invoke, and the runtime implementation has |
| 19 | to match. The tag takes only the container's name; configuration |
| 20 | like the entrypoint file lives on `.make()` (next step), not here: |
| 21 | |
| 22 | ```typescript |
| 23 | // src/Sandbox.ts |
| 24 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 25 | import * as Effect from "effect/Effect"; |
| 26 | import type { PlatformError } from "effect/PlatformError"; |
| 27 | |
| 28 | export class Sandbox extends Cloudflare.Container< |
| 29 | Sandbox, |
| 30 | { |
| 31 | shell: (command: string) => Effect.Effect< |
| 32 | { exitCode: number; stdout: string; stderr: string }, |
| 33 | PlatformError |
| 34 | >; |
| 35 | } |
| 36 | >()("Sandbox") {} |
| 37 | ``` |
| 38 | |
| 39 | The `Cloudflare.Container<Sandbox, { ... }>()(...)` shape is the same |
| 40 | ceremony as `DurableObject` — the empty `()` lets TypeScript |
| 41 | capture the class identity for the typed RPC stub. Anything that |
| 42 | binds `Sandbox` now sees `exec(command)` as a typed RPC method |
| 43 | returning `Effect<{ exitCode, stdout, stderr }, PlatformError>`. |
| 44 | |
| 45 | ## Add the runtime file |
| 46 | |
| 47 | The class above is just a typed identifier — it has no |
| 48 | implementation yet. Containers always split the implementation |
| 49 | into a **separate file** because the Durable Object that binds the |
| 50 | container imports the class. If the runtime lived in the same |
| 51 | file, the DO bundle would pull in process spawners, Node APIs, |
| 52 | SDKs, etc. and Cloudflare Workers would reject it. |
| 53 | |
| 54 | Create `src/Sandbox.runtime.ts` with an empty `.make()` shell. The |
| 55 | container's deploy-time props — `main` (the entrypoint file) and |
| 56 | anything else — are the **first argument** to `.make()`; the |
| 57 | runtime implementation is the second: |
| 58 | |
| 59 | ```typescript |
| 60 | // src/Sandbox.runtime.ts |
| 61 | import * as Effect from "effect/Effect"; |
| 62 | import { Sandbox } from "./Sandbox.ts"; |
| 63 | |
| 64 | export const SandboxLive = Sandbox.make( |
| 65 | { main: import.meta.url }, |
| 66 | Effect.gen(function* () { |
| 67 | return Sandbox.of({ |
| 68 | // exec + fetch will go here |
| 69 | }); |
| 70 | }), |
| 71 | ); |
| 72 | |
| 73 | export default SandboxLive; |
| 74 | ``` |
| 75 | |
| 76 | `Sandbox.of(...)` is an identity function carrying the container's |
| 77 | typed shape — it ensures your implementation matches the interface |
| 78 | you declared on the class. Right now it complains because `exec` |
| 79 | is missing. Let's fill it in. |
| 80 | |
| 81 | ## Customize per stage |
| 82 | |
| 83 | The container's deploy-time props can read the surrounding Stack |
| 84 | through `Stack.useSync`. Pass it as `.make()`'s first argument to |
| 85 | pick a beefier instance type in `prod` and the cheap `dev` instance |
| 86 | everywhere else: |
| 87 | |
| 88 | ```diff lang="typescript" |
| 89 | // src/Sandbox.runtime.ts |
| 90 | import * as Effect from "effect/Effect"; |
| 91 | +import { Stack } from "alchemy/Stack"; |
| 92 | import { Sandbox } from "./Sandbox.ts"; |
| 93 | |
| 94 | export const SandboxLive = Sandbox.make( |
| 95 | - { main: import.meta.url }, |
| 96 | + Stack.useSync((stack) => ({ |
| 97 | + main: import.meta.url, |
| 98 | + instanceType: stack.stage === "prod" ? "standard-1" : "dev", |
| 99 | + observability: { logs: { enabled: true } }, |
| 100 | + })), |
| 101 | Effect.gen(function* () { |
| 102 | return Sandbox.of({ |
| 103 | // exec + fetch will go here |
| 104 | }); |
| 105 | }), |
| 106 | ); |
| 107 | ``` |
| 108 | |
| 109 | `Stack.useSync` is the synchronous accessor for any data in the |
| 110 | surrounding Effect context — handy for stack-level config like |
| 111 | stage, app name, or anything else you'd want to vary per |
| 112 | environment. |
| 113 | |
| 114 | To reuse matching image builds across stages, configure `publish.repository` |
| 115 | in these same props; see [Share published images across stages](/cloudflare/compute/containers#share-published-images-across-stages). |
| 116 | |
| 117 | ## Implement `exec` as an RPC method |
| 118 | |
| 119 | Containers have **RPC methods** — the same pattern you used on |
| 120 | the `Counter` Durable Object in |
| 121 | [Add a Durable Object](/cloudflare/compute/durable-objects). |
| 122 | Anything you return from `Sandbox.of({ ... })` whose value is an |
| 123 | `Effect` becomes a typed RPC method that callers can invoke |
| 124 | through the typed handle. |
| 125 | |
| 126 | The interface declared on the class promised an `exec(command)` |
| 127 | method. Implement it now: |
| 128 | |
| 129 | ```diff lang="typescript" |
| 130 | // src/Sandbox.runtime.ts |
| 131 | import * as Effect from "effect/Effect"; |
| 132 | +import * as Stream from "effect/Stream"; |
| 133 | +import * as ChildProcess from "effect/process/ChildProcess"; |
| 134 | +import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner"; |
| 135 | import { Sandbox } from "./Sandbox.ts"; |
| 136 | |
| 137 | export const SandboxLive = Sandbox.make( |
| 138 | Stack.useSync((stack) => ({ main: import.meta.url, /* ... */ })), |
| 139 | Effect.gen(function* () { |
| 140 | + const cp = yield* ChildProcessSpawner; |
| 141 | |
| 142 | return Sandbox.of({ |
| 143 | + shell: (command) => |
| 144 | + cp |
| 145 | + .spawn(ChildProcess.make(command, { shell: true })) |
| 146 | + .pipe( |
| 147 | + Effect.flatMap((handle) => |
| 148 | + Effect.all( |
| 149 | + [ |
| 150 | + handle.exitCode, |
| 151 | + handle.stdout.pipe(Stream.decodeText, Stream.mkString), |
| 152 | + handle.stderr.pipe(Stream.decodeText, Stream.mkString), |
| 153 | + ], |
| 154 | + { concurrency: "unbounded" }, |
| 155 | + ), |
| 156 | + ), |
| 157 | + Effect.map(([exitCode, stdout, stderr]) => ({ |
| 158 | + exitCode, |
| 159 | + stdout, |
| 160 | + stderr, |
| 161 | + })), |
| 162 | + Effect.scoped, |
| 163 | + ), |
| 164 | }); |
| 165 | }), |
| 166 | ); |
| 167 | |
| 168 | export default SandboxLive; |
| 169 | ``` |
| 170 | |
| 171 | The body shells out via Effect's `ChildProcessSpawner` and |
| 172 | collects stdout/stderr/exit code, but the **shape** is what |
| 173 | matters: a function returning an `Effect` becomes a typed RPC |
| 174 | method. When the Durable Object calls `sandbox.shell("echo hi")`, |
| 175 | it gets back an `Effect<{ exitCode, stdout, stderr }>` — exactly the |
| 176 | type declared on the class. |
| 177 | |
| 178 | :::note |
| 179 | A container's methods can't reuse the names of the container handle's |
| 180 | own methods (`start`, `exec`, `getTcpPort`, …). That's why this one is |
| 181 | called `shell`. |
| 182 | ::: |
| 183 | |
| 184 | ## Add an HTTP handler |
| 185 | |
| 186 | A container can also serve HTTP. Add a `fetch` field — Alchemy |
| 187 | binds it to port `3000` inside the container by default, so any |
| 188 | HTTP server you'd normally run inside Docker just works: |
| 189 | |
| 190 | ```diff lang="typescript" |
| 191 | // src/Sandbox.runtime.ts |
| 192 | import * as Effect from "effect/Effect"; |
| 193 | import * as Stream from "effect/Stream"; |
| 194 | +import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 195 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 196 | import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner"; |
| 197 | import { Sandbox } from "./Sandbox.ts"; |
| 198 | |
| 199 | export const SandboxLive = Sandbox.make( |
| 200 | Stack.useSync((stack) => ({ main: import.meta.url, /* ... */ })), |
| 201 | Effect.gen(function* () { |
| 202 | const cp = yield* ChildProcessSpawner; |
| 203 | |
| 204 | return Sandbox.of({ |
| 205 | shell: /* ... unchanged ... */, |
| 206 | + fetch: Effect.succeed( |
| 207 | + HttpServerResponse.text("Hello from the Sandbox container!"), |
| 208 | + ), |
| 209 | }); |
| 210 | }), |
| 211 | ); |
| 212 | ``` |
| 213 | |
| 214 | `fetch` and RPC methods like `shell` are independent — a caller |
| 215 | decides which they want by either calling `getTcpPort(3000).fetch` |
| 216 | (HTTP) or invoking `.shell(...)` directly (RPC). We'll use both |
| 217 | later in the bonus section. |
| 218 | |
| 219 | ## Bind the container from a Durable Object |
| 220 | |
| 221 | Workers don't talk to containers directly — every container has a |
| 222 | **Durable Object in front of it** that owns its lifecycle. Create |
| 223 | `src/Agent.ts` with the bare DO shell that imports the `Sandbox` |
| 224 | class: |
| 225 | |
| 226 | ```typescript |
| 227 | // src/Agent.ts |
| 228 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 229 | import * as Effect from "effect/Effect"; |
| 230 | import { Sandbox } from "./Sandbox.ts"; |
| 231 | |
| 232 | export default class Agent extends Cloudflare.DurableObject<Agent>()( |
| 233 | "Agents", |
| 234 | Effect.gen(function* () { |
| 235 | return Effect.gen(function* () { |
| 236 | return {}; |
| 237 | }); |
| 238 | }), |
| 239 | ) {} |
| 240 | ``` |
| 241 | |
| 242 | Importing `Sandbox` (the class) does **not** pull in the runtime — |
| 243 | that lives in `Sandbox.runtime.ts` and Rolldown tree-shakes it out. |
| 244 | |
| 245 | ## Bind the container in the outer phase |
| 246 | |
| 247 | `yield* Sandbox` binds the container to the Durable Object and hands |
| 248 | you its handle: the typed shape you declared on the class, plus |
| 249 | `start`, `getTcpPort` and the rest of the container API. Resolve it in |
| 250 | the **outer** Construction phase: |
| 251 | |
| 252 | ```diff lang="typescript" |
| 253 | export default class Agent extends Cloudflare.DurableObject<Agent>()( |
| 254 | "Agents", |
| 255 | Effect.gen(function* () { |
| 256 | + const sandbox = yield* Sandbox; |
| 257 | |
| 258 | return Effect.gen(function* () { |
| 259 | return {}; |
| 260 | }); |
| 261 | }), |
| 262 | ) {} |
| 263 | ``` |
| 264 | |
| 265 | Binding never starts the container. It only registers the container |
| 266 | with the Durable Object. |
| 267 | |
| 268 | ## Start the container before calling it |
| 269 | |
| 270 | Define how to start the container once, and run it at the top of |
| 271 | every operation that needs the container: |
| 272 | |
| 273 | ```diff lang="typescript" |
| 274 | export default class Agent extends Cloudflare.DurableObject<Agent>()( |
| 275 | "Agents", |
| 276 | Effect.gen(function* () { |
| 277 | const sandbox = yield* Sandbox; |
| 278 | |
| 279 | return Effect.gen(function* () { |
| 280 | - return {}; |
| 281 | + const start = sandbox.start({ enableInternet: true }); |
| 282 | + return { |
| 283 | + exec: (command: string) => |
| 284 | + start.pipe(Effect.andThen(sandbox.shell(command))), |
| 285 | + }; |
| 286 | }); |
| 287 | }), |
| 288 | ) {} |
| 289 | ``` |
| 290 | |
| 291 | `start` is idempotent: it starts the container unless it is already |
| 292 | running, and concurrent calls start it once. A container that stopped |
| 293 | or crashed since the last request starts again on the next one. The DO |
| 294 | is now a thin RPC bridge: callers invoke `agent.exec(cmd)`, and the DO |
| 295 | starts the container and forwards to `sandbox.shell(cmd)`. |
| 296 | |
| 297 | ## Wire the Container into the Stack |
| 298 | |
| 299 | The Container's `.make()` is the side-effect that registers the |
| 300 | runtime — it has to be reachable from `alchemy.run.ts`. Provide |
| 301 | `SandboxLive` to the Stack via `Effect.provide`: |
| 302 | |
| 303 | ```diff lang="typescript" |
| 304 | // alchemy.run.ts |
| 305 | import * as Alchemy from "alchemy"; |
| 306 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 307 | import * as Effect from "effect/Effect"; |
| 308 | +import SandboxLive from "./src/Sandbox.runtime.ts"; |
| 309 | import Worker from "./src/worker.ts"; |
| 310 | |
| 311 | export default Alchemy.Stack( |
| 312 | "MyApp", |
| 313 | { |
| 314 | providers: Cloudflare.providers(), |
| 315 | state: Cloudflare.state(), |
| 316 | }, |
| 317 | Effect.gen(function* () { |
| 318 | const worker = yield* Worker; |
| 319 | return { url: worker.url }; |
| 320 | + }).pipe(Effect.provide(SandboxLive)), |
| 321 | ); |
| 322 | ``` |
| 323 | |
| 324 | The Worker binds `Agent` and exposes the `/sandbox/exec` route: |
| 325 | |
| 326 | ```diff lang="typescript" |
| 327 | // src/worker.ts |
| 328 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 329 | import * as Effect from "effect/Effect"; |
| 330 | +import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 331 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 332 | +import Agent from "./Agent.ts"; |
| 333 | |
| 334 | export default Cloudflare.Worker( |
| 335 | "Worker", |
| 336 | { main: import.meta.url }, |
| 337 | Effect.gen(function* () { |
| 338 | + const agents = yield* Agent; |
| 339 | |
| 340 | return { |
| 341 | fetch: Effect.gen(function* () { |
| 342 | + const request = yield* HttpServerRequest; |
| 343 | + |
| 344 | + if (request.url === "/sandbox/exec" && request.method === "POST") { |
| 345 | + const command = yield* request.text; |
| 346 | + const result = yield* agents |
| 347 | + .getByName("default") |
| 348 | + .exec(command) |
| 349 | + .pipe(Effect.orDie); |
| 350 | + return yield* HttpServerResponse.json(result); |
| 351 | + } |
| 352 | + |
| 353 | return HttpServerResponse.text("Hello from my Worker!"); |
| 354 | }), |
| 355 | }; |
| 356 | }), |
| 357 | ); |
| 358 | ``` |
| 359 | |
| 360 | ## Deploy |
| 361 | |
| 362 | ```sh |
| 363 | bun alchemy deploy |
| 364 | ``` |
| 365 | |
| 366 | The first deploy uploads the container image to Cloudflare and |
| 367 | provisions the registry — expect it to take a minute or two longer |
| 368 | than usual. The image here is built for you from the `main` |
| 369 | entrypoint; to run a pre-built image instead, see |
| 370 | [Bring your own image](/cloudflare/compute/containers#bring-your-own-image) |
| 371 | and [Build & push images](/docker/build-and-push) in the Docker hub. |
| 372 | |
| 373 | ## Verify |
| 374 | |
| 375 | Add a test that POSTs a shell command and expects the captured |
| 376 | stdout in the response: |
| 377 | |
| 378 | ```diff lang="typescript" |
| 379 | // test/integ.test.ts |
| 380 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 381 | import * as Test from "@alchemy.run/test/Bun"; |
| 382 | import { expect } from "bun:test"; |
| 383 | import * as Effect from "effect/Effect"; |
| 384 | +import * as HttpBody from "effect/http/HttpBody"; |
| 385 | import * as HttpClient from "effect/http/HttpClient"; |
| 386 | import Stack from "../alchemy.run.ts"; |
| 387 | |
| 388 | const { test, beforeAll, deploy } = Test.make({ |
| 389 | providers: Cloudflare.providers(), |
| 390 | state: Cloudflare.state(), |
| 391 | }); |
| 392 | |
| 393 | const stack = beforeAll(deploy(Stack)); |
| 394 | |
| 395 | +test( |
| 396 | + "Sandbox container executes a shell command", |
| 397 | + Effect.gen(function* () { |
| 398 | + const { url } = yield* stack; |
| 399 | + |
| 400 | + const response = yield* HttpClient.post(`${url}/sandbox/exec`, { |
| 401 | + body: HttpBody.text("echo hi"), |
| 402 | + }); |
| 403 | + const body = yield* response.json; |
| 404 | + expect(body).toMatchObject({ stdout: "hi\n", exitCode: 0 }); |
| 405 | + }), |
| 406 | + { timeout: 60_000 }, |
| 407 | +); |
| 408 | ``` |
| 409 | |
| 410 | ```sh |
| 411 | bun test test/integ.test.ts |
| 412 | ``` |
| 413 | |
| 414 | The first request boots the container (which takes a few seconds — |
| 415 | hence the bumped timeout); subsequent requests reuse the warm |
| 416 | instance until Cloudflare evicts it for inactivity. |
| 417 | |
| 418 | ## Bonus: HTTP requests against a container port |
| 419 | |
| 420 | Containers can run any HTTP server. The `Sandbox.runtime.ts` above |
| 421 | exposes `fetch` on port `3000` by default. Add a `hello` RPC method |
| 422 | to `Agent.ts` that proxies to it via `getTcpPort`: |
| 423 | |
| 424 | ```diff lang="typescript" |
| 425 | // src/Agent.ts |
| 426 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 427 | import * as Effect from "effect/Effect"; |
| 428 | +import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 429 | import { Sandbox } from "./Sandbox.ts"; |
| 430 | |
| 431 | export default class Agent extends Cloudflare.DurableObject<Agent>()( |
| 432 | "Agents", |
| 433 | Effect.gen(function* () { |
| 434 | const sandbox = yield* Sandbox; |
| 435 | |
| 436 | return Effect.gen(function* () { |
| 437 | const start = sandbox.start({ enableInternet: true }); |
| 438 | return { |
| 439 | exec: (command: string) => |
| 440 | start.pipe(Effect.andThen(sandbox.shell(command))), |
| 441 | + hello: () => |
| 442 | + Effect.gen(function* () { |
| 443 | + yield* start; |
| 444 | + const { fetch } = yield* sandbox.getTcpPort(3000); |
| 445 | + const response = yield* fetch( |
| 446 | + HttpClientRequest.get("http://container/"), |
| 447 | + ); |
| 448 | + return yield* response.text; |
| 449 | + }), |
| 450 | }; |
| 451 | }); |
| 452 | }), |
| 453 | ) {} |
| 454 | ``` |
| 455 | |
| 456 | And the matching `/sandbox/hello` route on the Worker: |
| 457 | |
| 458 | ```diff lang="typescript" |
| 459 | // src/worker.ts (inside fetch) |
| 460 | if (request.url === "/sandbox/exec" && request.method === "POST") { |
| 461 | // ... unchanged ... |
| 462 | } |
| 463 | |
| 464 | +if (request.url === "/sandbox/hello") { |
| 465 | + const text = yield* agents |
| 466 | + .getByName("default") |
| 467 | + .hello() |
| 468 | + .pipe(Effect.orDie); |
| 469 | + return HttpServerResponse.text(text); |
| 470 | +} |
| 471 | ``` |
| 472 | |
| 473 | `getTcpPort(n)` returns a port whose `fetch` waits until the |
| 474 | container's server accepts connections, so you don't have to |
| 475 | coordinate readiness yourself. It never starts the container: call |
| 476 | `start` first. |
| 477 | |
| 478 | Next you'll [add a Workflow](/cloudflare/compute/workflows) to |
| 479 | orchestrate multi-step durable work that the container or DOs can |
| 480 | trigger — perfect for jobs that need to outlive any single request. |