@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, 06:00 UTC

main
ts 1,668 lines 62.8 KB
Raw
1 import * as Docker from "@alchemy.run/docker";
2 import { healthcheckCommand, isHealthcheckDisabled } from "@alchemy.run/docker/HealthcheckCommand";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import { Action } from "alchemy/Action";
6 import * as Provider from "alchemy/Provider";
7 import { inMemoryState, isResourceState, State, type ResourceState } from "alchemy/State";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Path from "effect/Path";
11 import * as Redacted from "effect/Redacted";
12 import * as Schedule from "effect/Schedule";
13 import { findAvailablePort } from "./Runtime.ts";
14
15 const { test } = Test.make({ providers: Docker.providers(), state: inMemoryState(), adopt: true });
16
17 test.provider(
18 "configures kernel profiles, namespaces, supplementary groups, ulimits and process operations",
19 (stack) =>
20 Effect.gen(function* () {
21 const docker = yield* Docker.Docker;
22 const { stdout: securityOptions } = yield* docker.run([
23 "info",
24 "--format",
25 "{{json .SecurityOptions}}",
26 ]);
27 const appArmorProfile = securityOptions.includes("name=apparmor")
28 ? "docker-default"
29 : undefined;
30 const name = "alchemy-test-container-advanced-runtime";
31 const deploy = (maxFile: string) =>
32 Docker.Container("advanced-runtime", {
33 name,
34 image: "alpine:3.22",
35 seccompProfile: "builtin",
36 appArmorProfile,
37 userNamespace: "host",
38 groupAdd: ["1234"],
39 ulimits: { nofile: { soft: 1024, hard: 2048 } },
40 logDriver: "json-file",
41 logOptions: { "max-file": maxFile, "max-size": "1m" },
42 oomScoreAdjustment: 200,
43 stopSignal: "SIGINT",
44 start: false,
45 });
46
47 const first = yield* stack.deploy(deploy("2"));
48 yield* Effect.addFinalizer(() => docker.container.remove(name, true).pipe(Effect.ignore));
49 const info = yield* docker.container.inspect(name);
50 expect(info.HostConfig.SecurityOpt).toContain("seccomp=builtin");
51 if (appArmorProfile !== undefined) {
52 expect(info.AppArmorProfile).toBe(appArmorProfile);
53 }
54 expect(info.HostConfig.UsernsMode).toBe("host");
55 expect(info.HostConfig.GroupAdd).toContain("1234");
56 expect(info.HostConfig.Ulimits).toEqual(
57 expect.arrayContaining([{ Name: "nofile", Soft: 1024, Hard: 2048 }]),
58 );
59 expect(info.HostConfig.LogConfig).toMatchObject({
60 Type: "json-file",
61 Config: { "max-file": "2", "max-size": "1m" },
62 });
63 expect(info.HostConfig.OomScoreAdj).toBe(200);
64 expect(info.Config.StopSignal).toBe("SIGINT");
65
66 expect((yield* stack.plan(deploy("2"))).resources["advanced-runtime"]?.action).toBe("noop");
67 expect((yield* stack.deploy(deploy("2"))).id).toBe(first.id);
68 expect((yield* stack.plan(deploy("3"))).resources["advanced-runtime"]?.action).toBe(
69 "replace",
70 );
71 const second = yield* stack.deploy(deploy("3"));
72 expect(second.id).not.toBe(first.id);
73 expect(
74 (yield* docker.container.inspect(name)).HostConfig.LogConfig?.Config?.["max-file"],
75 ).toBe("3");
76 yield* stack.destroy();
77 }),
78 { tags: ["provider:docker", "provider:docker:container", "local"] },
79 );
80
81 test.provider(
82 "replaces a container when a custom seccomp profile file changes",
83 (stack) =>
84 Effect.gen(function* () {
85 const fs = yield* FileSystem.FileSystem;
86 const path = yield* Path.Path;
87 const docker = yield* Docker.Docker;
88 const dir = yield* fs.makeTempDirectoryScoped({
89 prefix: "alchemy-docker-seccomp-profile-",
90 });
91 const profile = path.join(dir, "seccomp.json");
92 const writeProfile = (blockedSyscall: string) =>
93 fs.writeFileString(
94 profile,
95 JSON.stringify({
96 defaultAction: "SCMP_ACT_ALLOW",
97 syscalls: [{ names: [blockedSyscall], action: "SCMP_ACT_ERRNO" }],
98 }),
99 );
100 yield* writeProfile("getppid");
101 const name = "alchemy-test-container-file-seccomp";
102 const deploy = () =>
103 Docker.Container("file-seccomp", {
104 name,
105 image: "alpine:3.22",
106 seccompProfile: profile,
107 start: false,
108 });
109 const first = yield* stack.deploy(deploy());
110 yield* Effect.addFinalizer(() => docker.container.remove(name, true).pipe(Effect.ignore));
111 expect((yield* stack.plan(deploy())).resources["file-seccomp"]?.action).toBe("noop");
112 expect((yield* stack.deploy(deploy())).id).toBe(first.id);
113 yield* writeProfile("getuid");
114 expect((yield* stack.plan(deploy())).resources["file-seccomp"]?.action).toBe("update");
115 const second = yield* stack.deploy(deploy());
116 expect(second.id).not.toBe(first.id);
117 yield* stack.destroy();
118 }),
119 { tags: ["provider:docker", "provider:docker:container", "local"] },
120 );
121
122 test.provider(
123 "enforces container resource limits and security options across replacements",
124 (stack) =>
125 Effect.gen(function* () {
126 const docker = yield* Docker.Docker;
127 const name = "alchemy-test-container-runtime-hardening";
128 const deploy = (pidsLimit: number) =>
129 Docker.Container("runtime-hardening", {
130 name,
131 image: "alpine:3.22",
132 memory: "256m",
133 memorySwap: "256m",
134 memoryReservation: "128m",
135 cpus: 0.5,
136 pidsLimit,
137 readOnlyRootFilesystem: true,
138 capDrop: ["ALL"],
139 noNewPrivileges: true,
140 init: true,
141 user: "1234:1234",
142 tmpfs: [{ path: "/tmp", size: "32m", mode: 0o1777 }],
143 start: false,
144 });
145
146 const first = yield* stack.deploy(deploy(128));
147 yield* Effect.addFinalizer(() => docker.container.remove(name, true).pipe(Effect.ignore));
148 const inspect = yield* docker.container.inspect(name);
149 expect(inspect.HostConfig.Memory).toBe(268435456);
150 expect(inspect.HostConfig.MemorySwap).toBe(268435456);
151 expect(inspect.HostConfig.MemoryReservation).toBe(134217728);
152 expect(inspect.HostConfig.NanoCpus).toBe(500000000);
153 expect(inspect.HostConfig.PidsLimit).toBe(128);
154 expect(inspect.HostConfig.ReadonlyRootfs).toBe(true);
155 expect(inspect.HostConfig.CapDrop).toContain("ALL");
156 expect(
157 inspect.HostConfig.SecurityOpt?.some((opt) => opt.startsWith("no-new-privileges")),
158 ).toBe(true);
159 expect(inspect.HostConfig.Init).toBe(true);
160 expect(inspect.Config.User).toBe("1234:1234");
161 expect(inspect.HostConfig.Tmpfs?.["/tmp"]).toContain("size=32m");
162 expect(inspect.HostConfig.Tmpfs?.["/tmp"]).toContain("mode=1777");
163
164 const unchanged = yield* stack.plan(deploy(128));
165 expect(unchanged.resources["runtime-hardening"]?.action).toBe("noop");
166 expect((yield* stack.deploy(deploy(128))).id).toBe(first.id);
167
168 const changed = yield* stack.plan(deploy(256));
169 expect(changed.resources["runtime-hardening"]).toMatchObject({
170 action: "replace",
171 deleteFirst: true,
172 });
173 const second = yield* stack.deploy(deploy(256));
174 expect(second.id).not.toBe(first.id);
175 expect((yield* docker.container.inspect(name)).HostConfig.PidsLimit).toBe(256);
176
177 yield* stack.destroy();
178 }),
179 { tags: ["provider:docker", "provider:docker:container", "local"] },
180 );
181
182 test.provider(
183 "enforces unprivileged read-only execution while keeping tmpfs writable",
184 (stack) =>
185 Effect.gen(function* () {
186 const docker = yield* Docker.Docker;
187 const name = "alchemy-test-container-unprivileged-exec";
188 const container = Docker.Container("unprivileged-exec", {
189 name,
190 image: "alpine:3.22",
191 command: ["sleep", "120"],
192 memory: "64m",
193 memorySwap: "64m",
194 readOnlyRootFilesystem: true,
195 capDrop: ["ALL"],
196 noNewPrivileges: true,
197 init: true,
198 user: "1234:1234",
199 tmpfs: [{ path: "/tmp", mode: 0o1777 }],
200 start: true,
201 });
202 const deployed = yield* stack.deploy(container);
203 yield* Effect.addFinalizer(() => docker.container.remove(name, true).pipe(Effect.ignore));
204 expect(deployed.status).toBe("running");
205
206 const exec = (...command: string[]) => docker.run(["container", "exec", name, ...command]);
207 expect((yield* exec("id", "-u")).stdout).toBe("1234");
208 expect((yield* exec("grep", "NoNewPrivs", "/proc/self/status")).stdout).toMatch(
209 /NoNewPrivs:\s+1/,
210 );
211 expect((yield* exec("touch", "/alchemy-write").pipe(Effect.flip))._tag).toBe("PlatformError");
212 yield* exec("touch", "/tmp/alchemy-write");
213 yield* stack.destroy();
214 }),
215 { tags: ["provider:docker", "provider:docker:container", "local"] },
216 );
217
218 test.provider(
219 "recreates an adopted container before claiming its hardening settings",
220 (stack) =>
221 Effect.gen(function* () {
222 const docker = yield* Docker.Docker;
223 const name = "alchemy-test-container-runtime-hardening-adopt";
224 yield* docker.container.remove(name, true).pipe(Effect.ignore);
225 const { stdout: foreignId } = yield* docker.run([
226 "container",
227 "create",
228 "--name",
229 name,
230 "alpine:3.22",
231 ]);
232 yield* Effect.addFinalizer(() => docker.container.remove(name, true).pipe(Effect.ignore));
233
234 const adopted = yield* stack.deploy(
235 Docker.Container("runtime-hardening-adopt", {
236 name,
237 image: "alpine:3.22",
238 capDrop: ["ALL"],
239 noNewPrivileges: true,
240 start: false,
241 }),
242 );
243 expect(adopted.id).not.toBe(foreignId.trim());
244 const inspected = yield* docker.container.inspect(name);
245 expect(inspected.HostConfig.CapDrop).toContain("ALL");
246 expect(
247 inspected.HostConfig.SecurityOpt?.some((opt) => opt.startsWith("no-new-privileges")),
248 ).toBe(true);
249 yield* stack.destroy();
250 }),
251 { tags: ["provider:docker", "provider:docker:container", "local"] },
252 );
253
254 test.provider(
255 "rejects invalid tmpfs targets before creating a Docker container",
256 (stack) =>
257 Effect.gen(function* () {
258 const docker = yield* Docker.Docker;
259 const name = "alchemy-test-container-invalid-tmpfs";
260 const failure = yield* stack
261 .deploy(
262 Docker.Container("invalid-tmpfs", {
263 name,
264 image: "alpine:3.22",
265 tmpfs: [{ path: "tmp", size: "32m" }],
266 start: false,
267 }),
268 )
269 .pipe(Effect.flip);
270 expect(String(failure)).toContain("tmpfs target must be an absolute path");
271 const present = yield* docker.container.inspect(name).pipe(
272 Effect.map(() => true),
273 Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)),
274 );
275 expect(present).toBe(false);
276 }),
277 { tags: ["provider:docker", "provider:docker:container", "local"] },
278 );
279
280 test.provider(
281 "rejects invalid or silently ignored container runtime restrictions",
282 (stack) =>
283 Effect.gen(function* () {
284 const invalid = [
285 {
286 id: "swap-without-memory",
287 props: { memorySwap: "128m" },
288 reason: "memorySwap requires memory",
289 },
290 {
291 id: "invalid-cpu-quota",
292 props: { cpus: 0 },
293 reason: "cpus must be a finite, positive number",
294 },
295 {
296 id: "invalid-pids-limit",
297 props: { pidsLimit: 0 },
298 reason: "pidsLimit must be a positive integer",
299 },
300 {
301 id: "empty-memory-limit",
302 props: { memory: "" },
303 reason: "memory cannot be empty",
304 },
305 {
306 id: "empty-user",
307 props: { user: " " },
308 reason: "user cannot be empty",
309 },
310 {
311 id: "empty-capability-drop",
312 props: { capDrop: [" "] },
313 reason: "capDrop cannot contain empty capabilities",
314 },
315 {
316 id: "empty-tmpfs-size",
317 props: { tmpfs: [{ path: "/tmp", size: "" }] },
318 reason: "tmpfs size cannot be empty",
319 },
320 {
321 id: "empty-seccomp-profile",
322 props: { seccompProfile: " " },
323 reason: "seccompProfile cannot be empty",
324 },
325 {
326 id: "empty-apparmor-profile",
327 props: { appArmorProfile: "" },
328 reason: "appArmorProfile cannot be empty",
329 },
330 {
331 id: "invalid-supplementary-group",
332 props: { groupAdd: [" "] },
333 reason: "groupAdd cannot contain empty groups",
334 },
335 {
336 id: "inverted-ulimit",
337 props: { ulimits: { nofile: { soft: 2048, hard: 1024 } } },
338 reason: "ulimits contains an invalid soft/hard limit",
339 },
340 {
341 id: "invalid-log-option",
342 props: { logOptions: { "max-file": "" } },
343 reason: "logOptions contains an invalid option",
344 },
345 {
346 id: "invalid-oom-score",
347 props: { oomScoreAdjustment: 1001 },
348 reason: "oomScoreAdjustment must be an integer",
349 },
350 ];
351 for (const { id, props, reason } of invalid) {
352 const error = yield* stack
353 .deploy(
354 Docker.Container(id, {
355 image: "alpine:3.22",
356 ...props,
357 start: false,
358 }),
359 )
360 .pipe(Effect.flip);
361 expect(String(error)).toContain(reason);
362 }
363 }),
364 { tags: ["provider:docker", "provider:docker:container", "local"] },
365 );
366
367 test.provider(
368 "renders Docker healthcheck arrays as a --health-cmd string",
369 () =>
370 Effect.sync(() => {
371 expect(healthcheckCommand("pg_isready -U postgres")).toBe("pg_isready -U postgres");
372 expect(healthcheckCommand(["CMD-SHELL", "pg_isready -U postgres"])).toBe(
373 "pg_isready -U postgres",
374 );
375 expect(healthcheckCommand(["CMD", "pg_isready", "-U", "postgres"])).toBe(
376 "pg_isready -U postgres",
377 );
378 expect(healthcheckCommand(["CMD", "echo", "a b", "it's"])).toBe("echo 'a b' 'it'\\''s'");
379 expect(healthcheckCommand(["NONE"])).toBeUndefined();
380 // Arrays without a Docker marker keep the old behaviour: joined with
381 // spaces and run in the shell.
382 expect(healthcheckCommand(["curl -f localhost || exit 1"])).toBe(
383 "curl -f localhost || exit 1",
384 );
385 expect(healthcheckCommand(["curl", "-f", "localhost", "||", "exit", "1"])).toBe(
386 "curl -f localhost || exit 1",
387 );
388 expect(isHealthcheckDisabled(["NONE"])).toBe(true);
389 expect(isHealthcheckDisabled(["CMD", "true"])).toBe(false);
390 }),
391 { tags: ["provider:docker", "provider:docker:container", "local"] },
392 );
393
394 test.provider(
395 "diff replaces a container when its image changes",
396 () =>
397 Effect.gen(function* () {
398 const containerProvider = yield* Provider.findProvider(Docker.Container);
399 const containerDiff = yield* containerProvider.diff!({
400 id: "web",
401 fqn: "web",
402 instanceId: "instance",
403 olds: { name: "web", image: "nginx:alpine" },
404 news: { name: "web", image: "nginx:1.27-alpine" },
405 oldBindings: [],
406 newBindings: [],
407 output: {
408 id: "web",
409 name: "web",
410 status: "created",
411 createdAt: 0,
412 imageRef: "nginx:alpine",
413 ports: {},
414 },
415 });
416 expect(containerDiff).toEqual({ action: "replace", deleteFirst: true });
417 }),
418 { tags: ["provider:docker", "provider:docker:container", "local"] },
419 );
420
421 test.provider(
422 "diff replaces a container when its Docker context changes",
423 () =>
424 Effect.gen(function* () {
425 const containerProvider = yield* Provider.findProvider(Docker.Container);
426 const containerDiff = yield* containerProvider.diff!({
427 id: "web",
428 fqn: "web",
429 instanceId: "instance",
430 olds: { name: "web", image: "nginx:alpine", context: "default" },
431 news: { name: "web", image: "nginx:alpine", context: "remote-build" },
432 oldBindings: [],
433 newBindings: [],
434 output: {
435 id: "web",
436 name: "web",
437 status: "created",
438 createdAt: 0,
439 imageRef: "nginx:alpine",
440 ports: {},
441 },
442 });
443 expect(containerDiff).toEqual({ action: "replace", deleteFirst: true });
444 }),
445 { tags: ["provider:docker", "provider:docker:container", "local"] },
446 );
447
448 test.provider(
449 "diff replaces a container when its labels or stop timeout change",
450 () =>
451 Effect.gen(function* () {
452 const containerProvider = yield* Provider.findProvider(Docker.Container);
453 const containerDiff = yield* containerProvider.diff!({
454 id: "web",
455 fqn: "web",
456 instanceId: "instance",
457 olds: {
458 name: "web",
459 image: "nginx:alpine",
460 labels: { "traefik.enable": "true" },
461 stopTimeout: "10 seconds",
462 },
463 news: {
464 name: "web",
465 image: "nginx:alpine",
466 labels: { "traefik.enable": "false" },
467 stopTimeout: "30 seconds",
468 },
469 oldBindings: [],
470 newBindings: [],
471 output: {
472 id: "web",
473 name: "web",
474 status: "created",
475 createdAt: 0,
476 imageRef: "nginx:alpine",
477 ports: {},
478 },
479 });
480 expect(containerDiff).toEqual({ action: "replace", deleteFirst: true });
481 }),
482 { tags: ["provider:docker", "provider:docker:container", "local"] },
483 );
484
485 // The config-hash formula must not change for containers that don't use env
486 // files: a new hash would recreate every existing container on upgrade.
487 // Value recorded from the formula as first released (#1397).
488 test.provider(
489 "keeps the config hash of containers without env files stable",
490 (stack) =>
491 Effect.gen(function* () {
492 const docker = yield* Docker.Docker;
493 yield* stack.destroy();
494 const container = yield* stack.deploy(
495 Docker.Container("golden-container", {
496 name: "alchemy-test-golden-config-hash",
497 image: "nginx:alpine",
498 command: ["nginx", "-g", "daemon off;"],
499 environment: { MODE: "golden" },
500 labels: { "com.alchemy.test": "golden" },
501 start: false,
502 }),
503 );
504 const label = (yield* docker.container.inspect(container.name)).Config.Labels?.[
505 "alchemy::container-config"
506 ];
507 expect(label).toBe("3c4c8eb58f436f13f0eb2cfe0a1edb45f0fab73d888ac381e163f986ce0e4e17");
508 yield* stack.destroy();
509 }),
510 { tags: ["provider:docker", "provider:docker:container", "local"] },
511 );
512
513 describe(
514 "Docker.Container",
515 { tags: ["provider:docker", "provider:docker:container", "local"], concurrent: false },
516 () => {
517 test.provider("publishes and inspects bound host ports", (stack) =>
518 Effect.gen(function* () {
519 const docker = yield* Docker.Docker;
520 const hostPort = yield* findAvailablePort();
521 // No explicit name: rely on the engine-generated physical name.
522 const container = yield* stack.deploy(
523 Docker.Container("nginx-container", {
524 image: "nginx:alpine",
525 ports: [{ external: hostPort, internal: 80 }],
526 start: true,
527 }),
528 );
529 expect(container.name.length).toBeGreaterThan(0);
530 expect(container.status).toBe("running");
531
532 const runtime = yield* docker.container.inspect(container.name);
533 // Docker always publishes the IPv4 (`0.0.0.0`) binding; whether it also
534 // adds an IPv6 (`::`) binding depends on the daemon's IPv6 config, so
535 // assert the guaranteed IPv4 mapping is present rather than requiring
536 // both.
537 expect(runtime?.NetworkSettings.Ports?.["80/tcp"]).toEqual(
538 expect.arrayContaining([{ HostIp: "0.0.0.0", HostPort: `${hostPort}` }]),
539 );
540 }),
541 );
542
543 test.provider("creates a stopped container when start is false", (stack) =>
544 Effect.gen(function* () {
545 const container = yield* stack.deploy(
546 Docker.Container("stopped-container", { image: "nginx:alpine", start: false }),
547 );
548 expect(container.status).toBe("created");
549 expect(container.imageRef).toBe("nginx:alpine");
550 }),
551 );
552
553 test.provider("applies container labels and a stop timeout", (stack) =>
554 Effect.gen(function* () {
555 const docker = yield* Docker.Docker;
556 const container = yield* stack.deploy(
557 Docker.Container("traefik-container", {
558 image: "nginx:alpine",
559 labels: {
560 "traefik.enable": "true",
561 "traefik.http.services.web.loadbalancer.server.port": "80",
562 },
563 stopTimeout: "10 minutes",
564 start: true,
565 }),
566 );
567
568 const info = yield* docker.container.inspect(container.name);
569 expect(info.Config.Labels).toEqual(
570 expect.objectContaining({
571 "traefik.enable": "true",
572 "traefik.http.services.web.loadbalancer.server.port": "80",
573 }),
574 );
575 expect(info.Config.StopTimeout).toBe(600);
576 }),
577 );
578
579 test.provider(
580 "updates network aliases without replacing the container",
581 (stack) =>
582 Effect.gen(function* () {
583 const docker = yield* Docker.Docker;
584 // No explicit names: the engine generates stable physical names that
585 // stay constant across the two deploys (same instance id).
586 const deployWithAlias = (alias: string) =>
587 stack.deploy(
588 Effect.gen(function* () {
589 const network = yield* Docker.Network("alias-network");
590 const container = yield* Docker.Container("alias-container", {
591 image: "nginx:alpine",
592 networks: [{ name: network.name, aliases: [alias] }],
593 });
594 return { container, network };
595 }),
596 );
597
598 const first = yield* deployWithAlias("old-alias");
599 const second = yield* deployWithAlias("new-alias");
600 expect(second.container.id).toBe(first.container.id);
601
602 const info = yield* docker.container.inspect(second.container.name);
603 const aliases = info?.NetworkSettings.Networks?.[second.network.name]?.Aliases ?? [];
604 expect(aliases).toContain("new-alias");
605 expect(aliases).not.toContain("old-alias");
606 }),
607 { tags: ["provider:docker:network"] },
608 );
609
610 test.provider("replaces the container when published ports change", (stack) =>
611 Effect.gen(function* () {
612 const firstPort = yield* findAvailablePort();
613 const secondPort = yield* findAvailablePort();
614 const first = yield* stack.deploy(
615 Docker.Container("ported-container", {
616 image: "nginx:alpine",
617 ports: [{ external: firstPort, internal: 80 }],
618 }),
619 );
620 const second = yield* stack.deploy(
621 Docker.Container("ported-container", {
622 image: "nginx:alpine",
623 ports: [{ external: secondPort, internal: 80 }],
624 }),
625 );
626 expect(second.id).not.toBe(first.id);
627 expect(second.ports["80/tcp"]).toBe(secondPort);
628 }),
629 );
630
631 // Rewrite the container's persisted row into the wedged shape an
632 // interrupted deploy leaves behind: `creating`, no attributes, and the
633 // Output-valued `image` prop lost in the round-trip (#736).
634 const wedgeContainerRow = (stack: { readonly name: string; readonly stage: string }) =>
635 Effect.gen(function* () {
636 const state = yield* yield* State;
637 const stage = stack.stage;
638 const fqns = yield* state.list({ stack: stack.name, stage });
639 const rows = yield* Effect.forEach(fqns, (fqn) =>
640 state.get({ stack: stack.name, stage, fqn }).pipe(Effect.map((row) => ({ fqn, row }))),
641 );
642 const wedged = rows.find(
643 (r): r is { fqn: string; row: ResourceState } =>
644 isResourceState(r.row) && r.row.resourceType === "Docker.Container",
645 );
646 if (!wedged) {
647 return yield* Effect.die(new Error("no Docker.Container state row found after deploy"));
648 }
649 yield* state.set({
650 stack: stack.name,
651 stage,
652 fqn: wedged.fqn,
653 value: {
654 ...wedged.row,
655 status: "creating",
656 attr: undefined,
657 props: { ...wedged.row.props, image: undefined },
658 },
659 });
660 });
661
662 test.provider(
663 "read recovers a creating-state container whose image prop was lost (#736)",
664 (stack) =>
665 Effect.gen(function* () {
666 yield* stack.destroy();
667 const docker = yield* Docker.Docker;
668
669 const deployContainer = () =>
670 stack.deploy(
671 // No explicit name: the engine-generated physical name is stable
672 // across both deploys, so `read` can find the live container.
673 Docker.Container("read-recovery-container", { image: "nginx:alpine", start: false }),
674 );
675
676 const created = yield* deployContainer();
677 // Safety net: remove the container if the test dies mid-way.
678 yield* Effect.addFinalizer(() =>
679 docker.container.remove(created.name, true).pipe(Effect.ignore),
680 );
681
682 yield* wedgeContainerRow(stack);
683
684 // Before the fix this crashed in `read` with
685 // `TypeError: undefined is not an object (evaluating 'image.imageRef')`.
686 const recovered = yield* deployContainer();
687 // Same container id — read/reconcile converged on the existing
688 // container instead of creating a duplicate.
689 expect(recovered.id).toBe(created.id);
690 expect(recovered.imageRef).toBe("nginx:alpine");
691
692 yield* stack.destroy();
693 }),
694 { timeout: 240_000 },
695 );
696
697 test.provider(
698 "diff recreates a creating-state container that vanished after its image prop was lost (#736)",
699 (stack) =>
700 Effect.gen(function* () {
701 yield* stack.destroy();
702 const docker = yield* Docker.Docker;
703
704 const deployContainer = () =>
705 stack.deploy(
706 Docker.Container("diff-recovery-container", { image: "nginx:alpine", start: false }),
707 );
708
709 const created = yield* deployContainer();
710 // Safety net: remove the container if the test dies mid-way.
711 yield* Effect.addFinalizer(() =>
712 docker.container.remove(created.name, true).pipe(Effect.ignore),
713 );
714
715 yield* wedgeContainerRow(stack);
716 // Remove the container out-of-band so recovery `read` misses and the
717 // engine falls through to `diff` with the junk creating-row props.
718 yield* docker.container.remove(created.name, true);
719
720 // Before the fix this crashed in `diff` with
721 // `TypeError: undefined is not an object (evaluating 'image.imageRef')`.
722 const recovered = yield* deployContainer();
723 expect(recovered.id).not.toBe(created.id);
724 expect(recovered.imageRef).toBe("nginx:alpine");
725 expect(recovered.status).toBe("created");
726
727 yield* stack.destroy();
728 }),
729 { timeout: 240_000 },
730 );
731
732 test.provider("passes environment values into the container (#1117)", (stack) =>
733 Effect.gen(function* () {
734 const docker = yield* Docker.Docker;
735 // Environment values ride the Docker CLI's process environment (the
736 // create args carry name-only `--env KEY` flags to keep secrets off
737 // the command line) — before the fix every entry resolved empty.
738 const container = yield* stack.deploy(
739 Docker.Container("env-container", {
740 image: "nginx:alpine",
741 environment: {
742 PLAIN_VALUE: "plain-value",
743 SECRET_VALUE: Redacted.make("secret-value"),
744 },
745 start: false,
746 }),
747 );
748
749 const info = yield* docker.container.inspect(container.name);
750 expect(info.Config.Env).toEqual(
751 expect.arrayContaining(["PLAIN_VALUE=plain-value", "SECRET_VALUE=secret-value"]),
752 );
753 }),
754 );
755
756 const writeEnvFiles = Effect.gen(function* () {
757 const fs = yield* FileSystem.FileSystem;
758 const path = yield* Path.Path;
759 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-docker-env-files-" });
760 const base = path.join(dir, "base.env");
761 const override = path.join(dir, "override.env");
762 yield* fs.writeFileString(base, "FROM_BASE=base\nLAYERED=base\nEXPLICIT=base\n");
763 yield* fs.writeFileString(override, "LAYERED=override\nEXPLICIT=override\n");
764 return { base, override };
765 });
766
767 // Docker keeps every duplicate in `Config.Env`; what matters is the value
768 // the process sees, so the container prints its environment and exits.
769 const printEnv = ["sh", "-c", 'echo "$FROM_BASE $LAYERED $EXPLICIT"'];
770 const readPrintedEnv = (name: string) =>
771 Effect.gen(function* () {
772 const docker = yield* Docker.Docker;
773 return yield* docker.run(["logs", name]).pipe(
774 Effect.map((result) => result.stdout.trim()),
775 Effect.repeat({
776 schedule: Schedule.spaced("250 millis"),
777 until: (output) => output.length > 0,
778 times: 40,
779 }),
780 );
781 });
782
783 test.provider("loads env files in order with explicit environment winning", (stack) =>
784 Effect.gen(function* () {
785 const { base, override } = yield* writeEnvFiles;
786 const container = yield* stack.deploy(
787 Docker.Container("env-file-container", {
788 image: "nginx:alpine",
789 command: printEnv,
790 envFiles: [base, override],
791 environment: { EXPLICIT: "explicit" },
792 start: true,
793 }),
794 );
795
796 expect(yield* readPrintedEnv(container.name)).toBe("base override explicit");
797 }),
798 );
799
800 test.provider("replaces the container when env file order changes", (stack) =>
801 Effect.gen(function* () {
802 const { base, override } = yield* writeEnvFiles;
803 const deploy = (envFiles: string[]) =>
804 stack.deploy(
805 Docker.Container("env-file-order-container", {
806 image: "nginx:alpine",
807 command: printEnv,
808 envFiles,
809 start: true,
810 }),
811 );
812
813 const first = yield* deploy([base, override]);
814 expect(yield* readPrintedEnv(first.name)).toBe("base override override");
815 const second = yield* deploy([override, base]);
816
817 expect(second.id).not.toBe(first.id);
818 expect(yield* readPrintedEnv(second.name)).toBe("base base base");
819 }),
820 );
821
822 test.provider("replaces the container when an env file's contents change", (stack) =>
823 Effect.gen(function* () {
824 const docker = yield* Docker.Docker;
825 const fs = yield* FileSystem.FileSystem;
826 const { base } = yield* writeEnvFiles;
827 const deploy = () =>
828 stack.deploy(
829 Docker.Container("env-file-content-container", {
830 image: "nginx:alpine",
831 command: printEnv,
832 envFiles: [base],
833 start: true,
834 }),
835 );
836
837 const first = yield* deploy();
838 expect(yield* readPrintedEnv(first.name)).toBe("base base base");
839 // Unchanged contents: the digest is stable, so nothing rolls.
840 expect((yield* deploy()).id).toBe(first.id);
841
842 // Same path, new contents: the next deploy replaces the container.
843 yield* fs.writeFileString(base, "FROM_BASE=base\nLAYERED=edited-secret-value\n");
844 const edited = Docker.Container("env-file-content-container", {
845 image: "nginx:alpine",
846 command: printEnv,
847 envFiles: [base],
848 start: true,
849 });
850 const plan = yield* stack.plan(edited);
851 expect(plan.resources["env-file-content-container"]?.action).toBe("update");
852 const second = yield* stack.deploy(edited);
853 expect(second.id).not.toBe(first.id);
854 expect(yield* readPrintedEnv(second.name)).toBe("base edited-secret-value");
855
856 // Only the container's own label carries the digest; Alchemy state
857 // holds neither the values nor the digest.
858 const label = (yield* docker.container.inspect(second.name)).Config.Labels?.[
859 "alchemy::container-config"
860 ];
861 expect(label).toBeDefined();
862 const state = yield* yield* State;
863 const fqns = yield* state.list({ stack: stack.name, stage: stack.stage });
864 const rows = yield* Effect.forEach(fqns, (fqn) =>
865 state.get({ stack: stack.name, stage: stack.stage, fqn }),
866 );
867 const persisted = yield* Effect.sync(() => JSON.stringify(rows));
868 expect(persisted).not.toContain("edited-secret-value");
869 expect(persisted).not.toContain(label!);
870 }),
871 );
872
873 test.provider(
874 "replaces the container when a later env file changes, given as a relative path",
875 (stack) =>
876 Effect.gen(function* () {
877 const fs = yield* FileSystem.FileSystem;
878 const path = yield* Path.Path;
879 const { base, override } = yield* writeEnvFiles;
880 // Docker resolves relative paths against the CLI's working
881 // directory; the digest must read the same file.
882 const relativeOverride = path.relative(process.cwd(), override);
883 expect(path.isAbsolute(relativeOverride)).toBe(false);
884 const container = Docker.Container("env-file-relative-container", {
885 image: "nginx:alpine",
886 command: printEnv,
887 envFiles: [base, relativeOverride],
888 start: true,
889 });
890
891 const first = yield* stack.deploy(container);
892 expect(yield* readPrintedEnv(first.name)).toBe("base override override");
893
894 yield* fs.writeFileString(override, "LAYERED=second-edit\nEXPLICIT=override\n");
895 const plan = yield* stack.plan(container);
896 expect(plan.resources["env-file-relative-container"]?.action).toBe("update");
897 const second = yield* stack.deploy(container);
898 expect(second.id).not.toBe(first.id);
899 expect(yield* readPrintedEnv(second.name)).toBe("base second-edit override");
900 }),
901 );
902
903 test.provider("fails the plan with the path when an env file is missing", (stack) =>
904 Effect.gen(function* () {
905 const fs = yield* FileSystem.FileSystem;
906 const { base } = yield* writeEnvFiles;
907 const container = Docker.Container("env-file-missing-container", {
908 image: "nginx:alpine",
909 envFiles: [base],
910 start: false,
911 });
912 yield* stack.deploy(container);
913
914 yield* fs.remove(base);
915 const error = yield* stack.plan(container).pipe(Effect.flip);
916 const report = yield* Effect.sync(() => String(error) + JSON.stringify(error));
917 expect(report).toContain(base);
918 expect(report).toContain("NotFound");
919 }),
920 );
921
922 // Prints a marker even when the variable is unset, so the log is never empty.
923 const printLayered = ["sh", "-c", 'echo "[$LAYERED]"'];
924
925 test.provider("fails the plan with the path when an env file is unreadable", (stack) =>
926 Effect.gen(function* () {
927 const fs = yield* FileSystem.FileSystem;
928 const { base } = yield* writeEnvFiles;
929 const container = Docker.Container("env-file-unreadable-container", {
930 image: "nginx:alpine",
931 envFiles: [base],
932 start: false,
933 });
934 yield* stack.deploy(container);
935
936 yield* Effect.acquireRelease(fs.chmod(base, 0o000), () =>
937 fs.chmod(base, 0o644).pipe(Effect.ignore),
938 );
939 const error = yield* stack.plan(container).pipe(Effect.flip);
940 const report = yield* Effect.sync(() => String(error) + JSON.stringify(error));
941 expect(report).toContain(base);
942 expect(report).toContain("PermissionDenied");
943 }),
944 );
945
946 test.provider("replaces the container when env files are added and removed", (stack) =>
947 Effect.gen(function* () {
948 const { base } = yield* writeEnvFiles;
949 const deploy = (envFiles: string[] | undefined) =>
950 stack.deploy(
951 Docker.Container("env-file-toggle-container", {
952 image: "nginx:alpine",
953 command: printLayered,
954 envFiles,
955 start: true,
956 }),
957 );
958
959 const without = yield* deploy(undefined);
960 expect(yield* readPrintedEnv(without.name)).toBe("[]");
961 const added = yield* deploy([base]);
962 expect(added.id).not.toBe(without.id);
963 expect(yield* readPrintedEnv(added.name)).toBe("[base]");
964 const removed = yield* deploy(undefined);
965 expect(removed.id).not.toBe(added.id);
966 expect(yield* readPrintedEnv(removed.name)).toBe("[]");
967 }),
968 );
969
970 test.provider("keys on env file contents, not timestamps or formatting intent", (stack) =>
971 Effect.gen(function* () {
972 const fs = yield* FileSystem.FileSystem;
973 const { base } = yield* writeEnvFiles;
974 const container = Docker.Container("env-file-bytes-container", {
975 image: "nginx:alpine",
976 command: printLayered,
977 envFiles: [base],
978 start: true,
979 });
980 const first = yield* stack.deploy(container);
981
982 // Rewriting identical bytes (new mtime) is not a change.
983 const original = yield* fs.readFileString(base);
984 yield* Effect.sleep("1100 millis");
985 yield* fs.writeFileString(base, original);
986 const touched = yield* stack.plan(container);
987 expect(touched.resources["env-file-bytes-container"]?.action).toBe("noop");
988 expect((yield* stack.deploy(container)).id).toBe(first.id);
989
990 // The digest covers raw bytes, so even a comment-only edit rolls the
991 // container: Alchemy does not interpret Docker's env-file syntax.
992 yield* fs.writeFileString(base, `${original}# reviewed\n`);
993 const commented = yield* stack.plan(container);
994 expect(commented.resources["env-file-bytes-container"]?.action).toBe("update");
995 }),
996 );
997
998 test.provider("tracks env files on an adopted container", (stack) =>
999 Effect.gen(function* () {
1000 const docker = yield* Docker.Docker;
1001 const fs = yield* FileSystem.FileSystem;
1002 const { base } = yield* writeEnvFiles;
1003 const name = "alchemy-test-adopted-env-file-container";
1004 yield* docker.container.remove(name, true).pipe(Effect.ignore);
1005 yield* Effect.addFinalizer(() => docker.container.remove(name, true).pipe(Effect.ignore));
1006 // Created outside Alchemy: no config-hash label to compare against.
1007 const { stdout: foreignId } = yield* docker.run([
1008 "container",
1009 "create",
1010 "--name",
1011 name,
1012 "--env-file",
1013 base,
1014 "nginx:alpine",
1015 ...printLayered,
1016 ]);
1017 const container = Docker.Container("env-file-adopted-container", {
1018 name,
1019 image: "nginx:alpine",
1020 command: printLayered,
1021 envFiles: [base],
1022 start: true,
1023 });
1024
1025 // Adoption recreates it once so the label exists from then on.
1026 const adopted = yield* stack.deploy(container);
1027 expect(adopted.id).not.toBe(foreignId.trim());
1028 const label = (yield* docker.container.inspect(name)).Config.Labels?.[
1029 "alchemy::container-config"
1030 ];
1031 expect(label).toBeDefined();
1032
1033 yield* fs.writeFileString(base, "LAYERED=after-adoption\n");
1034 const plan = yield* stack.plan(container);
1035 expect(plan.resources["env-file-adopted-container"]?.action).toBe("update");
1036 const updated = yield* stack.deploy(container);
1037 expect(yield* readPrintedEnv(updated.name)).toBe("[after-adoption]");
1038 }),
1039 );
1040
1041 test.provider("detects env file edits for a container in a named Docker context", (stack) =>
1042 Effect.gen(function* () {
1043 const docker = yield* Docker.Docker;
1044 const fs = yield* FileSystem.FileSystem;
1045 const { base } = yield* writeEnvFiles;
1046 const context = "alchemy-test-env-file-context";
1047 const { stdout: host } = yield* docker.run([
1048 "context",
1049 "inspect",
1050 "--format",
1051 "{{.Endpoints.docker.Host}}",
1052 ]);
1053 yield* docker.context.remove(context, true).pipe(Effect.ignore);
1054 yield* docker.context.create({ name: context, docker: `host=${host.trim()}` });
1055 yield* Effect.addFinalizer(() => docker.context.remove(context, true).pipe(Effect.ignore));
1056
1057 const container = Docker.Container("env-file-context-container", {
1058 image: "nginx:alpine",
1059 command: printLayered,
1060 envFiles: [base],
1061 context,
1062 start: true,
1063 });
1064 const first = yield* stack.deploy(container);
1065 yield* fs.writeFileString(base, "LAYERED=in-context\n");
1066 const plan = yield* stack.plan(container);
1067 expect(plan.resources["env-file-context-container"]?.action).toBe("update");
1068 const second = yield* stack.deploy(container);
1069 expect(second.id).not.toBe(first.id);
1070 yield* stack.destroy();
1071 }),
1072 );
1073
1074 test.provider(
1075 "does not replace the container when env files go from empty to omitted",
1076 (stack) =>
1077 Effect.gen(function* () {
1078 const first = yield* stack.deploy(
1079 Docker.Container("env-file-empty-container", {
1080 image: "nginx:alpine",
1081 envFiles: [],
1082 start: false,
1083 }),
1084 );
1085 const omitted = Docker.Container("env-file-empty-container", {
1086 image: "nginx:alpine",
1087 start: false,
1088 });
1089 const plan = yield* stack.plan(omitted);
1090 expect(plan.resources["env-file-empty-container"]?.action).not.toBe("replace");
1091 const second = yield* stack.deploy(omitted);
1092 expect(second.id).toBe(first.id);
1093 }),
1094 );
1095 // Runtime options are checked inside the running container, not on the
1096 // `docker container create` arguments.
1097 const sleeper = { image: "alpine:3.19", command: ["sleep", "300"], start: true };
1098 const exec = (name: string, ...command: string[]) =>
1099 Effect.gen(function* () {
1100 const docker = yield* Docker.Docker;
1101 return (yield* docker.run(["exec", name, ...command])).stdout.trim();
1102 });
1103
1104 test.provider("shares a donor container's network namespace", (stack) =>
1105 Effect.gen(function* () {
1106 const docker = yield* Docker.Docker;
1107 const { donor, sidecar } = yield* stack.deploy(
1108 Effect.gen(function* () {
1109 const donor = yield* Docker.Container("namespace-donor", {
1110 image: "nginx:alpine",
1111 start: true,
1112 });
1113 const sidecar = yield* Docker.Container("namespace-sidecar", {
1114 ...sleeper,
1115 networkMode: { container: donor.id },
1116 });
1117 return { donor, sidecar };
1118 }),
1119 );
1120
1121 const info = yield* docker.container.inspect(sidecar.name);
1122 expect(info.HostConfig.NetworkMode).toBe(`container:${donor.id}`);
1123 // The sidecar reaches the donor's nginx on its own loopback.
1124 const page = yield* exec(sidecar.name, "wget", "-qO-", "http://127.0.0.1").pipe(
1125 Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 20 }),
1126 );
1127 expect(page).toContain("nginx");
1128 }),
1129 );
1130
1131 test.provider("adds capabilities and exposes host devices", (stack) =>
1132 Effect.gen(function* () {
1133 const deploy = (capAdd: string[]) =>
1134 stack.deploy(
1135 Docker.Container("runtime-options-container", {
1136 ...sleeper,
1137 capAdd,
1138 devices: [{ hostPath: "/dev/zero", containerPath: "/dev/alchemy-zero" }],
1139 }),
1140 );
1141
1142 // `ip link add` needs NET_ADMIN, which Docker does not grant by default.
1143 const first = yield* deploy(["NET_ADMIN"]);
1144 yield* exec(first.name, "ip", "link", "add", "alchemy0", "type", "dummy");
1145 expect(yield* exec(first.name, "sh", "-c", "head -c 4 /dev/alchemy-zero | wc -c")).toBe(
1146 "4",
1147 );
1148
1149 // Duplicates and order normalize away: same container.
1150 const same = yield* deploy([" NET_ADMIN", "NET_ADMIN"]);
1151 expect(same.id).toBe(first.id);
1152
1153 // A different capability set replaces the container.
1154 const replaced = yield* deploy(["SYS_TIME"]);
1155 expect(replaced.id).not.toBe(first.id);
1156 const denied = yield* exec(
1157 replaced.name,
1158 "ip",
1159 "link",
1160 "add",
1161 "alchemy0",
1162 "type",
1163 "dummy",
1164 ).pipe(Effect.flip);
1165 expect(denied._tag).toBe("PlatformError");
1166 }),
1167 );
1168
1169 const invalidOptions: Array<[string, Partial<Docker.ContainerProps>]> = [
1170 [
1171 "ports",
1172 {
1173 networkMode: { container: "alchemy-missing-donor" },
1174 ports: [{ external: 0, internal: 80 }],
1175 },
1176 ],
1177 [
1178 "networks",
1179 { networkMode: "container:alchemy-missing-donor", networks: [{ name: "bridge" }] },
1180 ],
1181 [
1182 "conflicting device targets",
1183 {
1184 devices: [
1185 { hostPath: "/dev/zero", containerPath: "/dev/alchemy" },
1186 { hostPath: "/dev/null", containerPath: "/dev/alchemy" },
1187 ],
1188 },
1189 ],
1190 ];
1191 for (const [name, props] of invalidOptions) {
1192 test.provider(`rejects ${name} that cannot be combined before calling Docker`, (stack) =>
1193 Effect.gen(function* () {
1194 const docker = yield* Docker.Docker;
1195 const error = yield* stack
1196 .deploy(Docker.Container("invalid-runtime-options", { ...sleeper, ...props }))
1197 .pipe(Effect.flip);
1198 const report = yield* Effect.sync(() => String(error) + JSON.stringify(error));
1199 expect(report).toContain("InvalidContainerOptions");
1200 const listed = yield* docker.run([
1201 "ps",
1202 "--all",
1203 "--filter",
1204 "name=invalid-runtime-options",
1205 "--format",
1206 "{{.Names}}",
1207 ]);
1208 expect(listed.stdout.trim()).toBe("");
1209 }),
1210 );
1211 }
1212
1213 test.provider("applies a healthcheck with unit-suffixed durations", (stack) =>
1214 Effect.gen(function* () {
1215 const docker = yield* Docker.Docker;
1216 // `normalizeDuration` used to emit a bare nanosecond count (e.g.
1217 // `1000000000`), which `docker container create` rejects with "missing
1218 // unit in duration" — so this deploy would fail outright before the fix.
1219 const container = yield* stack.deploy(
1220 Docker.Container("healthcheck-container", {
1221 image: "nginx:alpine",
1222 healthcheck: {
1223 cmd: "true",
1224 interval: "1 second",
1225 timeout: "2 seconds",
1226 retries: 3,
1227 startPeriod: "1 second",
1228 },
1229 start: true,
1230 }),
1231 );
1232 expect(container.status).toBe("running");
1233
1234 // Docker reports the configured durations back in nanoseconds — assert
1235 // they round-tripped rather than being dropped or truncated.
1236 const info = yield* docker.container.inspect(container.name);
1237 const health = info?.Config.Healthcheck;
1238 expect(health?.Interval).toBe(1_000_000_000);
1239 expect(health?.Timeout).toBe(2_000_000_000);
1240 expect(health?.Retries).toBe(3);
1241 expect(health?.StartPeriod).toBe(1_000_000_000);
1242 }),
1243 );
1244 // The array form used to be joined with spaces, so `["CMD-SHELL", "true"]`
1245 // ran a command literally named `CMD-SHELL` and the container never
1246 // became healthy.
1247 test.provider("runs a CMD-SHELL array healthcheck as the shell command", (stack) =>
1248 Effect.gen(function* () {
1249 const docker = yield* Docker.Docker;
1250 const container = yield* stack.deploy(
1251 Docker.Container("healthcheck-cmd-shell", {
1252 image: "nginx:alpine",
1253 healthcheck: { cmd: ["CMD-SHELL", "true"], interval: "1 second", retries: 1 },
1254 start: true,
1255 }),
1256 );
1257 const info = yield* docker.container.inspect(container.name);
1258 expect(info?.Config.Healthcheck?.Test).toEqual(["CMD-SHELL", "true"]);
1259 }),
1260 );
1261
1262 test.provider("runs a CMD array healthcheck with its arguments quoted", (stack) =>
1263 Effect.gen(function* () {
1264 const docker = yield* Docker.Docker;
1265 const container = yield* stack.deploy(
1266 Docker.Container("healthcheck-cmd-exec", {
1267 image: "nginx:alpine",
1268 healthcheck: { cmd: ["CMD", "echo", "a b"], interval: "1 second", retries: 1 },
1269 start: true,
1270 }),
1271 );
1272 const info = yield* docker.container.inspect(container.name);
1273 expect(info?.Config.Healthcheck?.Test).toEqual(["CMD-SHELL", "echo 'a b'"]);
1274 }),
1275 );
1276
1277 test.provider("keeps a plain string healthcheck unchanged", (stack) =>
1278 Effect.gen(function* () {
1279 const docker = yield* Docker.Docker;
1280 const container = yield* stack.deploy(
1281 Docker.Container("healthcheck-cmd-string", {
1282 image: "nginx:alpine",
1283 healthcheck: { cmd: "true", interval: "1 second", retries: 1 },
1284 start: true,
1285 }),
1286 );
1287 const info = yield* docker.container.inspect(container.name);
1288 expect(info?.Config.Healthcheck?.Test).toEqual(["CMD-SHELL", "true"]);
1289 }),
1290 );
1291
1292 test.provider("runs an array without a marker as a shell line, as before", (stack) =>
1293 Effect.gen(function* () {
1294 const docker = yield* Docker.Docker;
1295 const container = yield* stack.deploy(
1296 Docker.Container("healthcheck-cmd-legacy", {
1297 image: "nginx:alpine",
1298 healthcheck: { cmd: ["true || exit 1"], interval: "1 second", retries: 1 },
1299 start: true,
1300 }),
1301 );
1302 const info = yield* docker.container.inspect(container.name);
1303 expect(info?.Config.Healthcheck?.Test).toEqual(["CMD-SHELL", "true || exit 1"]);
1304 }),
1305 );
1306
1307 test.provider("disables the image healthcheck with NONE", (stack) =>
1308 Effect.gen(function* () {
1309 const docker = yield* Docker.Docker;
1310 const container = yield* stack.deploy(
1311 Docker.Container("healthcheck-none", {
1312 image: "nginx:alpine",
1313 healthcheck: { cmd: ["NONE"] },
1314 start: true,
1315 }),
1316 );
1317 const info = yield* docker.container.inspect(container.name);
1318 expect(info?.Config.Healthcheck?.Test).toEqual(["NONE"]);
1319 }),
1320 );
1321
1322 // Stored form is not enough: the check must actually run in the container.
1323 const healthStatus = (name: string, until: "healthy" | "unhealthy") =>
1324 Effect.gen(function* () {
1325 const docker = yield* Docker.Docker;
1326 return yield* docker.container.inspect(name).pipe(
1327 Effect.map((info) => info.State.Health?.Status),
1328 Effect.repeat({
1329 schedule: Schedule.spaced("500 millis"),
1330 until: (status) => status === until,
1331 times: 40,
1332 }),
1333 );
1334 });
1335
1336 for (const [label, cmd, expected] of [
1337 ["a CMD-SHELL array", ["CMD-SHELL", "test -d /etc"], "healthy"],
1338 ["a CMD array", ["CMD", "test", "-d", "/etc"], "healthy"],
1339 ["a failing CMD array", ["CMD", "false"], "unhealthy"],
1340 ] as const) {
1341 test.provider(`reports ${expected} for ${label} healthcheck`, (stack) =>
1342 Effect.gen(function* () {
1343 const container = yield* stack.deploy(
1344 Docker.Container(`healthcheck-run-${expected}-${cmd[0].toLowerCase()}`, {
1345 image: "nginx:alpine",
1346 healthcheck: { cmd: [...cmd], interval: "1 second", retries: 1 },
1347 start: true,
1348 }),
1349 );
1350 expect(yield* healthStatus(container.name, expected)).toBe(expected);
1351 }),
1352 );
1353 }
1354
1355 test.provider("reports the host port Docker assigned to a random publish (#1388)", (stack) =>
1356 Effect.gen(function* () {
1357 const docker = yield* Docker.Docker;
1358 const container = yield* stack.deploy(
1359 Docker.Container("random-port-container", {
1360 image: "nginx:alpine",
1361 // `external: 0` = "any free host port".
1362 ports: [{ external: 0, internal: 80 }],
1363 start: true,
1364 }),
1365 );
1366
1367 // Before the fix this was 0: the create arg asked for host port 0
1368 // literally, and the requested binding was then reported over the
1369 // assigned one.
1370 const assigned = container.ports["80/tcp"];
1371 expect(assigned).toBeGreaterThan(0);
1372
1373 // …and it is the port the container is actually published on.
1374 const runtime = yield* docker.container.inspect(container.name);
1375 expect(runtime?.NetworkSettings.Ports?.["80/tcp"]).toEqual(
1376 expect.arrayContaining([expect.objectContaining({ HostPort: `${assigned}` })]),
1377 );
1378 }),
1379 );
1380
1381 test.provider("forwards extra hosts to the container (#1387)", (stack) =>
1382 Effect.gen(function* () {
1383 const docker = yield* Docker.Docker;
1384 const container = yield* stack.deploy(
1385 Docker.Container("extra-hosts-container", {
1386 image: "nginx:alpine",
1387 extraHosts: ["host.docker.internal:host-gateway", "db.internal:10.1.2.3"],
1388 start: true,
1389 }),
1390 );
1391
1392 const runtime = yield* docker.container.inspect(container.name);
1393 expect(runtime?.HostConfig.ExtraHosts).toEqual(
1394 expect.arrayContaining(["host.docker.internal:host-gateway", "db.internal:10.1.2.3"]),
1395 );
1396 }),
1397 );
1398
1399 test.provider(
1400 "disconnects only the networks alchemy connected (#1386)",
1401 (stack) =>
1402 Effect.gen(function* () {
1403 const docker = yield* Docker.Docker;
1404 const foreign = "alchemy-test-foreign-network";
1405
1406 const deploy = (attach: boolean) =>
1407 stack.deploy(
1408 Effect.gen(function* () {
1409 const network = yield* Docker.Network("managed-network");
1410 const container = yield* Docker.Container("managed-container", {
1411 image: "nginx:alpine",
1412 networks: attach ? [{ name: network.name }] : [],
1413 });
1414 return { container, network };
1415 }),
1416 );
1417
1418 const first = yield* deploy(true);
1419
1420 // A network alchemy never connected the container to — the case a
1421 // user, compose file, or another tool creates.
1422 yield* docker.network.create({ name: foreign, driver: "bridge" }).pipe(Effect.ignore);
1423 yield* Effect.addFinalizer(() => docker.network.remove(foreign).pipe(Effect.ignore));
1424 yield* docker.network.connect({ network: foreign, container: first.container.name });
1425
1426 // Drop the managed network from the desired state.
1427 const second = yield* deploy(false);
1428 expect(second.container.id).toBe(first.container.id);
1429
1430 const info = yield* docker.container.inspect(second.container.name);
1431 const attached = Object.keys(info?.NetworkSettings.Networks ?? {});
1432 // Ours goes…
1433 expect(attached).not.toContain(first.network.name);
1434 // …the foreign one and Docker's own default stay. Before the fix the
1435 // reconciler swept every live network and tore off both.
1436 expect(attached).toContain(foreign);
1437 expect(attached).toContain("bridge");
1438 }),
1439 { tags: ["provider:docker:network"], timeout: 240_000 },
1440 );
1441
1442 test.provider(
1443 "recreates a container when an Action-backed environment value changes",
1444 (stack) =>
1445 Effect.gen(function* () {
1446 const docker = yield* Docker.Docker;
1447 const Environment = Action("ContainerEnvironment", (input: { value: string }) =>
1448 Effect.succeed(input.value),
1449 );
1450 const deployWithEnvironment = (value: string) =>
1451 stack.deploy(
1452 Effect.gen(function* () {
1453 const environment = yield* Environment({ value });
1454 return yield* Docker.Container("action-env-container", {
1455 image: "nginx:alpine",
1456 environment: { VALUE: environment },
1457 start: false,
1458 });
1459 }),
1460 );
1461
1462 const first = yield* deployWithEnvironment("first");
1463 const second = yield* deployWithEnvironment("second");
1464
1465 expect(second.id).not.toBe(first.id);
1466 const info = yield* docker.container.inspect(second.name);
1467 expect(info.Config.Env).toContain("VALUE=second");
1468 expect(info.Config.Env).not.toContain("VALUE=first");
1469 }),
1470 );
1471
1472 test.provider(
1473 "recreates a container when a Docker image is rebuilt with the same ref",
1474 (stack) =>
1475 Effect.gen(function* () {
1476 const fs = yield* FileSystem.FileSystem;
1477 const path = yield* Path.Path;
1478 const docker = yield* Docker.Docker;
1479 const root = yield* fs.makeTempDirectoryScoped({
1480 prefix: "alchemy-container-image-",
1481 });
1482 const deploy = () =>
1483 stack.deploy(
1484 Effect.gen(function* () {
1485 const image = yield* Docker.Image("container-image", {
1486 build: { context: root },
1487 });
1488 const container = yield* Docker.Container("rebuilt-image-container", {
1489 image,
1490 start: false,
1491 });
1492 return { container, image };
1493 }),
1494 );
1495
1496 yield* fs.writeFileString(
1497 path.join(root, "Dockerfile"),
1498 "FROM nginx:alpine\nLABEL alchemy.generation=first\n",
1499 );
1500 const first = yield* deploy();
1501 yield* fs.writeFileString(
1502 path.join(root, "Dockerfile"),
1503 "FROM nginx:alpine\nLABEL alchemy.generation=second\n",
1504 );
1505 const second = yield* deploy();
1506
1507 expect(second.image.imageRef).toBe(first.image.imageRef);
1508 expect(second.image.imageId).not.toBe(first.image.imageId);
1509 expect(second.container.id).not.toBe(first.container.id);
1510 const info = yield* docker.container.inspect(second.container.name);
1511 expect(info.Image).toBe(second.image.imageId);
1512 }),
1513 { timeout: 120_000 },
1514 );
1515
1516 // #1990: an image that is still an Output at plan time (here from an
1517 // Action) must still roll the container when it resolves to a new value.
1518 test.provider("recreates a container when an Action-resolved image changes", (stack) =>
1519 Effect.gen(function* () {
1520 const docker = yield* Docker.Docker;
1521 const Resolve = Action("ContainerImageRef", (input: { image: string }) =>
1522 Effect.succeed(input.image),
1523 );
1524 const deploy = (image: string) =>
1525 stack.deploy(
1526 Effect.gen(function* () {
1527 const ref = yield* Resolve({ image });
1528 return yield* Docker.Container("action-image-container", {
1529 image: ref,
1530 command: ["sleep", "300"],
1531 start: true,
1532 });
1533 }),
1534 );
1535
1536 const first = yield* deploy("alpine:3.19");
1537 const second = yield* deploy("busybox:1.36");
1538 expect(second.id).not.toBe(first.id);
1539 expect(second.imageRef).toBe("busybox:1.36");
1540 expect((yield* docker.container.inspect(second.name)).Config.Image).toBe("busybox:1.36");
1541
1542 // The same resolved image keeps the container.
1543 const third = yield* deploy("busybox:1.36");
1544 expect(third.id).toBe(second.id);
1545 }),
1546 );
1547
1548 test.provider("adopts a container from a named context without removing it", (stack) =>
1549 Effect.gen(function* () {
1550 const docker = yield* Docker.Docker;
1551 const context = "alchemy-test-container-adoption";
1552 const name = "alchemy-test-adopted-container";
1553 const { stdout: host } = yield* docker.run([
1554 "context",
1555 "inspect",
1556 "--format",
1557 "{{.Endpoints.docker.Host}}",
1558 ]);
1559
1560 yield* docker.context.remove(context, true).pipe(Effect.ignore);
1561 yield* docker.context.create({
1562 name: context,
1563 docker: `host=${host.trim()}`,
1564 });
1565 yield* Effect.addFinalizer(() => docker.context.remove(context, true).pipe(Effect.ignore));
1566 yield* docker.container.remove(name, true, context).pipe(Effect.ignore);
1567 const { stdout: id } = yield* docker.run([
1568 "--context",
1569 context,
1570 "container",
1571 "create",
1572 "--name",
1573 name,
1574 "nginx:alpine",
1575 ]);
1576 yield* Effect.addFinalizer(() =>
1577 docker.container.remove(name, true, context).pipe(Effect.ignore),
1578 );
1579
1580 const adopted = yield* stack.deploy(
1581 Docker.Container("adopted-container", {
1582 name,
1583 image: "nginx:alpine",
1584 context,
1585 }),
1586 );
1587
1588 expect(adopted.id).toBe(id);
1589 }),
1590 );
1591
1592 test.provider("updates start state without replacing the container", (stack) =>
1593 Effect.gen(function* () {
1594 const first = yield* stack.deploy(
1595 Docker.Container("started-container", {
1596 image: "nginx:alpine",
1597 start: false,
1598 }),
1599 );
1600 const second = yield* stack.deploy(
1601 Docker.Container("started-container", {
1602 image: "nginx:alpine",
1603 start: true,
1604 }),
1605 );
1606
1607 expect(second.id).toBe(first.id);
1608 expect(second.status).toBe("running");
1609 }),
1610 );
1611
1612 test.provider(
1613 "updates networks without replacing a container with a host-bound port",
1614 (stack) =>
1615 Effect.gen(function* () {
1616 const hostPort = yield* findAvailablePort();
1617 const deployWithAlias = (alias: string) =>
1618 stack.deploy(
1619 Effect.gen(function* () {
1620 const network = yield* Docker.Network("host-port-network");
1621 const container = yield* Docker.Container("host-port-container", {
1622 image: "nginx:alpine",
1623 ports: [
1624 {
1625 external: `127.0.0.1:${hostPort}`,
1626 internal: 80,
1627 },
1628 ],
1629 networks: [{ name: network.name, aliases: [alias] }],
1630 });
1631 return { container, network };
1632 }),
1633 );
1634
1635 const first = yield* deployWithAlias("old-alias");
1636 const second = yield* deployWithAlias("new-alias");
1637
1638 expect(second.container.id).toBe(first.container.id);
1639 }),
1640 );
1641
1642 test.provider(
1643 "reconciles removed environment after a creating-state image prop is lost",
1644 (stack) =>
1645 Effect.gen(function* () {
1646 const docker = yield* Docker.Docker;
1647 const first = yield* stack.deploy(
1648 Docker.Container("lost-image-env-container", {
1649 image: "nginx:alpine",
1650 environment: { OLD_VALUE: "present" },
1651 }),
1652 );
1653
1654 yield* wedgeContainerRow(stack);
1655
1656 const second = yield* stack.deploy(
1657 Docker.Container("lost-image-env-container", {
1658 image: "nginx:alpine",
1659 }),
1660 );
1661 const info = yield* docker.container.inspect(second.name);
1662
1663 expect(second.id).not.toBe(first.id);
1664 expect(info.Config.Env).not.toContain("OLD_VALUE=present");
1665 }),
1666 );
1667 },
1668 );