@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 1,118 lines 43.5 KB
Raw
1 import { Unowned } from "alchemy/AdoptPolicy";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
6 import { toSeconds } from "alchemy/Util/Duration";
7 import { sha256, sha256Object } from "alchemy/Util/sha256";
8 import * as Data from "effect/Data";
9 import * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Equal from "effect/Equal";
12 import * as FileSystem from "effect/FileSystem";
13 import * as Path from "effect/Path";
14 import type { PlatformError } from "effect/PlatformError";
15 import * as Redacted from "effect/Redacted";
16 import { Docker, dockerContextName, dockerPhysicalName } from "./Docker.ts";
17 import { healthcheckCommand, isHealthcheckDisabled } from "./HealthcheckCommand.ts";
18 import type { Providers } from "./Providers.ts";
19
20 const CREATE_CONFIG_HASH_LABEL = "alchemy::container-config";
21
22 export interface ContainerProps {
23 /** Image reference or Docker image resource. */
24 image: Container.Image;
25 /** Docker context name or context resource. */
26 context?: Docker.ContextRef;
27 /**
28 * Container name.
29 *
30 * @default Generated from stack, stage, logical id, and instance id.
31 */
32 name?: string;
33 /** Command to run in the container. */
34 command?: string[];
35 /** Container environment variables. Use Redacted for secrets. */
36 environment?: Record<string, string | Redacted.Redacted<string>>;
37 /**
38 * Paths to Docker env files, forwarded in the declared order as repeated
39 * `--env-file` options. Explicit `environment` values are forwarded after
40 * these files and take precedence in Docker. Editing a file's contents
41 * replaces the container on the next deploy. Only a digest of the contents
42 * is kept, on the container's own label; neither contents nor digest are
43 * written to Alchemy state. Docker itself exposes the resolved values
44 * through `docker inspect`, so treat env files as secrets.
45 */
46 envFiles?: string[];
47 /** Host/container port mappings. */
48 ports?: Container.PortMapping[];
49 /** Volume or bind mounts. */
50 volumes?: Container.VolumeMapping[];
51 /** Restart policy. */
52 restart?: "no" | "always" | "on-failure" | "unless-stopped";
53 /**
54 * Container labels. Alchemy's internal ownership labels are added
55 * automatically.
56 */
57 labels?: Record<string, string>;
58 /**
59 * Grace period before Docker forcefully kills the container after stopping
60 * it.
61 */
62 stopTimeout?: Duration.Input;
63 /** Networks to connect after create. */
64 networks?: Container.NetworkMapping[];
65 /** Network namespace. Use `{ container: id }` to share another container's namespace. */
66 networkMode?: Container.NetworkMode;
67 /** Linux capabilities to add, for example `SYS_ADMIN`. */
68 capAdd?: string[];
69 /** Linux capabilities to drop, for example `["ALL"]`. */
70 capDrop?: string[];
71 /** Hard memory limit in Docker's byte-suffix format, e.g. `"512m"`. */
72 memory?: string;
73 /**
74 * Combined memory-plus-swap limit in Docker's byte-suffix format.
75 * Requires `memory`. Set to the same value to disable swap, or `"-1"`
76 * to allow unlimited swap (subject to the host).
77 */
78 memorySwap?: string;
79 /** Soft memory limit under contention, e.g. `"256m"`. */
80 memoryReservation?: string;
81 /** CPU quota, in cores (e.g. `0.5` limits to half a CPU). */
82 cpus?: number;
83 /** Maximum number of processes and threads in the container. */
84 pidsLimit?: number;
85 /** Mount the container's root filesystem read-only. Writable paths need a volume or tmpfs. */
86 readOnlyRootFilesystem?: boolean;
87 /** Prevent processes from gaining additional privileges through exec. */
88 noNewPrivileges?: boolean;
89 /** Run Docker's init process to forward signals and reap child processes. */
90 init?: boolean;
91 /** Runtime user, e.g. `"1000:1000"` or `"app"`. Omit to keep the image's user. */
92 user?: string;
93 /**
94 * Seccomp JSON profile path on the Docker CLI host, or `"builtin"` to
95 * select Docker's default policy. `"unconfined"` explicitly disables it.
96 * Changes to a profile file's contents recreate the container.
97 */
98 seccompProfile?: string;
99 /**
100 * Name of a preloaded AppArmor profile, e.g. `"docker-default"`.
101 * Requires AppArmor support on the target host. `"unconfined"` disables it.
102 */
103 appArmorProfile?: string;
104 /** Docker user-namespace mode. `"host"` opts out of daemon user remapping. */
105 userNamespace?: string;
106 /** Supplementary Linux group names or numeric GIDs. */
107 groupAdd?: string[];
108 /** Per-process resource limits. `-1` represents unlimited. */
109 ulimits?: Record<string, Container.Ulimit>;
110 /** Docker log driver, e.g. `"local"`, `"json-file"`, or `"none"`. */
111 logDriver?: string;
112 /** Driver-specific settings, such as `{ "max-size": "10m", "max-file": "3" }`. */
113 logOptions?: Record<string, string>;
114 /** Relative OOM score adjustment on Linux, from -1000 to 1000. */
115 oomScoreAdjustment?: number;
116 /** Stop signal, e.g. `"SIGTERM"` or `"SIGINT"`. */
117 stopSignal?: string;
118 /** Writable in-memory mounts, including size and POSIX mode controls. */
119 tmpfs?: Container.TmpfsMount[];
120 /** Host devices to expose to the container. */
121 devices?: Container.DeviceMapping[];
122 /**
123 * Extra `/etc/hosts` entries, each `hostname:address`. Docker's
124 * `host-gateway` alias resolves to the host machine, so
125 * `"host.docker.internal:host-gateway"` reaches services listening on the
126 * developer's machine from inside the container.
127 *
128 * On Linux `host-gateway` is the bridge gateway address, so those packets
129 * traverse the host's `INPUT` chain — under a default-deny firewall the
130 * name resolves and the connection then times out. See the Host Access
131 * examples.
132 */
133 extraHosts?: string[];
134 /** Remove the container when it exits. @default false */
135 removeOnExit?: boolean;
136 /** Start the container after creation/reconciliation. @default false */
137 start?: boolean;
138 /** Docker healthcheck configuration. */
139 healthcheck?: Container.Healthcheck;
140 }
141
142 export declare namespace Container {
143 type Status = "created" | "running" | "paused" | "restarting" | "removing" | "exited" | "dead";
144 type Image = string | { imageRef: string; imageId?: string };
145 interface PortMapping {
146 /** External port on the host. */
147 external: number | string;
148 /** Internal port inside the container. */
149 internal: number | string;
150 /** Protocol used for the mapping. @default "tcp" */
151 protocol?: "tcp" | "udp";
152 }
153 interface VolumeMapping {
154 /** Host path or named volume source. */
155 hostPath: string;
156 /** Container path. */
157 containerPath: string;
158 /** Mount read-only. @default false */
159 readOnly?: boolean;
160 }
161 interface TmpfsMount {
162 /** Absolute mount target in the container, e.g. `"/tmp"`. */
163 path: string;
164 /** Docker byte-suffix size, e.g. `"32m"`. Omit for the engine default. */
165 size?: string;
166 /** POSIX mode as a number, e.g. `0o1777` for a sticky world-writable directory. */
167 mode?: number;
168 }
169 interface Ulimit {
170 /** Process soft limit. `-1` means unlimited. */
171 soft: number;
172 /** Process hard limit. `-1` means unlimited. */
173 hard: number;
174 }
175 interface NetworkMapping {
176 /** Network name or ID. */
177 name: string;
178 /** Network aliases for the container. */
179 aliases?: string[];
180 }
181 type NetworkMode = string | { container: string };
182 interface DeviceMapping {
183 /** Host device path. */
184 hostPath: string;
185 /** Container device path. */
186 containerPath: string;
187 /** Cgroup permissions. @default "rwm" */
188 permissions?: string;
189 }
190 interface Healthcheck {
191 /**
192 * Command to run for health checks. A string runs in the container's
193 * shell. An array follows Docker's healthcheck `Test` form:
194 * `["CMD-SHELL", "pg_isready -U app"]`, `["CMD", "pg_isready", "-U", "app"]`,
195 * or `["NONE"]` to disable the image's healthcheck.
196 */
197 cmd: string[] | string;
198 /** Time between checks. */
199 interval?: Duration.Input;
200 /** Maximum time a check may run. */
201 timeout?: Duration.Input;
202 /** Consecutive failures before unhealthy. */
203 retries?: number;
204 /** Startup grace period. */
205 startPeriod?: Duration.Input;
206 /** Check interval during startup. Requires Docker API 1.44+. */
207 startInterval?: Duration.Input;
208 }
209 }
210
211 export interface Container extends Resource<
212 "Docker.Container",
213 ContainerProps,
214 {
215 /** Docker container id. */
216 id: string;
217 /** Docker container name. */
218 name: string;
219 /** Docker container state. */
220 status: Container.Status;
221 /** Creation timestamp in milliseconds since epoch. */
222 createdAt: number;
223 /** Image reference used to create the container. */
224 imageRef: string;
225 /**
226 * Map of internal container ports to their bound host ports.
227 * Format: `"80/tcp" -> 8080`.
228 */
229 ports: Record<string, number>;
230 /** Configured network namespace, when reported by Docker. */
231 networkMode?: string;
232 /** Added Linux capabilities, when reported by Docker. */
233 capAdd?: string[];
234 /** Configured host devices, when reported by Docker. */
235 devices?: Container.DeviceMapping[];
236 },
237 never,
238 Providers
239 > {}
240
241 /**
242 * A Docker container managed through the active Docker context.
243 *
244 * This resource creates, starts, stops, inspects, and removes containers through
245 * the Docker CLI. It is not interchangeable with `Cloudflare.Container`, which
246 * manages Cloudflare's container platform; use pushed image references to bridge
247 * Docker-built images into cloud container runtimes.
248 *
249 *
250 * ### Running Containers
251 * **Example:** Nginx with a published port
252 * ```typescript
253 * const nginx = yield* Docker.Container("nginx", {
254 * image: "nginx:alpine",
255 * ports: [{ external: 8080, internal: 80 }],
256 * start: true,
257 * });
258 * ```
259 *
260 * ### Secret Environment
261 * **Example:** Redacted env var
262 * ```typescript
263 * const password = yield* Config.Redacted("POSTGRES_PASSWORD");
264 * const db = yield* Docker.Container("postgres", {
265 * image: "postgres:18-alpine",
266 * environment: {
267 * POSTGRES_PASSWORD: password,
268 * },
269 * start: true,
270 * });
271 * ```
272 *
273 * ### Environment Files
274 * **Example:** Layered Docker env files
275 * ```typescript
276 * const app = yield* Docker.Container("app", {
277 * image: "ghcr.io/acme/app:latest",
278 * envFiles: ["./config/base.env", "./config/production.env"],
279 * // Explicit values are passed after env files and take precedence.
280 * environment: { LOG_LEVEL: "info" },
281 * });
282 * ```
283 *
284 * Editing an env file replaces the container on the next deploy, as does
285 * adopting a container that uses env files (once, so later edits are tracked).
286 * Alchemy reads
287 * the files at plan time but keeps only a digest of their contents, on the
288 * container's own label; neither the values nor the digest are written to
289 * Alchemy state. Docker exposes the resolved values through `docker inspect`,
290 * so treat env files as secrets.
291 *
292 * ### Networks and Volumes
293 * **Example:** PostgreSQL with persistent storage
294 * ```typescript
295 * const network = yield* Docker.Network("app-network");
296 * const data = yield* Docker.Volume("postgres-data");
297 * const postgresName = "app-postgres";
298 * yield* Docker.Container("postgres", {
299 * name: postgresName,
300 * image: "postgres:18-alpine",
301 * ports: [{ external: 15432, internal: 5432 }],
302 * volumes: [{ hostPath: data.name, containerPath: "/var/lib/postgresql/data" }],
303 * networks: [{ name: network.name, aliases: ["postgres"] }],
304 * start: true,
305 * });
306 * const runtime = yield* Docker.inspectContainer(postgresName);
307 * ```
308 *
309 * ### Host Access
310 * `extraHosts` writes lines into the container's `/etc/hosts`; it changes name
311 * resolution and nothing else. Docker's `host-gateway` alias resolves to the
312 * host machine, which is how a container reaches a service on the developer's
313 * loopback.
314 *
315 * On Linux `host-gateway` is the Docker bridge gateway (typically
316 * `172.17.0.1`), so a container's packets to it arrive on the host's `INPUT`
317 * chain. Under a default-deny firewall — ufw ships
318 * `DEFAULT_INPUT_POLICY="DROP"` — the hostname resolves correctly and the
319 * connection then times out, which reads like an application bug rather than a
320 * firewall one. Allow the bridge subnet to fix it:
321 * `sudo ufw allow from 172.16.0.0/12`.
322 *
323 * **Example:** Reach a service on the developer's machine
324 * ```typescript
325 * const api = yield* Docker.Container("api", {
326 * image: "ghcr.io/acme/api:latest",
327 * // `host-gateway` resolves to the host machine, so a database listening
328 * // on the developer's loopback is reachable from inside the container.
329 * extraHosts: ["host.docker.internal:host-gateway"],
330 * environment: {
331 * DATABASE_URL: "postgres://postgres@host.docker.internal:5432/app",
332 * },
333 * start: true,
334 * });
335 * ```
336 *
337 * **Example:** Pin a hostname to a fixed address
338 * ```typescript
339 * const api = yield* Docker.Container("api", {
340 * image: "ghcr.io/acme/api:latest",
341 * // Any `hostname:address` pair — host access is just the common case.
342 * extraHosts: ["service.example:192.0.2.10"],
343 * start: true,
344 * });
345 * ```
346 *
347 * ### Runtime Options
348 * **Example:** Contain a background worker
349 * ```typescript
350 * const worker = yield* Docker.Container("worker", {
351 * image: "oven/bun:1",
352 * memory: "512m",
353 * memorySwap: "512m",
354 * memoryReservation: "256m",
355 * cpus: 0.5,
356 * pidsLimit: 128,
357 * readOnlyRootFilesystem: true,
358 * capDrop: ["ALL"],
359 * noNewPrivileges: true,
360 * init: true,
361 * user: "1000:1000",
362 * tmpfs: [{ path: "/tmp", size: "32m", mode: 0o1777 }],
363 * });
364 * ```
365 *
366 * **Example:** Customize confinement, process limits, and log rotation
367 * ```typescript
368 * const api = yield* Docker.Container("api", {
369 * image: "ghcr.io/acme/api:latest",
370 * seccompProfile: "./security/api-seccomp.json", // client-side JSON; edits roll the container
371 * appArmorProfile: "my-loaded-profile", // must already be loaded on the host
372 * groupAdd: ["1000"],
373 * ulimits: { nofile: { soft: 1024, hard: 4096 } },
374 * logDriver: "local",
375 * logOptions: { "max-size": "10m", "max-file": "3" },
376 * oomScoreAdjustment: 200,
377 * stopSignal: "SIGTERM",
378 * });
379 * ```
380 *
381 * **Example:** Share a donor container's network namespace
382 * ```typescript
383 * const donor = yield* Docker.Container("donor", { image: "redis:alpine" });
384 * const sidecar = yield* Docker.Container("sidecar", {
385 * image: "busybox:latest",
386 * networkMode: { container: donor.id },
387 * });
388 * ```
389 *
390 * **Example:** Add capabilities and devices
391 * ```typescript
392 * const worker = yield* Docker.Container("worker", {
393 * image: "ubuntu:latest",
394 * capAdd: ["SYS_ADMIN"],
395 * devices: [{ hostPath: "/dev/fuse", containerPath: "/dev/fuse" }],
396 * });
397 * ```
398 *
399 * **Example:** Publish on any free host port
400 * ```typescript
401 * const api = yield* Docker.Container("api", {
402 * image: "ghcr.io/acme/api:latest",
403 * // `external: 0` lets Docker choose; the assigned port is reported back.
404 * ports: [{ external: 0, internal: 3000 }],
405 * start: true,
406 * });
407 * const hostPort = api.ports["3000/tcp"];
408 * ```
409 *
410 * ### Traefik
411 * **Example:** Route a container through Traefik
412 * ```typescript
413 * const api = yield* Docker.Container("api", {
414 * image: "ghcr.io/acme/api:latest",
415 * networks: [{ name: "traefik" }],
416 * labels: {
417 * "traefik.enable": "true",
418 * "traefik.http.routers.api.rule": "Host(`api.example.com`)",
419 * "traefik.http.services.api.loadbalancer.server.port": "3000",
420 * },
421 * stopTimeout: "30 seconds",
422 * start: true,
423 * });
424 * ```
425 *
426 * **Example:** Use a Docker.Context resource
427 * ```typescript
428 * const remote = yield* Docker.Context("remote", {
429 * name: "remote-build",
430 * docker: "host=ssh://docker@example.com",
431 * });
432 *
433 * const api = yield* Docker.Container("api", {
434 * image: "nginx:alpine",
435 * context: remote,
436 * });
437 * ```
438 *
439 * @resource
440 * @product Container
441 */
442 export const Container = Resource<Container>("Docker.Container");
443
444 /**
445 * Inspect a Docker container by name and return normalized runtime details.
446 *
447 * This is a small public wrapper around Docker's raw inspect output. It returns
448 * the stable data Alchemy callers typically need, including bound host ports.
449 */
450 export const inspectContainer = (
451 name: string,
452 context?: Docker.ContextRef,
453 ): Effect.Effect<Container["Attributes"], PlatformError, Docker> =>
454 Docker.pipe(
455 Effect.flatMap((docker) => docker.container.inspect(name, dockerContextName(context))),
456 Effect.map((container) => toContainerAttributes(container, container.Config.Image)),
457 );
458
459 export const ContainerProvider = () =>
460 Provider.effect(
461 Container,
462 Effect.gen(function* () {
463 const docker = yield* Docker;
464 const fs = yield* FileSystem.FileSystem;
465 const path = yield* Path.Path;
466
467 // Env files are read so editing one rolls the container, but only a
468 // digest of their bytes enters the config hash, which lives solely in
469 // the container's own label (where `docker inspect` already exposes
470 // the resolved values). Neither contents nor digest reach alchemy state.
471 const envFilesDigest = Effect.fn(function* (envFiles: ReadonlyArray<string> | undefined) {
472 if (!envFiles?.length) return undefined;
473 const digests = yield* Effect.forEach(envFiles, (file) =>
474 fs.readFile(path.resolve(file)).pipe(
475 Effect.flatMap(sha256),
476 Effect.map((digest) => `${file}\0${digest}`),
477 ),
478 );
479 return yield* sha256(digests.join("\n"));
480 });
481
482 // Docker CLI loads seccomp profiles from client-side files at create
483 // time. Hash the contents as well as the path so policy edits are never
484 // silently ignored on subsequent deploys.
485 const seccompProfileDigest = Effect.fn(function* (profile: string | undefined) {
486 if (!isCustomSeccompProfile(profile)) return undefined;
487 return yield* fs.readFile(path.resolve(profile)).pipe(Effect.flatMap(sha256));
488 });
489
490 // Without env files the hash input is unchanged from before they were
491 // supported, so existing containers keep their label and are not rolled.
492 const desiredConfigHash = Effect.fn(function* (
493 args: Parameters<Docker["Service"]["container"]["create"]>[0],
494 news: ContainerProps,
495 ) {
496 const envFiles = yield* envFilesDigest(news.envFiles);
497 const seccompProfile = yield* seccompProfileDigest(news.seccompProfile);
498 return yield* sha256Object({
499 ...args,
500 imageId: normalizeImageId(news.image),
501 ...(envFiles === undefined ? {} : { envFiles }),
502 ...(seccompProfile === undefined ? {} : { seccompProfile }),
503 });
504 });
505
506 const reconcileNetworks = Effect.fn(function* (
507 live: Docker.Container,
508 news: ContainerProps,
509 olds: ContainerProps | undefined,
510 ) {
511 const context = dockerContextName(news.context);
512 const connect = new Map<string, Container.NetworkMapping>();
513 const disconnect = new Set<string>();
514 for (const network of news.networks ?? []) {
515 const entry = live.NetworkSettings.Networks?.[network.name];
516 if (!entry) {
517 connect.set(network.name, network);
518 } else if (!Equal.equals(entry.Aliases ?? [], network.aliases ?? [])) {
519 connect.set(network.name, network);
520 disconnect.add(network.name);
521 }
522 }
523 // Only networks alchemy itself attached are alchemy's to detach, and
524 // `olds.networks` is the sole record of which those are — the live
525 // container cannot say who connected a network. Sweeping every live
526 // network instead tore off the default `bridge` and anything a user,
527 // compose file, or another tool had attached out of band (#1386).
528 const desired = new Set((news.networks ?? []).map((n) => n.name));
529 for (const network of olds?.networks ?? []) {
530 if (!desired.has(network.name) && live.NetworkSettings.Networks?.[network.name]) {
531 disconnect.add(network.name);
532 }
533 }
534 yield* Effect.forEach(
535 disconnect,
536 (network) => docker.network.disconnect({ network, container: live.Id, context }),
537 { concurrency: "unbounded" },
538 );
539 yield* Effect.forEach(
540 connect.values(),
541 (network) =>
542 docker.network.connect({
543 network: network.name,
544 container: live.Id,
545 alias: network.aliases,
546 context,
547 }),
548 { concurrency: "unbounded" },
549 );
550 });
551
552 const inspect = (name: string, context?: string) =>
553 docker.container
554 .inspect(name, context)
555 .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined));
556
557 const remove = (name: string, context?: string) =>
558 docker.container.stop(name, context).pipe(
559 Effect.andThen(docker.container.remove(name, true, context)),
560 Effect.catchReason("PlatformError", "NotFound", () => Effect.void),
561 );
562
563 return Container.Provider.of({
564 list: () => Effect.succeed([]),
565 read: Effect.fn(function* ({ id, instanceId, olds, output }) {
566 const context = dockerContextName(olds.context);
567 const name = yield* dockerPhysicalName(id, olds, instanceId);
568 const info = yield* inspect(name, context);
569 if (!info) return undefined;
570 // `olds.image` may be `undefined` when a `creating` row was
571 // persisted before upstream Outputs resolved — fall back to the
572 // live container's actual image.
573 const attrs = toContainerAttributes(
574 info,
575 olds.image !== undefined ? normalizeImageRef(olds.image) : info.Config.Image,
576 );
577 if (output) return attrs;
578 // Without prior state, only adopt a container that carries our
579 // branding; anything else is foreign and gated behind `--adopt`.
580 const owned = yield* hasAlchemyTags(id, info.Config.Labels ?? undefined);
581 return owned ? attrs : Unowned(attrs);
582 }),
583 diff: Effect.fn(function* ({ id, instanceId, news, olds }) {
584 if (!isResolved(news)) return undefined;
585 // An Output-valued `image` doesn't survive a `creating`-state
586 // round-trip (it deserializes as `undefined`) — without comparable
587 // prior create args, let the engine apply its default update logic.
588 if (olds.image === undefined) return undefined;
589 if (dockerContextName(olds.context) !== dockerContextName(news.context)) {
590 return { action: "replace" as const, deleteFirst: true };
591 }
592 const oldArgs = yield* makeCreateArgs(id, olds, instanceId);
593 const newArgs = yield* makeCreateArgs(id, news, instanceId);
594 if (!Equal.equals(oldArgs, newArgs)) {
595 return { action: "replace" as const, deleteFirst: true };
596 }
597 if (
598 !Equal.equals(olds.networks ?? [], news.networks ?? []) ||
599 (olds.start ?? false) !== (news.start ?? false)
600 ) {
601 return { action: "update" as const };
602 }
603 // File-backed inputs can change without changing their paths.
604 // Compare their digests against the live config hash.
605 if (news.envFiles?.length || isCustomSeccompProfile(news.seccompProfile)) {
606 const live = yield* inspect(newArgs.name, dockerContextName(news.context));
607 const applied = live?.Config.Labels?.[CREATE_CONFIG_HASH_LABEL];
608 if (applied !== undefined && applied !== (yield* desiredConfigHash(newArgs, news))) {
609 return { action: "update" as const };
610 }
611 }
612 }),
613 reconcile: Effect.fn(function* ({ id, instanceId, news, olds, output }) {
614 const context = dockerContextName(news.context);
615 const args = yield* makeCreateArgs(id, news, instanceId);
616 const configHash = yield* desiredConfigHash(args, news);
617 // Adoption has output but no olds. In that case the observed
618 // container already lives in the desired context.
619 const oldContext = olds ? dockerContextName(olds.context) : context;
620 const desiredLive = yield* inspect(args.name, context);
621 const previous =
622 output && (output.name !== args.name || oldContext !== context)
623 ? yield* inspect(output.name, oldContext)
624 : undefined;
625 if (previous) {
626 yield* remove(previous.Id, oldContext);
627 }
628 const live = desiredLive?.Id === previous?.Id ? undefined : desiredLive;
629
630 const oldArgs =
631 live?.Config.Labels?.[CREATE_CONFIG_HASH_LABEL] === undefined && olds !== undefined
632 ? yield* makeCreateArgs(
633 id,
634 {
635 ...olds,
636 image: olds.image ?? output?.imageRef ?? news.image,
637 },
638 instanceId,
639 )
640 : undefined;
641 const recreate =
642 live !== undefined &&
643 (live.Config.Labels?.[CREATE_CONFIG_HASH_LABEL] === undefined
644 ? (oldArgs !== undefined && !Equal.equals(oldArgs, args)) ||
645 normalizeImageId(olds?.image) !== normalizeImageId(news.image) ||
646 !matchesLegacyConfig(live, args, news.image) ||
647 // Env file contents can't be compared without a label (e.g. an
648 // adopted container); recreate once so later edits are tracked.
649 (news.envFiles?.length ?? 0) > 0 ||
650 isCustomSeccompProfile(news.seccompProfile) ||
651 // A legacy/adopted container has no stamped config hash.
652 // Do not retain it without proof that the requested security
653 // restrictions were applied.
654 hasHardeningOptions(news)
655 : live.Config.Labels[CREATE_CONFIG_HASH_LABEL] !== configHash);
656 if (recreate) {
657 yield* remove(live.Id, context);
658 }
659
660 const current = recreate ? undefined : live;
661 if (!current) {
662 const internalTags = yield* createInternalTags(id);
663 const { stdout: containerId } = yield* docker.container.create({
664 ...args,
665 context,
666 label: {
667 ...args.label,
668 ...internalTags,
669 [CREATE_CONFIG_HASH_LABEL]: configHash,
670 },
671 });
672 yield* Effect.forEach(
673 news.networks ?? [],
674 (network) =>
675 docker.network.connect({
676 network: network.name,
677 container: containerId,
678 alias: network.aliases,
679 context,
680 }),
681 { concurrency: "unbounded" },
682 );
683 if (news.start) {
684 yield* docker.container.start(containerId, context);
685 }
686 const info = yield* docker.container.inspect(containerId, context);
687 return toContainerAttributes(info, args.image);
688 }
689
690 yield* reconcileNetworks(current, news, olds);
691 if (news.start && current.State.Status !== "running") {
692 yield* docker.container.start(current.Id, context);
693 } else if (!news.start && current.State.Status === "running") {
694 yield* docker.container.stop(current.Id, context);
695 }
696 return yield* docker.container
697 .inspect(current.Id, context)
698 .pipe(Effect.map((info) => toContainerAttributes(info, args.image)));
699 }),
700 delete: Effect.fn(({ olds, output }) =>
701 remove(output.name, dockerContextName(olds.context)),
702 ),
703 });
704 }),
705 );
706
707 const normalizeImageRef = (image: Container.Image): string =>
708 typeof image === "string" ? image : image.imageRef;
709
710 const normalizeImageId = (image: Container.Image | undefined) =>
711 typeof image === "string" ? undefined : image?.imageId;
712
713 type CreateArgs = Parameters<Docker["Service"]["container"]["create"]>[0];
714
715 // Containers created before config hashes were introduced are compared using
716 // the fields Docker reports without image-default normalization. A subsequent
717 // create stamps the complete resolved configuration hash.
718 const matchesLegacyConfig = (live: Docker.Container, desired: CreateArgs, image: Container.Image) =>
719 (normalizeImageId(image)
720 ? live.Image === normalizeImageId(image)
721 : live.Config.Image === desired.image) &&
722 (desired.command === undefined || Equal.equals(live.Config.Cmd, desired.command)) &&
723 Object.entries(desired.env ?? {}).every(([key, value]) =>
724 live.Config.Env?.includes(`${key}=${value}`),
725 );
726
727 const makeCreateArgs = (id: string, news: ContainerProps, instanceId: string) =>
728 dockerPhysicalName(id, news, instanceId).pipe(
729 Effect.tap(() => validateContainerOptions(news)),
730 Effect.map((name): Parameters<Docker["Service"]["container"]["create"]>[0] => ({
731 name,
732 image: normalizeImageRef(news.image),
733 command: news.command,
734 env: normalizeEnvironment(news.environment),
735 "env-file": news.envFiles?.length ? news.envFiles : undefined,
736 volume: news.volumes?.map(
737 (v) => `${v.hostPath}:${v.containerPath}${v.readOnly ? ":ro" : ""}`,
738 ),
739 p: news.ports?.map((port) => {
740 const target = `${port.internal}/${port.protocol ?? "tcp"}`;
741 // `external: 0` means "any free host port". Docker spells that as a
742 // bare container port (`-p 80/tcp`); `-p 0:80/tcp` instead asks for
743 // host port 0 literally, which the daemon accepts and then reports
744 // back as 0.
745 return isRandomHostPort(port.external) ? target : `${port.external}:${target}`;
746 }),
747 "add-host": news.extraHosts,
748 network: normalizeNetworkMode(news.networkMode),
749 "cap-add": normalizeCapabilities(news.capAdd),
750 ...(news.capDrop?.length ? { "cap-drop": normalizeCapabilities(news.capDrop) } : {}),
751 ...(news.memory !== undefined ? { memory: news.memory } : {}),
752 ...(news.memorySwap !== undefined ? { "memory-swap": news.memorySwap } : {}),
753 ...(news.memoryReservation !== undefined
754 ? { "memory-reservation": news.memoryReservation }
755 : {}),
756 ...(news.cpus !== undefined ? { cpus: news.cpus } : {}),
757 ...(news.pidsLimit !== undefined ? { "pids-limit": news.pidsLimit } : {}),
758 ...(news.readOnlyRootFilesystem ? { "read-only": true } : {}),
759 ...(normalizeSecurityOptions(news) ? { "security-opt": normalizeSecurityOptions(news) } : {}),
760 ...(news.userNamespace !== undefined ? { userns: news.userNamespace } : {}),
761 ...(news.groupAdd?.length ? { "group-add": normalizeGroups(news.groupAdd) } : {}),
762 ...(Object.keys(news.ulimits ?? {}).length ? { ulimit: normalizeUlimits(news.ulimits) } : {}),
763 ...(news.logDriver !== undefined ? { "log-driver": news.logDriver } : {}),
764 ...(Object.keys(news.logOptions ?? {}).length
765 ? { "log-opt": normalizeLogOptions(news.logOptions) }
766 : {}),
767 ...(news.oomScoreAdjustment !== undefined
768 ? { "oom-score-adj": news.oomScoreAdjustment }
769 : {}),
770 ...(news.stopSignal !== undefined ? { "stop-signal": news.stopSignal } : {}),
771 ...(news.init ? { init: true } : {}),
772 ...(news.user !== undefined ? { user: news.user } : {}),
773 ...(news.tmpfs?.length ? { tmpfs: normalizeTmpfs(news.tmpfs) } : {}),
774 device: normalizeDevices(news.devices),
775 restart: news.restart ?? "no",
776 label: news.labels,
777 "stop-timeout": toSeconds(news.stopTimeout)?.toString(),
778 rm: news.removeOnExit ?? false,
779 ...(news.healthcheck
780 ? {
781 "health-cmd": healthcheckCommand(news.healthcheck.cmd),
782 // Only when set: an always-present key would change every
783 // container's config hash and recreate it on upgrade.
784 ...(isHealthcheckDisabled(news.healthcheck.cmd) ? { "no-healthcheck": true } : {}),
785 "health-interval": normalizeDuration(news.healthcheck.interval),
786 "health-timeout": normalizeDuration(news.healthcheck.timeout),
787 "health-retries": news.healthcheck.retries ?? 0,
788 "health-start-period": normalizeDuration(news.healthcheck.startPeriod),
789 "health-start-interval": normalizeDuration(news.healthcheck.startInterval),
790 }
791 : {
792 "health-cmd": undefined,
793 "health-interval": undefined,
794 "health-timeout": undefined,
795 "health-retries": undefined,
796 "health-start-period": undefined,
797 "health-start-interval": undefined,
798 }),
799 })),
800 );
801
802 const toContainerAttributes = (
803 info: Docker.Container,
804 imageRef: string,
805 ): Container["Attributes"] => ({
806 id: info.Id,
807 name: typeof info.Name === "string" ? info.Name.replace(/^\//, "") : info.Id,
808 status: info.State.Status,
809 createdAt: Date.parse(info.Created) || Date.now(),
810 imageRef,
811 ports: toPortAttributes(info),
812 networkMode: info.HostConfig.NetworkMode,
813 capAdd: info.HostConfig.CapAdd ?? undefined,
814 devices: info.HostConfig.Devices?.map((device) => ({
815 hostPath: device.PathOnHost,
816 containerPath: device.PathInContainer,
817 permissions: device.CgroupPermissions,
818 })),
819 });
820
821 const normalizeNetworkMode = (mode: Container.NetworkMode | undefined): string | undefined =>
822 mode === undefined ? undefined : typeof mode === "string" ? mode : `container:${mode.container}`;
823
824 const normalizeCapabilities = (capAdd: string[] | undefined): string[] | undefined => {
825 if (!capAdd?.length) return undefined;
826 return [...new Set(capAdd.map((capability) => capability.trim()).filter(Boolean))].sort();
827 };
828
829 const isCustomSeccompProfile = (profile: string | undefined): profile is string =>
830 profile !== undefined && profile !== "builtin" && profile !== "unconfined";
831
832 const normalizeSecurityOptions = (props: ContainerProps): string[] | undefined => {
833 const options = [
834 ...(props.noNewPrivileges ? ["no-new-privileges"] : []),
835 ...(props.seccompProfile ? [`seccomp=${props.seccompProfile}`] : []),
836 ...(props.appArmorProfile ? [`apparmor=${props.appArmorProfile}`] : []),
837 ];
838 return options.length ? options : undefined;
839 };
840
841 const normalizeGroups = (groups: string[]): string[] =>
842 [...new Set(groups.map((group) => group.trim()))].sort();
843
844 const normalizeUlimits = (limits: ContainerProps["ulimits"]): string[] =>
845 Object.entries(limits ?? {})
846 .sort(([left], [right]) => left.localeCompare(right))
847 .map(([name, { soft, hard }]) => `${name}=${soft}:${hard}`);
848
849 const normalizeLogOptions = (options: ContainerProps["logOptions"]): string[] =>
850 Object.entries(options ?? {})
851 .sort(([left], [right]) => left.localeCompare(right))
852 .map(([name, value]) => `${name}=${value}`);
853
854 const normalizeTmpfs = (mounts: Container.TmpfsMount[]): string[] =>
855 [...mounts]
856 .sort((a, b) => a.path.localeCompare(b.path))
857 .map(({ path, size, mode }) => {
858 const options = [
859 ...(size !== undefined ? [`size=${size}`] : []),
860 ...(mode !== undefined ? [`mode=${mode.toString(8)}`] : []),
861 ];
862 return options.length > 0 ? `${path}:${options.join(",")}` : path;
863 });
864
865 const hasHardeningOptions = (props: ContainerProps): boolean =>
866 (props.capDrop?.length ?? 0) > 0 ||
867 props.memory !== undefined ||
868 props.memorySwap !== undefined ||
869 props.memoryReservation !== undefined ||
870 props.cpus !== undefined ||
871 props.pidsLimit !== undefined ||
872 props.readOnlyRootFilesystem === true ||
873 props.noNewPrivileges === true ||
874 props.seccompProfile !== undefined ||
875 props.appArmorProfile !== undefined ||
876 props.userNamespace !== undefined ||
877 (props.groupAdd?.length ?? 0) > 0 ||
878 Object.keys(props.ulimits ?? {}).length > 0 ||
879 props.logDriver !== undefined ||
880 Object.keys(props.logOptions ?? {}).length > 0 ||
881 props.oomScoreAdjustment !== undefined ||
882 props.stopSignal !== undefined ||
883 props.init === true ||
884 props.user !== undefined ||
885 (props.tmpfs?.length ?? 0) > 0;
886
887 const normalizeDevices = (devices: Container.DeviceMapping[] | undefined): string[] | undefined => {
888 if (!devices?.length) return undefined;
889 const normalized = devices.map(
890 (device) => `${device.hostPath}:${device.containerPath}:${device.permissions ?? "rwm"}`,
891 );
892 return [...new Set(normalized)].sort();
893 };
894
895 /**
896 * Raised before Docker is called when a container's options cannot be
897 * combined, e.g. sharing another container's network namespace while
898 * publishing ports.
899 */
900 export class InvalidContainerOptions extends Data.TaggedError("InvalidContainerOptions")<{
901 readonly message: string;
902 }> {}
903
904 const validateContainerOptions = (news: ContainerProps) => {
905 // The CLI formatter omits empty strings. Reject them instead of silently
906 // dropping user-specified resource and security restrictions.
907 for (const option of [
908 "memory",
909 "memorySwap",
910 "memoryReservation",
911 "user",
912 "seccompProfile",
913 "appArmorProfile",
914 "userNamespace",
915 "logDriver",
916 "stopSignal",
917 ] as const) {
918 if (news[option] !== undefined && news[option].trim().length === 0) {
919 return Effect.fail(
920 new InvalidContainerOptions({
921 message: `Docker.Container ${option} cannot be empty`,
922 }),
923 );
924 }
925 }
926 if (news.capDrop?.some((capability) => capability.trim().length === 0)) {
927 return Effect.fail(
928 new InvalidContainerOptions({
929 message: "Docker.Container capDrop cannot contain empty capabilities",
930 }),
931 );
932 }
933 if (news.groupAdd?.some((group) => group.trim().length === 0)) {
934 return Effect.fail(
935 new InvalidContainerOptions({
936 message: "Docker.Container groupAdd cannot contain empty groups",
937 }),
938 );
939 }
940 for (const [name, limit] of Object.entries(news.ulimits ?? {})) {
941 if (
942 !/^[a-z][a-z0-9_-]*$/.test(name) ||
943 !Number.isSafeInteger(limit.soft) ||
944 !Number.isSafeInteger(limit.hard) ||
945 limit.soft < -1 ||
946 limit.hard < -1 ||
947 (limit.hard !== -1 && (limit.soft === -1 || limit.soft > limit.hard))
948 ) {
949 return Effect.fail(
950 new InvalidContainerOptions({
951 message: `Docker.Container ulimits contains an invalid soft/hard limit for ${name}`,
952 }),
953 );
954 }
955 }
956 for (const [name, value] of Object.entries(news.logOptions ?? {})) {
957 if (!name.trim() || name.includes("=") || !value.trim()) {
958 return Effect.fail(
959 new InvalidContainerOptions({
960 message: `Docker.Container logOptions contains an invalid option: ${name}`,
961 }),
962 );
963 }
964 }
965 if (
966 news.oomScoreAdjustment !== undefined &&
967 (!Number.isInteger(news.oomScoreAdjustment) ||
968 news.oomScoreAdjustment < -1000 ||
969 news.oomScoreAdjustment > 1000)
970 ) {
971 return Effect.fail(
972 new InvalidContainerOptions({
973 message: "Docker.Container oomScoreAdjustment must be an integer from -1000 to 1000",
974 }),
975 );
976 }
977 if (news.memorySwap !== undefined && news.memory === undefined) {
978 return Effect.fail(
979 new InvalidContainerOptions({
980 message: "Docker.Container memorySwap requires memory to be set",
981 }),
982 );
983 }
984 if (news.cpus !== undefined && (!Number.isFinite(news.cpus) || news.cpus <= 0)) {
985 return Effect.fail(
986 new InvalidContainerOptions({
987 message: "Docker.Container cpus must be a finite, positive number",
988 }),
989 );
990 }
991 if (
992 news.pidsLimit !== undefined &&
993 (!Number.isInteger(news.pidsLimit) || (news.pidsLimit <= 0 && news.pidsLimit !== -1))
994 ) {
995 return Effect.fail(
996 new InvalidContainerOptions({
997 message: "Docker.Container pidsLimit must be a positive integer or -1 (unlimited)",
998 }),
999 );
1000 }
1001 if (
1002 isContainerNetworkMode(news.networkMode) &&
1003 ((news.ports?.length ?? 0) > 0 || (news.networks?.length ?? 0) > 0)
1004 ) {
1005 return Effect.fail(
1006 new InvalidContainerOptions({
1007 message: "Docker.Container networkMode.container cannot be combined with ports or networks",
1008 }),
1009 );
1010 }
1011 const targets = new Set<string>();
1012 for (const device of news.devices ?? []) {
1013 if (targets.has(device.containerPath)) {
1014 return Effect.fail(
1015 new InvalidContainerOptions({
1016 message: `Docker.Container devices contain conflicting target path ${device.containerPath}`,
1017 }),
1018 );
1019 }
1020 targets.add(device.containerPath);
1021 }
1022 const tmpfsTargets = new Set<string>();
1023 for (const mount of news.tmpfs ?? []) {
1024 if (mount.size !== undefined && mount.size.trim().length === 0) {
1025 return Effect.fail(
1026 new InvalidContainerOptions({
1027 message: `Docker.Container tmpfs size cannot be empty for ${mount.path}`,
1028 }),
1029 );
1030 }
1031 if (!mount.path.startsWith("/") || mount.path.includes(":") || mount.path.includes(",")) {
1032 return Effect.fail(
1033 new InvalidContainerOptions({
1034 message: `Docker.Container tmpfs target must be an absolute path: ${mount.path}`,
1035 }),
1036 );
1037 }
1038 if (tmpfsTargets.has(mount.path)) {
1039 return Effect.fail(
1040 new InvalidContainerOptions({
1041 message: `Docker.Container tmpfs contains duplicate target ${mount.path}`,
1042 }),
1043 );
1044 }
1045 if (
1046 mount.mode !== undefined &&
1047 (!Number.isInteger(mount.mode) || mount.mode < 0 || mount.mode > 0o7777)
1048 ) {
1049 return Effect.fail(
1050 new InvalidContainerOptions({
1051 message: `Docker.Container tmpfs mode is not a valid POSIX mode for ${mount.path}`,
1052 }),
1053 );
1054 }
1055 tmpfsTargets.add(mount.path);
1056 }
1057 return Effect.void;
1058 };
1059
1060 const isContainerNetworkMode = (mode: Container.NetworkMode | undefined): boolean =>
1061 typeof mode === "string" ? mode.startsWith("container:") : mode !== undefined;
1062
1063 /** First binding that carries a real (non-zero) host port. */
1064 const boundHostPort = (
1065 bindings: ReadonlyArray<{ HostPort?: string }> | null | undefined,
1066 ): number | undefined => {
1067 for (const binding of bindings ?? []) {
1068 if (!binding.HostPort) continue;
1069 const port = Number.parseInt(binding.HostPort, 10);
1070 if (Number.isInteger(port) && port > 0) return port;
1071 }
1072 return undefined;
1073 };
1074
1075 /**
1076 * `HostConfig.PortBindings` is what was *requested*, `NetworkSettings.Ports`
1077 * what Docker actually *assigned* — so the assignment wins wherever both
1078 * exist. A container published with `external: 0` (or any random-publish
1079 * mapping) has no requested host port at all, and reading the request over
1080 * the assignment reported 0 instead of the port the container is reachable
1081 * on. The request is still the fallback: a created-but-not-yet-started
1082 * container has empty `NetworkSettings.Ports`.
1083 */
1084 const toPortAttributes = (info: Docker.Container): Record<string, number> => {
1085 const ports: Record<string, number> = {};
1086 for (const [internal, bindings] of Object.entries(info.HostConfig.PortBindings ?? {})) {
1087 const port = boundHostPort(bindings);
1088 if (port !== undefined) ports[internal] = port;
1089 }
1090 for (const [internal, bindings] of Object.entries(info.NetworkSettings.Ports ?? {})) {
1091 const port = boundHostPort(bindings);
1092 if (port !== undefined) ports[internal] = port;
1093 }
1094 return ports;
1095 };
1096
1097 /** `external: 0` / `"0"` asks Docker to pick any free host port. */
1098 const isRandomHostPort = (external: number | string): boolean =>
1099 Number.parseInt(String(external), 10) === 0;
1100
1101 const normalizeEnvironment = (
1102 environment: Record<string, string | Redacted.Redacted<string>> | undefined,
1103 ): Record<string, string> =>
1104 Object.fromEntries(
1105 Object.entries(environment ?? {}).map(([key, value]) => [
1106 key,
1107 Redacted.isRedacted(value) ? Redacted.value(value) : value,
1108 ]),
1109 );
1110
1111 const normalizeDuration = (input: Duration.Input | undefined): string | undefined => {
1112 if (!input) return undefined;
1113 const duration = Duration.fromInputUnsafe(input);
1114 // Docker parses `--health-*` durations with Go's `time.ParseDuration`, which
1115 // requires a unit suffix — a bare nanosecond count is rejected with "missing
1116 // unit in duration". `ns` is the lossless Go-duration rendering of the nanos.
1117 return `${Duration.toNanosUnsafe(duration).toString()}ns`;
1118 };