The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,264 lines 44.4 KB
Raw
1 import { Unowned } from "alchemy/AdoptPolicy";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import { Platform, type Main, type PlatformProps } from "alchemy/Platform";
4 import * as Provider from "alchemy/Provider";
5 import type { Resource } from "alchemy/Resource";
6 import {
7 createContainerRuntimeContext,
8 type HostRuntimeContext,
9 type ServerHost,
10 } from "alchemy/Runtime/Process";
11 import { Stack } from "alchemy/Stack";
12 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
13 import * as Data from "effect/Data";
14 import * as Effect from "effect/Effect";
15 import * as Equal from "effect/Equal";
16 import type { PlatformError } from "effect/PlatformError";
17 import * as Redacted from "effect/Redacted";
18 import * as Schedule from "effect/Schedule";
19 import type * as rolldown from "rolldown";
20 import { Docker, dockerEngineContextName, dockerPhysicalName } from "./Docker.ts";
21 import { healthcheckCommand, isHealthcheckDisabled } from "./HealthcheckCommand.ts";
22 import type { Providers } from "./Providers.ts";
23 import { makeServiceImage } from "./ServiceImage.ts";
24
25 export interface ServicePropsBase extends PlatformProps {
26 /**
27 * Service name.
28 *
29 * @default Generated from stack, stage, logical id, and instance id.
30 */
31 name?: string;
32 /**
33 * The engine the service is deployed to: a Docker context name, a
34 * `Docker.Context` resource, or a `Docker.Swarm` — passing the swarm also
35 * orders the service after the swarm is initialized.
36 */
37 context?: Docker.EngineRef;
38 /** Entrypoint command passed after the image. */
39 command?: string[];
40 /** Additional args appended after `command`. */
41 args?: string[];
42 /** Environment variables. Use Redacted for secrets. */
43 environment?: Record<string, string | Redacted.Redacted<string>>;
44 /**
45 * Environment variables injected by the platform (bound `Config` values and
46 * future bindings). Merged after `environment`; usually not set directly.
47 */
48 env?: Record<string, any>;
49 /** Overlay networks attached to this service. */
50 networks?: Array<string | Service.NetworkAttachment>;
51 /** Published port mappings. */
52 ports?: Service.PortMapping[];
53 /**
54 * Service discovery endpoint mode.
55 *
56 * @default "vip"
57 */
58 endpointMode?: "vip" | "dnsrr";
59 /**
60 * Desired number of service replicas.
61 *
62 * @default 1
63 */
64 replicas?: number;
65 /** Placement controls for task scheduling. */
66 placement?: Service.Placement;
67 /** Deprecated alias for `placement.constraints`. */
68 constraints?: string[];
69 /** Rolling update strategy for service updates. */
70 updateConfig?: Service.RolloutConfig;
71 /** Rollback strategy applied when updates fail. */
72 rollbackConfig?: Service.RolloutConfig;
73 /** Task restart behavior. */
74 restartPolicy?: Service.RestartPolicy;
75 /** Container healthcheck for service tasks. */
76 healthcheck?: Service.Healthcheck;
77 /** Grace period before force-killing a task during shutdown, e.g. `"30s"`. */
78 stopGracePeriod?: string;
79 /** Volume or bind mounts. */
80 volumes?: Service.VolumeMapping[];
81 /** Swarm secrets mounted into task containers. */
82 secrets?: Service.SecretRef[];
83 /** Swarm configs mounted into task containers. */
84 configs?: Service.ConfigRef[];
85 /**
86 * Mount task root filesystem read-only.
87 *
88 * @default false
89 */
90 readOnlyRootFs?: boolean;
91 /**
92 * Service labels. Alchemy's internal ownership labels are added
93 * automatically.
94 */
95 labels?: Record<string, string>;
96 }
97
98 /**
99 * Run a pre-built image: a registry reference or a Docker image resource
100 * (`Docker.Image` / `Docker.RemoteImage`).
101 */
102 export interface ImageServiceProps extends ServicePropsBase {
103 /** Docker image reference or Docker image resource. */
104 image: Service.Image;
105 main?: undefined;
106 }
107
108 /**
109 * Bundle an inline Effect program (`main`) into a generated image built
110 * against the service's Docker context. The optional `image` is the
111 * environment base (`FROM`) and must be able to run the bun runtime.
112 */
113 export interface BundledServiceProps extends ServicePropsBase {
114 /**
115 * Module entrypoint for the bundled program. This should typically be
116 * `import.meta.url` (or `import.meta.filename`) from an inline Effect
117 * program.
118 */
119 main: string;
120 /**
121 * Environment image used as the generated Dockerfile's `FROM`. Must be
122 * able to run the bun runtime.
123 *
124 * @default "oven/bun:1"
125 */
126 image?: string;
127 /**
128 * Container port the bundled HTTP server listens on. Baked into the image
129 * as `ENV PORT` + `EXPOSE`; publish it to the swarm ingress with `ports`.
130 */
131 port?: number;
132 /**
133 * Named export to load from `main`.
134 *
135 * @default "default"
136 */
137 handler?: string;
138 /** Bundler configuration for the entrypoint. */
139 build?: {
140 input?: Partial<rolldown.InputOptions>;
141 output?: Partial<rolldown.OutputOptions>;
142 };
143 }
144
145 /**
146 * Service props — the image comes from exactly one of two sources, flat on
147 * the props: `image` (a pre-built reference) or `main` (a bundled Effect
148 * program).
149 */
150 export type ServiceProps = ImageServiceProps | BundledServiceProps;
151
152 export declare namespace Service {
153 type Image = string | { imageRef: string };
154
155 interface PortMapping {
156 /** Published port on the swarm node. Omit to let Swarm assign one dynamically. */
157 external?: number;
158 /** Container port receiving traffic. */
159 internal: number;
160 /**
161 * Protocol used for the mapping.
162 *
163 * @default "tcp"
164 */
165 protocol?: "tcp" | "udp";
166 /**
167 * Publish through the swarm routing mesh (`ingress`) or directly on each
168 * node (`host`).
169 *
170 * @default "ingress"
171 */
172 mode?: "ingress" | "host";
173 }
174
175 interface VolumeMapping {
176 /** Host path or named volume source. */
177 hostPath: string;
178 /** Container path. */
179 containerPath: string;
180 /**
181 * Mount read-only.
182 *
183 * @default false
184 */
185 readOnly?: boolean;
186 }
187
188 interface NetworkAttachment {
189 /** Network name. */
190 name: string;
191 /** Network aliases for the service's tasks. */
192 aliases?: string[];
193 }
194
195 interface Placement {
196 /** Placement constraints, e.g. `"node.role==worker"`. */
197 constraints?: string[];
198 /** Placement preferences, e.g. `"spread=node.labels.zone"`. */
199 preferences?: string[];
200 /** Maximum number of replicas per swarm node. */
201 maxReplicasPerNode?: number;
202 }
203
204 interface RolloutConfig {
205 /** Number of tasks updated simultaneously. */
206 parallelism?: number;
207 /** Delay between task updates, e.g. `"10s"`. */
208 delay?: string;
209 /** Duration to monitor each updated task for failure, e.g. `"30s"`. */
210 monitor?: string;
211 /** Action on update failure. */
212 failureAction?: "pause" | "continue" | "rollback";
213 /** Failure ratio tolerated during an update. */
214 maxFailureRatio?: number;
215 /** Operation order during updates. */
216 order?: "stop-first" | "start-first";
217 }
218
219 interface RestartPolicy {
220 /** Condition under which tasks restart. */
221 condition?: "none" | "on-failure" | "any";
222 /** Delay between restart attempts, e.g. `"5s"`. */
223 delay?: string;
224 /** Maximum restart attempts before giving up. */
225 maxAttempts?: number;
226 /** Window used to evaluate the restart policy, e.g. `"120s"`. */
227 window?: string;
228 }
229
230 interface Healthcheck {
231 /**
232 * Command to run for health checks. A string runs in the container's
233 * shell. An array follows Docker's healthcheck `Test` form:
234 * `["CMD-SHELL", "pg_isready -U app"]`, `["CMD", "pg_isready", "-U", "app"]`,
235 * or `["NONE"]` to disable the image's healthcheck.
236 */
237 cmd: string[] | string;
238 /** Time between checks, e.g. `"30s"`. */
239 interval?: string;
240 /** Maximum time a check may run, e.g. `"5s"`. */
241 timeout?: string;
242 /** Consecutive failures before unhealthy. */
243 retries?: number;
244 /** Startup grace period, e.g. `"30s"`. */
245 startPeriod?: string;
246 }
247
248 interface SecretRef {
249 /** Swarm secret name. */
250 source: string;
251 /** Target file name in `/run/secrets/`. Defaults to `source`. */
252 target?: string;
253 /** File owner uid. */
254 uid?: string;
255 /** File owner gid. */
256 gid?: string;
257 /** File mode, e.g. `0o400`. */
258 mode?: number | string;
259 }
260
261 interface ConfigRef {
262 /** Swarm config name. */
263 source: string;
264 /** Target path in the container. Defaults to `/<source>`. */
265 target?: string;
266 /** File owner uid. */
267 uid?: string;
268 /** File owner gid. */
269 gid?: string;
270 /** File mode, e.g. `0o444`. */
271 mode?: number | string;
272 }
273 }
274
275 export interface Service extends Resource<
276 "Docker.Service",
277 ServiceProps,
278 {
279 /** Swarm service id. */
280 id: string;
281 /** Swarm service name. */
282 name: string;
283 /** Docker context the service is deployed to. */
284 context?: string;
285 /** Image reference the service runs. */
286 image: string;
287 /** Desired number of replicas. */
288 replicas: number;
289 /** Network ids the service's tasks attach to. */
290 networks: string[];
291 /** Published port mappings reported by Swarm. */
292 ports: Service.PortMapping[];
293 /** Service labels reported by Swarm. */
294 labels: Record<string, string>;
295 /** Service discovery endpoint mode. */
296 endpointMode: "vip" | "dnsrr";
297 /** Creation timestamp in milliseconds since epoch. */
298 createdAt: number;
299 /** Last update timestamp in milliseconds since epoch. */
300 updatedAt: number;
301 /** Content hash of the bundled program's image (`main` form only). */
302 code?: {
303 /** Content hash of the bundled program's image. */
304 hash: string;
305 };
306 },
307 never,
308 Providers
309 > {}
310
311 /** Services available to an effectful `Service` impl at init time. */
312 export type ServiceServices = ServerHost;
313
314 /**
315 * The impl shape for an effectful `Service`: a long-running server returning
316 * `{ fetch }` (plus optional RPC methods).
317 */
318 export type ServiceShape = Main<ServiceServices>;
319
320 export interface ServiceRuntimeContext extends HostRuntimeContext {
321 readonly Type: "Docker.Service";
322 }
323
324 /**
325 * A Docker Swarm service: N replicas of a container kept alive by the swarm,
326 * deployed through the active (or a named) Docker context.
327 *
328 * The target engine must be a swarm manager — `Service` wraps
329 * `docker service`, swarm mode's orchestration API. Declare the swarm with
330 * `Docker.Swarm` and pass it as `context` so the service deploys after the
331 * swarm exists; for a plain single container on a non-swarm daemon use
332 * `Docker.Container` instead.
333 *
334 * The service's image comes from one of two sources:
335 *
336 * - `image` — run a pre-built reference (a registry ref, or a `Docker.Image`
337 * / `Docker.RemoteImage` resource).
338 * - `main` — bundle an inline Effect program into a generated bun image,
339 * built directly against the service's Docker context. The impl returns
340 * `{ fetch }` and may register background loops via `ServerHost.run` —
341 * the same effectful platform shape as `AWS.ECS.Service`.
342 *
343 * The bundled image is content-addressed and only rebuilt when the program
344 * (or its generated Dockerfile) changes. It is built on the target engine's
345 * local store — single-node swarms run it as-is; multi-node swarms need the
346 * image on a registry every node can reach (build with `Docker.Image` +
347 * `registry` and pass the pushed ref as `image` instead).
348 *
349 * Only replicated services are supported. Changes to the image, replicas,
350 * environment, labels, networks, ports, mounts, secrets, configs, constraints,
351 * healthcheck, and rollout or restart policies are applied in place with
352 * `docker service update`, so swarm rolls tasks over following `updateConfig`.
353 * An update that swarm rolls back or pauses fails the deploy with
354 * `DockerServiceUpdateFailed`. Changing the name, context, command, args,
355 * endpoint mode, placement preferences, or read-only root filesystem, or
356 * removing a policy setting, replaces the service (delete-then-create).
357 * ### Creating Services
358 * **Example:** Replicated Nginx
359 * ```typescript
360 * const swarm = yield* Docker.Swarm("swarm");
361 * const web = yield* Docker.Service("web", {
362 * context: swarm,
363 * image: "nginx:alpine",
364 * replicas: 3,
365 * ports: [{ external: 8080, internal: 80 }],
366 * });
367 * ```
368 *
369 * **Example:** Run a Built Image
370 * ```typescript
371 * const image = yield* Docker.Image("app-image", {
372 * build: { context: "./app" },
373 * });
374 * const app = yield* Docker.Service("app", {
375 * context: swarm,
376 * image,
377 * replicas: 2,
378 * });
379 * ```
380 *
381 * ### Effectful Services
382 * **Example:** Inline Effect Server
383 * ```typescript
384 * const swarm = yield* Docker.Swarm("swarm");
385 * const api = yield* Docker.Service(
386 * "Api",
387 * {
388 * context: swarm,
389 * main: import.meta.url,
390 * port: 3000,
391 * ports: [{ external: 8080, internal: 3000 }],
392 * replicas: 2,
393 * },
394 * Effect.gen(function* () {
395 * return {
396 * fetch: Effect.gen(function* () {
397 * return yield* HttpServerResponse.json({ ok: true });
398 * }),
399 * };
400 * }),
401 * );
402 * ```
403 *
404 * **Example:** Background Loops with ServerHost
405 * ```typescript
406 * // Class props may be an Effect, so the service can yield the swarm it
407 * // deploys into (declared once at module level).
408 * const Swarm = Docker.Swarm("swarm");
409 *
410 * export default class Worker extends Docker.Service<Worker>()(
411 * "Worker",
412 * Effect.gen(function* () {
413 * const swarm = yield* Swarm;
414 * return { context: swarm, main: import.meta.url, port: 3000 };
415 * }),
416 * Effect.gen(function* () {
417 * const host = yield* ServerHost;
418 * yield* host.run(
419 * pollQueue.pipe(Effect.repeat(Schedule.spaced("5 seconds")), Effect.asVoid),
420 * );
421 * return {
422 * fetch: Effect.succeed(HttpServerResponse.text("ok")),
423 * };
424 * }),
425 * ) {}
426 * ```
427 *
428 * ### Bundling & Tree-shaking
429 * `main` is bundled with rolldown at deploy time. Unused code is
430 * tree-shaken. `effect`, alchemy, and `@distilled.cloud` are marked
431 * pure so unused parts prune more aggressively. Your app is not
432 * marked pure.
433 *
434 * **Example:** Mark additional packages as pure
435 * Only list packages with no top-level side effects.
436 * ```typescript
437 * {
438 * main: import.meta.url,
439 * build: {
440 * pure: { packages: ["my-lib", "@my-scope/*"] },
441 * },
442 * }
443 * ```
444 *
445 * **Example:** Turn it off
446 * ```typescript
447 * {
448 * main: import.meta.url,
449 * build: { pure: false },
450 * }
451 * ```
452 *
453 * ### Docker Contexts
454 * **Example:** Deploy to a Remote Swarm over SSH
455 * ```typescript
456 * const vps = yield* Docker.Context("vps", {
457 * docker: "host=ssh://deploy@example.com",
458 * });
459 * const swarm = yield* Docker.Swarm("swarm", {
460 * context: vps,
461 * advertiseAddr: "10.0.0.1",
462 * });
463 * const app = yield* Docker.Service("app", {
464 * context: swarm,
465 * image: "nginx:alpine",
466 * replicas: 3,
467 * });
468 * ```
469 *
470 * ### Networks & Volumes
471 * **Example:** Overlay Network with Aliases
472 * ```typescript
473 * const network = yield* Docker.Network("app-net", {
474 * context: swarm,
475 * driver: "overlay",
476 * });
477 * const db = yield* Docker.Service("db", {
478 * context: swarm,
479 * image: "postgres:18-alpine",
480 * networks: [{ name: network.name, aliases: ["postgres"] }],
481 * volumes: [{ hostPath: "pg-data", containerPath: "/var/lib/postgresql/data" }],
482 * });
483 * ```
484 *
485 * ### Rollouts & Placement
486 * **Example:** Rolling Update with Rollback
487 * ```typescript
488 * const app = yield* Docker.Service("app", {
489 * image: "ghcr.io/acme/app:latest",
490 * replicas: 4,
491 * updateConfig: {
492 * parallelism: 1,
493 * delay: "10s",
494 * failureAction: "rollback",
495 * order: "start-first",
496 * },
497 * placement: {
498 * constraints: ["node.role==worker"],
499 * maxReplicasPerNode: 2,
500 * },
501 * });
502 * ```
503 *
504 * ### Secrets & Configs
505 * **Example:** Mount Swarm Secrets
506 * ```typescript
507 * const app = yield* Docker.Service("app", {
508 * image: "ghcr.io/acme/app:latest",
509 * secrets: [{ source: "db-password", target: "db_password", mode: 0o400 }],
510 * configs: [{ source: "app-config", target: "/etc/app/config.yaml" }],
511 * });
512 * ```
513 *
514 * @resource
515 * @product Swarm
516 */
517 export const Service: Platform<Service, ServiceServices, ServiceShape, ServiceRuntimeContext> =
518 Platform("Docker.Service", {
519 createRuntimeContext: createContainerRuntimeContext("Docker.Service") as (
520 id: string,
521 ) => ServiceRuntimeContext,
522 });
523
524 /** True when the props declare a bundled `main` program. */
525 const isBundledService = (props: ServiceProps): props is BundledServiceProps =>
526 typeof (props as BundledServiceProps).main === "string";
527
528 /**
529 * A `docker service update` that swarm rolled back or paused instead of
530 * completing. `--detach=false` exits 0 on a rollback and 1 on a pause, so the
531 * provider reads the service's `UpdateStatus` after the update.
532 */
533 export class DockerServiceUpdateFailed extends Data.TaggedError("DockerServiceUpdateFailed")<{
534 readonly service: string;
535 readonly state: string;
536 readonly reason: string;
537 }> {
538 override get message() {
539 return `Update of service "${this.service}" ended in ${this.state}: ${this.reason}`;
540 }
541 }
542
543 type ServiceInspect = {
544 ID: string;
545 CreatedAt?: string;
546 UpdatedAt?: string;
547 UpdateStatus?: {
548 State?: string;
549 Message?: string;
550 };
551 Spec: {
552 Name: string;
553 Labels?: Record<string, string> | null;
554 TaskTemplate?: {
555 ContainerSpec?: {
556 Image?: string;
557 Env?: string[] | null;
558 Mounts?: Array<{ Target?: string }> | null;
559 Secrets?: Array<{ SecretName?: string }> | null;
560 Configs?: Array<{ ConfigName?: string }> | null;
561 };
562 Networks?: Array<{ Target?: string }>;
563 Placement?: {
564 Constraints?: string[];
565 };
566 };
567 Mode?: {
568 Replicated?: {
569 Replicas?: number;
570 };
571 Global?: Record<string, never>;
572 };
573 EndpointSpec?: {
574 Mode?: "vip" | "dnsrr";
575 Ports?: Array<{
576 PublishedPort?: number;
577 TargetPort?: number;
578 Protocol?: "tcp" | "udp";
579 PublishMode?: "ingress" | "host";
580 }>;
581 };
582 };
583 };
584
585 export const ServiceProvider = () =>
586 Provider.effect(
587 Service,
588 Effect.gen(function* () {
589 const docker = yield* Docker;
590 const stack = yield* Stack;
591 const serviceImage = yield* makeServiceImage;
592
593 // The bundled program's bootstrap reads these to rebuild the Stack at
594 // container runtime (same contract as the ECS bootstrap).
595 const alchemyEnv = {
596 ALCHEMY_STACK_NAME: stack.name,
597 ALCHEMY_STAGE: stack.stage,
598 ALCHEMY_PHASE: "runtime",
599 };
600
601 const inspect = (id: string, context?: string) =>
602 docker.service.inspect(id, context).pipe(
603 Effect.map((result) => normalizeServiceInspect(result)),
604 Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined),
605 );
606
607 /**
608 * Resolve the image the service should run: build the bundled `main`
609 * program (content-addressed, skipped when already present in the
610 * target engine) or normalize the pre-built reference.
611 */
612 const resolveImage = Effect.fn(function* (
613 id: string,
614 props: ServiceProps,
615 name: string,
616 context: string | undefined,
617 session: { note: (message: string) => Effect.Effect<void> },
618 ) {
619 if (isBundledService(props)) {
620 return yield* serviceImage.resolve({
621 id,
622 source: props,
623 name,
624 context,
625 isExternal: props.isExternal,
626 session,
627 });
628 }
629 return {
630 imageRef: normalizeImageRef(props.image),
631 codeHash: undefined,
632 };
633 });
634
635 return Service.Provider.of({
636 list: () => Effect.succeed([]),
637 read: Effect.fn(function* ({ id, instanceId, olds, output }) {
638 const name = yield* servicePhysicalName(id, olds, instanceId);
639 const context = dockerEngineContextName(olds?.context);
640 const live = yield* inspect(name, context);
641 if (!live) return undefined;
642 ensureReplicatedMode(live);
643 const attrs = toServiceAttributes(live, context, output?.code);
644 if (output) return attrs;
645 const owned = yield* hasAlchemyTags(id, live.Spec.Labels ?? undefined);
646 return owned ? attrs : Unowned(attrs);
647 }),
648 diff: Effect.fn(function* ({ id, instanceId, news, olds, output }) {
649 if (!isResolved(news)) return undefined;
650
651 const oldDesired = yield* normalizeDesired(id, olds, instanceId);
652 const newDesired = yield* normalizeDesired(id, news, instanceId);
653
654 if (!Equal.equals(oldDesired, newDesired)) {
655 return requiresReplacement(oldDesired, newDesired)
656 ? { action: "replace" as const, deleteFirst: true }
657 : { action: "update" as const };
658 }
659
660 // Bundled program: the image identity is the content hash — a code
661 // or bootstrap change rolls the service onto the new image.
662 if (isBundledService(news)) {
663 const hash = yield* serviceImage.hash({
664 source: news,
665 isExternal: news.isExternal,
666 });
667 if (hash !== output?.code?.hash) {
668 return { action: "update" as const };
669 }
670 }
671
672 return { action: "noop" as const };
673 }),
674 reconcile: Effect.fn(function* ({ id, instanceId, news, olds, output, session }) {
675 const desired = yield* normalizeDesired(id, news, instanceId);
676 const resolved = yield* resolveImage(id, news, desired.name, desired.context, session);
677 const image = resolved.imageRef;
678 const code = resolved.codeHash ? { hash: resolved.codeHash } : undefined;
679 const environment = isBundledService(news)
680 ? { ...alchemyEnv, ...desired.environment }
681 : desired.environment;
682
683 if (output && olds) {
684 const oldDesired = yield* normalizeDesired(id, olds, instanceId);
685 if (
686 deepEqual(oldDesired, desired) &&
687 (resolved.codeHash === undefined || resolved.codeHash === output.code?.hash)
688 ) {
689 const current = yield* inspect(output.id, desired.context);
690 if (current) {
691 ensureReplicatedMode(current);
692 return toServiceAttributes(current, desired.context, code);
693 }
694 }
695 }
696
697 if (output) {
698 const current = yield* inspect(output.id, desired.context);
699 if (current) {
700 ensureReplicatedMode(current);
701 const internalTags = yield* createInternalTags(id);
702 const allDesiredLabels = { ...internalTags, ...desired.labels };
703 const currentLabels = current.Spec.Labels ?? {};
704 const labelsToRemove = Object.keys(currentLabels).filter(
705 (k) => !(k in allDesiredLabels),
706 );
707 // `service update` only adds and removes list entries, so the
708 // removals are computed from the observed spec rather than olds.
709 const spec = current.Spec.TaskTemplate?.ContainerSpec;
710 const envToRemove = (spec?.Env ?? [])
711 .map((entry) => entry.split("=", 1)[0]!)
712 .filter((key) => !(key in environment));
713 const currentConstraints = current.Spec.TaskTemplate?.Placement?.Constraints ?? [];
714 const constraintsToRemove = currentConstraints.filter(
715 (c) => !desired.constraints.includes(c),
716 );
717 // `--constraint-add` appends without de-duplicating.
718 const constraintsToAdd = desired.constraints.filter(
719 (c) => !currentConstraints.includes(c),
720 );
721 const desiredTargets = new Set(desired.volumes.map((v) => v.containerPath));
722 const mountsToRemove = (spec?.Mounts ?? []).flatMap((m) =>
723 m.Target && !desiredTargets.has(m.Target) ? [m.Target] : [],
724 );
725 const desiredPorts = new Set(desired.ports.map(formatPublish));
726 const portsToRemove = (current.Spec.EndpointSpec?.Ports ?? []).flatMap((p) =>
727 p.TargetPort !== undefined &&
728 !desiredPorts.has(
729 formatPublish({
730 external: p.PublishedPort,
731 internal: p.TargetPort,
732 protocol: p.Protocol,
733 mode: p.PublishMode,
734 }),
735 )
736 ? // `--publish-rm` matches target, protocol and publish mode.
737 [
738 `target=${p.TargetPort},protocol=${p.Protocol ?? "tcp"},mode=${p.PublishMode ?? "ingress"}`,
739 ]
740 : [],
741 );
742 // A rollback exits 0 but a paused rollout exits 1, so the
743 // outcome is read from `UpdateStatus` either way.
744 const updateError = yield* docker.service
745 .update({
746 context: desired.context,
747 id: output.id,
748 image,
749 replicas: desired.replicas,
750 "endpoint-mode": desired.endpointMode,
751 // Attaching a network the service is already on fails, so
752 // every attachment is detached and the desired set re-added.
753 "network-rm": (current.Spec.TaskTemplate?.Networks ?? []).flatMap((n) =>
754 n.Target ? [n.Target] : [],
755 ),
756 "network-add": desired.networks.map(formatNetwork),
757 "constraint-rm": constraintsToRemove,
758 "constraint-add": constraintsToAdd,
759 "replicas-max-per-node": desired.maxReplicasPerNode,
760 "update-parallelism": desired.updateConfig?.parallelism,
761 "update-delay": desired.updateConfig?.delay,
762 "update-monitor": desired.updateConfig?.monitor,
763 "update-failure-action": desired.updateConfig?.failureAction,
764 "update-max-failure-ratio": desired.updateConfig?.maxFailureRatio,
765 "update-order": desired.updateConfig?.order,
766 "rollback-parallelism": desired.rollbackConfig?.parallelism,
767 "rollback-delay": desired.rollbackConfig?.delay,
768 "rollback-monitor": desired.rollbackConfig?.monitor,
769 "rollback-failure-action": desired.rollbackConfig?.failureAction,
770 "rollback-max-failure-ratio": desired.rollbackConfig?.maxFailureRatio,
771 "rollback-order": desired.rollbackConfig?.order,
772 "restart-condition": desired.restartPolicy?.condition,
773 "restart-delay": desired.restartPolicy?.delay,
774 "restart-max-attempts": desired.restartPolicy?.maxAttempts,
775 "restart-window": desired.restartPolicy?.window,
776 "health-cmd": desired.healthcheck
777 ? healthcheckCommand(desired.healthcheck.cmd)
778 : undefined,
779 "no-healthcheck":
780 desired.healthcheck !== undefined &&
781 isHealthcheckDisabled(desired.healthcheck.cmd),
782 "health-interval": desired.healthcheck?.interval,
783 "health-timeout": desired.healthcheck?.timeout,
784 "health-retries": desired.healthcheck?.retries,
785 "health-start-period": desired.healthcheck?.startPeriod,
786 "stop-grace-period": desired.stopGracePeriod,
787 "mount-rm": mountsToRemove,
788 "mount-add": desired.volumes.map(formatMount),
789 // Re-adding a ref that is still attached conflicts on its
790 // target, so every attached ref is removed and the desired
791 // set re-added in the same update.
792 "secret-rm": (spec?.Secrets ?? []).flatMap((s) =>
793 s.SecretName ? [s.SecretName] : [],
794 ),
795 "secret-add": desired.secrets.map(formatRef),
796 "config-rm": (spec?.Configs ?? []).flatMap((c) =>
797 c.ConfigName ? [c.ConfigName] : [],
798 ),
799 "config-add": desired.configs.map(formatRef),
800 "read-only": desired.readOnlyRootFs || undefined,
801 "publish-rm": portsToRemove,
802 "publish-add": desired.ports.map(formatPublish),
803 "label-add": allDesiredLabels,
804 "label-rm": labelsToRemove,
805 "env-rm": envToRemove,
806 "env-add": environment,
807 args:
808 desired.command.length > 0
809 ? desired.command.concat(desired.args).join(" ")
810 : undefined,
811 })
812 .pipe(
813 Effect.as(undefined),
814 Effect.catchTag("PlatformError", (error) => Effect.succeed(error)),
815 );
816
817 const updated = yield* inspectOrDie(inspect, output.id, desired.context);
818 // Swarm clears `UpdateStatus` whenever it accepts an update, so
819 // any status here belongs to this update.
820 const status = updated.UpdateStatus;
821 if (
822 status?.State === "rollback_completed" ||
823 status?.State === "rollback_paused" ||
824 status?.State === "paused"
825 ) {
826 return yield* new DockerServiceUpdateFailed({
827 service: updated.Spec.Name,
828 state: status.State,
829 reason: status.Message ?? "",
830 });
831 }
832 if (updateError) {
833 return yield* updateError;
834 }
835
836 // Best-effort: the service now runs the new content-addressed
837 // image, so drop the one built for the previous bundle.
838 if (output.code && output.code.hash !== resolved.codeHash) {
839 yield* docker.image
840 .remove(output.image, true, desired.context)
841 .pipe(Effect.catchCause(() => Effect.void));
842 }
843
844 return toServiceAttributes(updated, desired.context, code);
845 }
846 }
847
848 const existingByName = yield* inspect(desired.name, desired.context);
849 if (existingByName) {
850 ensureReplicatedMode(existingByName);
851 return toServiceAttributes(existingByName, desired.context, code);
852 }
853
854 const internalTags = yield* createInternalTags(id);
855 const allDesiredLabels = { ...internalTags, ...desired.labels };
856 yield* docker.service.create({
857 context: desired.context,
858 name: desired.name,
859 image,
860 replicas: desired.replicas,
861 "endpoint-mode": desired.endpointMode,
862 network: desired.networks.map(formatNetwork),
863 constraint: desired.constraints,
864 "replicas-max-per-node": desired.maxReplicasPerNode,
865 "placement-pref": desired.preferences,
866 "update-parallelism": desired.updateConfig?.parallelism,
867 "update-delay": desired.updateConfig?.delay,
868 "update-monitor": desired.updateConfig?.monitor,
869 "update-failure-action": desired.updateConfig?.failureAction,
870 "update-max-failure-ratio": desired.updateConfig?.maxFailureRatio,
871 "update-order": desired.updateConfig?.order,
872 "rollback-parallelism": desired.rollbackConfig?.parallelism,
873 "rollback-delay": desired.rollbackConfig?.delay,
874 "rollback-monitor": desired.rollbackConfig?.monitor,
875 "rollback-failure-action": desired.rollbackConfig?.failureAction,
876 "rollback-max-failure-ratio": desired.rollbackConfig?.maxFailureRatio,
877 "rollback-order": desired.rollbackConfig?.order,
878 "restart-condition": desired.restartPolicy?.condition,
879 "restart-delay": desired.restartPolicy?.delay,
880 "restart-max-attempts": desired.restartPolicy?.maxAttempts,
881 "restart-window": desired.restartPolicy?.window,
882 "health-cmd": desired.healthcheck
883 ? healthcheckCommand(desired.healthcheck.cmd)
884 : undefined,
885 "no-healthcheck":
886 desired.healthcheck !== undefined && isHealthcheckDisabled(desired.healthcheck.cmd),
887 "health-interval": desired.healthcheck?.interval,
888 "health-timeout": desired.healthcheck?.timeout,
889 "health-retries": desired.healthcheck?.retries,
890 "health-start-period": desired.healthcheck?.startPeriod,
891 "stop-grace-period": desired.stopGracePeriod,
892 mount: desired.volumes.map(formatMount),
893 secret: desired.secrets.map(formatRef),
894 config: desired.configs.map(formatRef),
895 "read-only": desired.readOnlyRootFs || undefined,
896 publish: desired.ports.map(formatPublish),
897 label: allDesiredLabels,
898 env: environment,
899 command: desired.command,
900 args: desired.args,
901 });
902 return toServiceAttributes(
903 yield* inspectOrDie(inspect, desired.name, desired.context),
904 desired.context,
905 code,
906 );
907 }),
908 delete: Effect.fn(({ output }) =>
909 docker
910 .run([
911 ...(output.context ? ["--context", output.context] : []),
912 "service",
913 "scale",
914 "--detach=false",
915 `${output.id}=0`,
916 ])
917 .pipe(
918 Effect.flatMap(() => docker.service.remove(output.id, output.context)),
919 Effect.flatMap(() =>
920 waitForServiceContainersReleased(docker, output.id, output.context),
921 ),
922 Effect.catchReason("PlatformError", "NotFound", () => Effect.void),
923 // Best-effort: drop the content-addressed image built for a
924 // bundled program so replaced/destroyed services don't strand
925 // local image tags.
926 Effect.andThen(
927 output.code
928 ? docker.image
929 .remove(output.image, true, output.context)
930 .pipe(Effect.catchCause(() => Effect.void))
931 : Effect.void,
932 ),
933 ),
934 ),
935 });
936 }),
937 );
938
939 /** Swarm rejects service names longer than 63 characters. */
940 const servicePhysicalName = (
941 id: string,
942 props: { name?: string } | undefined,
943 instanceId: string,
944 ) => dockerPhysicalName(id, props, instanceId, 63);
945
946 const normalizeDesired = (id: string, props: ServiceProps, instanceId: string) =>
947 servicePhysicalName(id, props, instanceId).pipe(
948 Effect.map((name) => ({
949 name,
950 context: dockerEngineContextName(props.context),
951 // The bundled form's image identity is its content hash (compared
952 // separately in diff) — the `image` prop is only the environment base
953 // there, and it participates in the hash.
954 image: isBundledService(props) ? undefined : normalizeImageRef(props.image),
955 command: props.command ?? [],
956 args: props.args ?? [],
957 environment: {
958 ...normalizeEnvironment(props.environment),
959 ...normalizeBoundEnv(props.env),
960 },
961 networks: normalizeNetworks(props.networks),
962 ports: normalizePorts(props.ports),
963 endpointMode: props.endpointMode ?? "vip",
964 replicas: normalizeReplicas(props.replicas),
965 constraints: [...(props.constraints ?? []), ...(props.placement?.constraints ?? [])],
966 maxReplicasPerNode: props.placement?.maxReplicasPerNode,
967 preferences: props.placement?.preferences ?? [],
968 updateConfig: props.updateConfig,
969 rollbackConfig: props.rollbackConfig,
970 restartPolicy: props.restartPolicy,
971 healthcheck: props.healthcheck,
972 stopGracePeriod: props.stopGracePeriod,
973 volumes: props.volumes ?? [],
974 secrets: props.secrets ?? [],
975 configs: props.configs ?? [],
976 readOnlyRootFs: props.readOnlyRootFs ?? false,
977 labels: props.labels ?? {},
978 })),
979 );
980
981 type DesiredService = Effect.Success<ReturnType<typeof normalizeDesired>>;
982
983 /**
984 * Fields `docker service update` changes in place. Swarm rolls the tasks
985 * onto the new spec following `updateConfig`, so `order: "start-first"` and
986 * `failureAction: "rollback"` apply.
987 */
988 const inPlaceFields = new Set<keyof DesiredService>([
989 "image",
990 "replicas",
991 "environment",
992 "labels",
993 "networks",
994 "constraints",
995 "maxReplicasPerNode",
996 "updateConfig",
997 "rollbackConfig",
998 "restartPolicy",
999 "healthcheck",
1000 "stopGracePeriod",
1001 "volumes",
1002 "secrets",
1003 "configs",
1004 "ports",
1005 ]);
1006
1007 /**
1008 * Settings `service update` can change but not reset to the engine default:
1009 * removing one, or a field inside one, replaces the service.
1010 */
1011 const resettableFields = new Set<keyof DesiredService>([
1012 "maxReplicasPerNode",
1013 "updateConfig",
1014 "rollbackConfig",
1015 "restartPolicy",
1016 "healthcheck",
1017 "stopGracePeriod",
1018 ]);
1019
1020 const clearsSetting = (olds: unknown, news: unknown): boolean => {
1021 if (olds === undefined) return false;
1022 if (news === undefined) return true;
1023 if (typeof olds !== "object" || olds === null) return false;
1024 return Object.entries(olds).some(
1025 ([key, value]) => value !== undefined && (news as Record<string, unknown>)[key] === undefined,
1026 );
1027 };
1028
1029 /**
1030 * `--publish-rm` matches target, protocol and mode, and `--publish-add` skips
1031 * a port already in the spec. Dropping one of several ports that share a
1032 * target therefore drops the kept ones too, so that change replaces.
1033 */
1034 const dropsSharedTargetPort = (olds: DesiredService, news: DesiredService): boolean => {
1035 const kept = new Set(news.ports.map(formatPublish));
1036 const key = (port: Service.PortMapping) => `${port.internal}/${port.protocol}/${port.mode}`;
1037 const removedKeys = new Set(olds.ports.filter((p) => !kept.has(formatPublish(p))).map(key));
1038 return olds.ports.some((p) => kept.has(formatPublish(p)) && removedKeys.has(key(p)));
1039 };
1040
1041 const requiresReplacement = (olds: DesiredService, news: DesiredService): boolean =>
1042 dropsSharedTargetPort(olds, news) ||
1043 (Object.keys(news) as Array<keyof DesiredService>).some(
1044 (key) =>
1045 !deepEqual(olds[key], news[key]) &&
1046 (!inPlaceFields.has(key) ||
1047 (resettableFields.has(key) && clearsSetting(olds[key], news[key]))),
1048 );
1049
1050 const normalizeImageRef = (image: Service.Image): string =>
1051 typeof image === "string" ? image : image.imageRef;
1052
1053 const normalizeEnvironment = (
1054 environment: Record<string, string | Redacted.Redacted<string>> | undefined,
1055 ) =>
1056 Object.fromEntries(
1057 Object.entries(environment ?? {}).map(([key, value]) => [
1058 key,
1059 Redacted.isRedacted(value) ? Redacted.value(value) : value,
1060 ]),
1061 );
1062
1063 /**
1064 * Platform-injected env (`props.env`) after Output resolution: values are
1065 * usually marker-packed strings, but tolerate Redacted and structured values.
1066 */
1067 const normalizeBoundEnv = (env: Record<string, any> | undefined): Record<string, string> =>
1068 Object.fromEntries(
1069 Object.entries(env ?? {}).map(([key, value]) => [
1070 key,
1071 typeof value === "string"
1072 ? value
1073 : Redacted.isRedacted(value)
1074 ? Redacted.value(value as Redacted.Redacted<string>)
1075 : JSON.stringify(value),
1076 ]),
1077 );
1078
1079 const normalizePorts = (ports: Service.PortMapping[] | undefined): Service.PortMapping[] =>
1080 (ports ?? []).map((port) => ({
1081 external: port.external,
1082 internal: port.internal,
1083 protocol: port.protocol ?? "tcp",
1084 mode: port.mode ?? "ingress",
1085 }));
1086
1087 const normalizeReplicas = (replicas: number | undefined): number => {
1088 const value = replicas ?? 1;
1089 if (!Number.isInteger(value) || value < 0) {
1090 throw new Error("Service.replicas must be an integer >= 0");
1091 }
1092 return value;
1093 };
1094
1095 const normalizeNetworks = (
1096 networks: Array<string | Service.NetworkAttachment> | undefined,
1097 ): Service.NetworkAttachment[] =>
1098 (networks ?? []).map((network) =>
1099 typeof network === "string"
1100 ? { name: network }
1101 : { name: network.name, aliases: network.aliases },
1102 );
1103
1104 const formatMount = (volume: Service.VolumeMapping): string =>
1105 [
1106 `type=${/^(\/|\.\/|\.\.\/|~)/.test(volume.hostPath) ? "bind" : "volume"}`,
1107 `source=${volume.hostPath}`,
1108 `target=${volume.containerPath}`,
1109 ...(volume.readOnly ? ["readonly=true"] : []),
1110 ].join(",");
1111
1112 const formatNetwork = (network: Service.NetworkAttachment): string =>
1113 [`name=${network.name}`, ...(network.aliases ?? []).map((a) => `alias=${a}`)].join(",");
1114
1115 const formatRef = (ref: Service.SecretRef | Service.ConfigRef): string =>
1116 Object.entries(ref)
1117 .filter(([, value]) => value !== undefined)
1118 .map(([key, value]) => `${key}=${value}`)
1119 .join(",");
1120
1121 const formatPublish = (port: Service.PortMapping): string =>
1122 [
1123 ...(port.external !== undefined ? [`published=${port.external}`] : []),
1124 `target=${port.internal}`,
1125 `protocol=${port.protocol ?? "tcp"}`,
1126 `mode=${port.mode ?? "ingress"}`,
1127 ].join(",");
1128
1129 const toServiceAttributes = (
1130 service: ServiceInspect,
1131 context?: string,
1132 code?: { hash: string },
1133 ): Service["Attributes"] => ({
1134 id: service.ID,
1135 name: service.Spec.Name,
1136 context,
1137 image: service.Spec.TaskTemplate?.ContainerSpec?.Image ?? "",
1138 replicas: service.Spec.Mode?.Replicated?.Replicas ?? 1,
1139 networks: (service.Spec.TaskTemplate?.Networks ?? []).flatMap((n) =>
1140 n.Target ? [n.Target] : [],
1141 ),
1142 ports: (service.Spec.EndpointSpec?.Ports ?? []).flatMap((port) => {
1143 if (port.PublishedPort === undefined || port.TargetPort === undefined) {
1144 return [];
1145 }
1146 return [
1147 {
1148 external: port.PublishedPort,
1149 internal: port.TargetPort,
1150 protocol: port.Protocol ?? "tcp",
1151 mode: port.PublishMode ?? "ingress",
1152 },
1153 ];
1154 }),
1155 labels: service.Spec.Labels ?? {},
1156 endpointMode: service.Spec.EndpointSpec?.Mode ?? "vip",
1157 createdAt: Date.parse(service.CreatedAt ?? "") || Date.now(),
1158 updatedAt: Date.parse(service.UpdatedAt ?? "") || Date.now(),
1159 code,
1160 });
1161
1162 const ensureReplicatedMode = (service: ServiceInspect): void => {
1163 if (service.Spec.Mode?.Global !== undefined) {
1164 throw new Error(
1165 `Docker.Service only supports replicated services. Service "${service.Spec.Name}" is global.`,
1166 );
1167 }
1168 };
1169
1170 const parseInspectArray = <T>(json: string): T => {
1171 const parsed = JSON.parse(json) as T[];
1172 if (parsed.length === 0) {
1173 throw new Error("docker inspect returned no objects");
1174 }
1175 return parsed[0]!;
1176 };
1177
1178 const normalizeServiceInspect = (value: unknown): ServiceInspect => {
1179 if (typeof value === "object" && value !== null && "stdout" in value) {
1180 const stdout = (value as { stdout?: unknown }).stdout;
1181 if (typeof stdout === "string") {
1182 return parseInspectArray<ServiceInspect>(stdout);
1183 }
1184 }
1185 return value as ServiceInspect;
1186 };
1187
1188 const inspectOrDie = <T>(
1189 inspect: (nameOrId: string, context?: string) => Effect.Effect<T | undefined, any>,
1190 nameOrId: string,
1191 context?: string,
1192 ) =>
1193 inspect(nameOrId, context).pipe(
1194 Effect.flatMap((value) =>
1195 value ? Effect.succeed(value) : Effect.die(`Expected ${nameOrId} to exist after create`),
1196 ),
1197 );
1198
1199 const waitForServiceContainersReleased = (
1200 docker: Docker["Service"],
1201 serviceId: string,
1202 context?: string,
1203 ): Effect.Effect<void, PlatformError> => {
1204 const maxAttempts = 10;
1205 const noContainers = Symbol.for("Docker.Service.NoContainers");
1206
1207 const poll = listServiceContainerIds(docker, serviceId, context).pipe(
1208 Effect.flatMap((containerIds) =>
1209 containerIds.length === 0 ? Effect.fail(noContainers) : Effect.succeed(containerIds),
1210 ),
1211 );
1212
1213 return poll.pipe(
1214 Effect.repeat(Schedule.spaced("1 second").pipe(Schedule.upTo({ times: maxAttempts - 1 }))),
1215 Effect.catchIf(
1216 (error): error is typeof noContainers => error === noContainers,
1217 () => Effect.void,
1218 ),
1219 Effect.andThen(listServiceContainerIds(docker, serviceId, context)),
1220 Effect.flatMap((containerIds) =>
1221 containerIds.length === 0
1222 ? Effect.void
1223 : // Best effort cleanup for lingering task containers that keep volumes attached.
1224 Effect.forEach(
1225 containerIds,
1226 (containerId) =>
1227 docker
1228 .run([
1229 ...(context ? ["--context", context] : []),
1230 "container",
1231 "rm",
1232 "-f",
1233 containerId,
1234 ])
1235 .pipe(Effect.catchCause(() => Effect.void)),
1236 { concurrency: "unbounded" },
1237 ).pipe(Effect.as(undefined)),
1238 ),
1239 );
1240 };
1241
1242 const listServiceContainerIds = (
1243 docker: Docker["Service"],
1244 serviceId: string,
1245 context?: string,
1246 ): Effect.Effect<string[], PlatformError> =>
1247 docker
1248 .run([
1249 ...(context ? ["--context", context] : []),
1250 "ps",
1251 "-a",
1252 "--filter",
1253 `label=com.docker.swarm.service.id=${serviceId}`,
1254 "--format",
1255 "{{.ID}}",
1256 ])
1257 .pipe(
1258 Effect.map((result) =>
1259 result.stdout
1260 .split("\n")
1261 .map((line) => line.trim())
1262 .filter((line) => line.length > 0),
1263 ),
1264 );