@alchemy.run/docker 0.0.0 → 2.0.0-beta.84

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