From bb39eeae9da90a77fe960de27856bbbfa2eb8880 Mon Sep 17 00:00:00 2001 From: Sebastian Lorenz Date: Sun, 25 Oct 2026 19:07:14 +0000 Subject: [PATCH] feat(docker): declare how output streams are framed in DockerApi HttpApiSchema.Upgrade can declare the headers of its 101 now, so attach and exec start declare their Content-Type, and the logs of containers, services and tasks declare theirs as a stream header, all as the new DockerApi.StreamContentType: raw-stream for a TTY, multiplexed-stream otherwise. The services frame a stream by the decoded media type, with no parsing of their own; without the header they fall back to the TTY as before. DockerApi.ExecStartConfig is the Engine's start options with Detach false only: a detached start answers 200 instead of upgrading the connection, which an upgrade endpoint can't declare. --- .changeset/effect-docker.md | 2 +- packages/effect/src/docker/DockerApi.ts | 64 ++++++++++++++++--- .../effect/src/docker/DockerContainers.ts | 21 +++--- packages/effect/src/docker/DockerExec.ts | 40 +++++------- packages/effect/src/docker/DockerServices.ts | 10 +-- 5 files changed, 87 insertions(+), 50 deletions(-) diff --git a/.changeset/effect-docker.md b/.changeset/effect-docker.md index 58f0140a1e..6776fb458c 100644 --- a/.changeset/effect-docker.md +++ b/.changeset/effect-docker.md @@ -8,7 +8,7 @@ Add `effect/docker`, an Effect-native client for the Docker Engine API, and `Nod - `DockerSchema` holds Schemas for the Engine's request and response definitions, generated from moby's API document (API 1.56, decoding every version from 1.44). - `DockerConfig` is the client's configuration as plain data: `layer` takes static values, and `layerFromEnv` reads it as the Docker CLI does (`DOCKER_HOST`, contexts, TLS material, `config.json`). - `DockerEngine` is the connection to one Engine: an `HttpClient` that negotiates the API version. It holds no registry credentials. -- `DockerApi` defines the Engine API as `HttpApi` endpoint groups, one per area, which the services are clients of, and the models they take and return where those differ from `DockerSchema`'s, such as secrets as `Redacted`. `ApiVersions` annotates the endpoints and request fields newer than API 1.44 with the version they arrived in. A test checks the groups against the operations of the pinned API document, with the places where the Engine differs from it listed. Every endpoint declares the Engine's error responses (`EngineErrors`, or `SwarmErrors` where Swarm serves it, whose 503 is `SwarmUnavailable`), which decode to the `DockerError` reason classes; services fail with them as `DockerError`, which names the operation. +- `DockerApi` defines the Engine API as `HttpApi` endpoint groups, one per area, which the services are clients of, and the models they take and return where those differ from `DockerSchema`'s, such as secrets as `Redacted`. `ApiVersions` annotates the endpoints and request fields newer than API 1.44 with the version they arrived in. Logs, attach and exec start declare the `Content-Type` that says how their output is framed (`StreamContentType`), attach and exec start on their `101`. A test checks the groups against the operations of the pinned API document, with the places where the Engine differs from it listed. Every endpoint declares the Engine's error responses (`EngineErrors`, or `SwarmErrors` where Swarm serves it, whose 503 is `SwarmUnavailable`), which decode to the `DockerError` reason classes; services fail with them as `DockerError`, which names the operation. - `DockerSystem` covers ping, version, info, events, disk usage, registry login and build-cache pruning. - `DockerContainers` covers the container lifecycle, logs, stats, attach and archives; `DockerExec` runs commands in running containers; `DockerNetworks` and `DockerVolumes` manage networks and volumes. - `DockerRegistryAuth` resolves the registry credentials that images, plugins and services send, as the Docker CLI does (`DOCKER_AUTH_CONFIG`, credential helpers, `auths`); provide it yourself to resolve them another way. diff --git a/packages/effect/src/docker/DockerApi.ts b/packages/effect/src/docker/DockerApi.ts index 9e8f43840f..a7b1a42019 100644 --- a/packages/effect/src/docker/DockerApi.ts +++ b/packages/effect/src/docker/DockerApi.ts @@ -222,8 +222,31 @@ export class SwarmErrors extends HttpApiMiddleware.Service()("effec const id = { id: Schema.String } const name = { name: Schema.String } -/** The headers of a logs response: its `Content-Type` says whether it is raw or multiplexed. */ -const logsHeaders = { "content-type": Schema.optional(Schema.String) } +/** + * The media type of a container's output stream, which logs, attach and exec + * start answer with: `multiplexed-stream` frames stdout and stderr, + * `raw-stream` is the output of a TTY as it is. + * + * @stability unstable + * @category schemas + * @since 4.2.0 + */ +export const StreamContentType = Schema.Literals([ + "application/vnd.docker.raw-stream", + "application/vnd.docker.multiplexed-stream" +]) + +/** + * The media type of a container's output stream, see {@link StreamContentType}. + * + * @stability unstable + * @category models + * @since 4.2.0 + */ +export type StreamContentType = typeof StreamContentType.Type + +/** The headers of an output stream's response, or of its `101`: the `Content-Type` says how it is framed. */ +const streamHeaders = { "content-type": Schema.optional(StreamContentType) } /** * Filters of a list or prune: values by key, one value as a string, as the Engine's JSON `map[string][]string` query parameter. @@ -703,7 +726,7 @@ export const Containers = HttpApiGroup.make("containers").add( tail: Schema.optional(Schema.Union([Schema.Number, Schema.Literal("all")])) }, // raw or multiplexed, as the `Content-Type` says - success: HttpApiSchema.WithHeaders(HttpApiSchema.StreamUint8Array(), logsHeaders) + success: HttpApiSchema.WithHeaders(HttpApiSchema.StreamUint8Array(), streamHeaders) }), HttpApiEndpoint.get("stats", "/containers/:id/stats", { params: id, @@ -735,7 +758,7 @@ export const Containers = HttpApiGroup.make("containers").add( logs: Schema.optional(Schema.Boolean), detachKeys: Schema.optional(Schema.String) }, - success: HttpApiSchema.Upgrade({ protocol: "tcp" }) + success: HttpApiSchema.Upgrade({ protocol: "tcp", headers: streamHeaders }) }), HttpApiEndpoint.head("statPath", "/containers/:id/archive", { params: id, @@ -787,10 +810,33 @@ export const ExecConfig = DockerSchema.ExecConfig.mapFields((fields) => ({ ...fi */ export type ExecConfig = typeof ExecConfig.Type +/** + * How to start an exec, as the Engine's `ExecStartConfig`, attached to its + * stdio: `Detach` can only be `false`. A detached start answers `200` instead + * of upgrading the connection, which an upgrade endpoint can't declare. + * + * @stability unstable + * @category schemas + * @since 4.2.0 + */ +export const ExecStartConfig = DockerSchema.ExecStartConfig.mapFields((fields) => ({ + ...fields, + Detach: Schema.optionalKey(Schema.Literal(false)) +})) + +/** + * How to start an exec, see {@link ExecStartConfig}. + * + * @stability unstable + * @category models + * @since 4.2.0 + */ +export type ExecStartConfig = typeof ExecStartConfig.Type + /** * The Engine's exec endpoints, which `DockerExec` is a client of. Starting an * exec upgrades its request, which carries the start options, to the exec's - * stdio. + * stdio, framed as the `101`'s `Content-Type` says. * * @stability unstable * @category groups @@ -808,8 +854,8 @@ export const Exec = HttpApiGroup.make("exec").add( }), HttpApiEndpoint.post("start", "/exec/:id/start", { params: id, - payload: DockerSchema.ExecStartConfig, - success: HttpApiSchema.Upgrade({ protocol: "tcp" }) + payload: ExecStartConfig, + success: HttpApiSchema.Upgrade({ protocol: "tcp", headers: streamHeaders }) }), HttpApiEndpoint.post("resize", "/exec/:id/resize", { params: id, @@ -1431,7 +1477,7 @@ export const Services = HttpApiGroup.make("services").add( params: id, query: LogsQuery, // raw or multiplexed, as the `Content-Type` says - success: HttpApiSchema.WithHeaders(HttpApiSchema.StreamUint8Array(), logsHeaders) + success: HttpApiSchema.WithHeaders(HttpApiSchema.StreamUint8Array(), streamHeaders) }) ).middleware(SwarmErrors) @@ -1459,7 +1505,7 @@ export const Tasks = HttpApiGroup.make("tasks").add( params: id, query: LogsQuery, // raw or multiplexed, as the `Content-Type` says - success: HttpApiSchema.WithHeaders(HttpApiSchema.StreamUint8Array(), logsHeaders) + success: HttpApiSchema.WithHeaders(HttpApiSchema.StreamUint8Array(), streamHeaders) }) ).middleware(SwarmErrors) diff --git a/packages/effect/src/docker/DockerContainers.ts b/packages/effect/src/docker/DockerContainers.ts index fb41a439b3..13c9e48e53 100644 --- a/packages/effect/src/docker/DockerContainers.ts +++ b/packages/effect/src/docker/DockerContainers.ts @@ -54,7 +54,7 @@ import { withStreamOperation } from "./DockerEngine.ts" import { DockerError, InvalidResponse, StreamFailed } from "./DockerError.ts" -import { frames, type Framing, fromContentType, type Handle, makeHandle, releaseOnFailure } from "./DockerExec.ts" +import { contentTypeOf, frames, type Handle, makeHandle, releaseOnFailure } from "./DockerExec.ts" import * as DockerSchema from "./DockerSchema.ts" /** @@ -589,13 +589,14 @@ export const make: Effect.Effect api.inspect({ params: { id }, query: options ?? {} }) const resize: DockerContainers["Service"]["resize"] = (id, size) => api.resize({ params: { id }, query: size }) - /** The framing of a stream, from its `Content-Type`, otherwise from whether the container has a TTY. */ - const framingOf = (id: string, contentType: string | undefined): Effect.Effect => { - const framing = fromContentType(contentType) - return framing !== undefined - ? Effect.succeed(framing) - : Effect.map(inspect(id), (info) => info.Config?.Tty === true ? "raw" : "multiplexed") - } + /** A stream's content type, as the Engine sends it, otherwise from whether the container has a TTY. */ + const contentTypeFor = ( + id: string, + contentType: DockerApi.StreamContentType | undefined + ): Effect.Effect => + contentType !== undefined + ? Effect.succeed(contentType) + : Effect.map(inspect(id), (info) => contentTypeOf(info.Config?.Tty === true)) const getArchive: DockerContainers["Service"]["getArchive"] = (id, containerPath) => Effect.map( @@ -637,7 +638,7 @@ export const make: Effect.Effect - Effect.map(framingOf(id, headers["content-type"]), (framing) => frames(body, framing)) + Effect.map(contentTypeFor(id, headers["content-type"]), (contentType) => frames(body, contentType)) ) ) ).pipe(withStreamOperation(engine, "docker.Containers.logs", id)) @@ -675,7 +676,7 @@ export const make: Effect.Effect Fiber.join(exitCode), resize: (size) => resize(id, size) diff --git a/packages/effect/src/docker/DockerExec.ts b/packages/effect/src/docker/DockerExec.ts index 06eb038a66..fbbdb2605a 100644 --- a/packages/effect/src/docker/DockerExec.ts +++ b/packages/effect/src/docker/DockerExec.ts @@ -302,7 +302,7 @@ export const make: Effect.Effect = E function*(id: string, options?: { readonly consoleSize?: DockerApi.TtySize | undefined }) { const info = yield* inspect(id) const tty = info.ProcessConfig?.tty === true - const body: DockerSchema.ExecStartConfig = { + const body: DockerApi.ExecStartConfig = { Detach: false, Tty: tty, ...(options?.consoleSize !== undefined @@ -314,7 +314,7 @@ export const make: Effect.Effect = E return yield* makeHandle({ engine, socket, - framing: fromContentType(headers["content-type"]) ?? (tty ? "raw" : "multiplexed"), + contentType: headers["content-type"] ?? contentTypeOf(tty), stdin: info.OpenStdin === true, exitCode: (outputDone) => Effect.andThen(outputDone, exitCodeWith(inspect, id)), resize: (size) => resize(id, size) @@ -412,7 +412,8 @@ export const layer: Layer.Layer = Layer.effect( // ----------------------------------------------------------------------------- /* - * The Engine's stream framing for logs, attach and exec. + * The Engine's stream framing for logs, attach and exec, which the response's + * `Content-Type` names (`DockerApi.StreamContentType`). * * Without a TTY the Engine multiplexes stdout and stderr: each frame has an * 8-byte header `[type, 0, 0, 0, size (uint32, big-endian)]` followed by `size` @@ -422,26 +423,13 @@ export const layer: Layer.Layer = Layer.effect( */ /** - * How to read a stream: multiplexed frames, or raw stdout. + * The content type of a stream that has none: raw with a TTY, multiplexed + * otherwise. * * @internal */ -export type Framing = "multiplexed" | "raw" - -/** - * Picks the framing from a `Content-Type`, when it is one of the two stream - * types. Any other content type, or none, decides nothing. - * - * @internal - */ -export const fromContentType = (contentType: string | undefined): Framing | undefined => { - const type = contentType?.split(";")[0].trim().toLowerCase() - return type === "application/vnd.docker.multiplexed-stream" - ? "multiplexed" - : type === "application/vnd.docker.raw-stream" - ? "raw" - : undefined -} +export const contentTypeOf = (tty: boolean): DockerApi.StreamContentType => + tty ? "application/vnd.docker.raw-stream" : "application/vnd.docker.multiplexed-stream" /** * The result of feeding bytes to a demultiplexer. `SystemError` ends the @@ -505,15 +493,17 @@ const truncatedFrame = (pending: number): DockerError => }) /** - * Turns a byte stream into frames with the given framing. + * Turns a byte stream into frames, as its content type frames it. * * @internal */ export const frames = ( bytes: Stream.Stream, - framing: Framing + contentType: DockerApi.StreamContentType ): Stream.Stream => { - if (framing === "raw") return Stream.map(bytes, (data): LogFrame => ({ stream: "stdout", data })) + if (contentType === "application/vnd.docker.raw-stream") { + return Stream.map(bytes, (data): LogFrame => ({ stream: "stdout", data })) + } return Stream.suspend(() => { const demuxer = makeDemuxer() return Stream.flatMap(bytes, (chunk): Stream.Stream => { @@ -567,7 +557,7 @@ const isEnd = (error: Socket.SocketError): boolean => export const makeHandle = (options: { readonly engine: DockerEngine["Service"] readonly socket: Socket.Socket - readonly framing: Framing + readonly contentType: DockerApi.StreamContentType readonly stdin: boolean /** * For exec, runs once the output has ended (`outputDone` fails with the @@ -594,7 +584,7 @@ export const makeHandle = (options: { ) if (chunks === undefined) break for (const chunk of chunks) { - if (options.framing === "raw") { + if (options.contentType === "application/vnd.docker.raw-stream") { yield* Queue.offer(stdout, chunk) continue } diff --git a/packages/effect/src/docker/DockerServices.ts b/packages/effect/src/docker/DockerServices.ts index 18a1d0f1e3..7ace21e269 100644 --- a/packages/effect/src/docker/DockerServices.ts +++ b/packages/effect/src/docker/DockerServices.ts @@ -41,7 +41,7 @@ import type * as DockerConfig from "./DockerConfig.ts" import { type LogFrame, logsQuery } from "./DockerContainers.ts" import { apiClient, DockerEngine, modifyWith, withOperation, withStreamOperation } from "./DockerEngine.ts" import { DockerError, InvalidResponse } from "./DockerError.ts" -import { frames, fromContentType } from "./DockerExec.ts" +import { frames } from "./DockerExec.ts" import * as DockerImages from "./DockerImages.ts" import { authConfig, DockerRegistryAuth } from "./DockerRegistryAuth.ts" import type * as DockerSchema from "./DockerSchema.ts" @@ -189,17 +189,17 @@ export const parseLogLine = (line: string, options?: { readonly timestamps?: boo */ export const logFrames = ( logs: { - readonly headers: { readonly "content-type"?: string | undefined } + readonly headers: { readonly "content-type"?: DockerApi.StreamContentType | undefined } readonly body: Stream.Stream }, operation: string ): Stream.Stream => { - const framing = fromContentType(logs.headers["content-type"]) - return framing === undefined + const contentType = logs.headers["content-type"] + return contentType === undefined ? Stream.fail( new DockerError({ reason: new InvalidResponse({ issue: "the logs have no stream Content-Type" }), operation }) ) - : frames(logs.body, framing) + : frames(logs.body, contentType) } // -----------------------------------------------------------------------------