diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 6513e576b..8096e688e 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -897,28 +897,26 @@ receives. The gateway's `GatewayRelay` hands one `Request` to the worker's `relayTargets` under the module's capability name, and answers the target's `Response` with its body streamed. The core names no target. -Three admin operations carry it over the uplink, and a worker answers them -only on the gateway's own uplink session (`FORBIDDEN` elsewhere; a gateway -refuses them from everyone): +Two admin operations and one byte channel carry it over the uplink, and a +worker answers the operations only on the gateway's own uplink session +(`FORBIDDEN` elsewhere; a gateway refuses them from everyone): - `relay.request` opens a relay (`relayId`, `target`, method, URL, headers, - tenant, lease id, `hasBody`) and answers `{}` once the response body has - ended, or `{ cancelled: true }` once a cancel took effect. The response - leaves as request-scoped `relay-head` and `relay-chunk` pushes keyed by its - frame id, each written before the next part of the target's body is read. -- `relay.body` sends the request body in `seq` order, then `end`. A call is - answered once the target's stream has taken the chunk, so the gateway - keeps at most 4 unanswered. + tenant, lease id, `hasBody`, `channel`) and answers `{}` once the response + body has ended, or `{ cancelled: true }` once a cancel took effect. The head + leaves as a request-scoped `relay-head` push keyed by its frame id. The + request body arrives, and the response body leaves, on the byte channel + `channel` names (ADR 0028). The worker accepts the channel when it reads the + line, before the call parks for startup. - `relay.cancel` aborts the target's `Request` signal; so does the close of the connection the relay came on. -The gateway bounds every wait: a deadline for the whole exchange -(`WORKER_UNREACHABLE` when it passes), 8 relays at once per worker, and 64 -MiB of response a caller has not read. A lost uplink fails the call as +The gateway bounds every wait: one deadline for the whole exchange, channel +wait included (`WORKER_UNREACHABLE` when it passes). The link bounds the +channels open to a worker at 64. A lost uplink fails the call as `WORKER_UNREACHABLE` through `isUplinkLost`, the one function the relay, the -lease coordinator and the component relay all ask. The uplink is shared, so a -large relay delays the other calls on it (no flow control; #511 accepts -this). +lease coordinator and the component relay all ask. A slow reader slows only +its own channel, and small calls go first on the uplink. ### Aggregated reads diff --git a/docs/internal/COMPONENTS.md b/docs/internal/COMPONENTS.md index 5d2ba91ab..ba80c22fe 100644 --- a/docs/internal/COMPONENTS.md +++ b/docs/internal/COMPONENTS.md @@ -41,8 +41,8 @@ rule 14); a single-file component's surface is what the file exports. | `DaemonEndpointHost` | `src/daemon/connection-host.ts` | Claiming the socket, recovering a stale entry, the listener lifecycle. | Anything after a connection is accepted. | | `AdminSecretManager`, session resolver | `src/daemon/admin-secret.ts`, `src/daemon/session.ts` | The per-start admin secret, its hash and persistence; turning a credential into `{ principal, role }`. | Decide what a role may do. | | `GatewayUplink` | `src/daemon/gateway-uplink.ts` | When a worker dials its gateway: one outbound connection, redialled with backoff, handed to `DaemonServer`. | What travels over the link. | -| Link module | `src/link/` (surface: `index.ts`) | Wrapping one uplink transport connection (ADR 0028 §1-3): text messages passed through unchanged and ahead of bulk bytes, byte channels with credit, the envelope, the two-lane scheduler and the channel rules, the 64 channel limit and the waits it bounds (30 s accept, 60 s credit). Nothing uses it yet; #558 wraps the uplink with it. | Know what a channel carries, or touch a socket (the transport port does). | -| Relay targets | `src/daemon/relay.ts` | A worker's `relayTargets` (capability name to a function that takes a `Request`, a tenant and a lease id and answers a `Response`), and per uplink connection the relays it carries: the request body fed by `relay.body`, the response sent as `relay-head` and `relay-chunk` pushes, cancel and abort on close. Nothing registers a target yet. | Name a target: the core knows none; modules register through the option. | +| Link module | `src/link/` (surface: `index.ts`) | Wrapping one uplink transport connection (ADR 0028 §1-3): text messages passed through unchanged and ahead of bulk bytes, byte channels with credit, the envelope, the two-lane scheduler and the channel rules, the 64 channel limit and the waits it bounds (30 s accept, 60 s credit). Both uplink ends (the worker's and the gateway's) wrap their connection with it. | Know what a channel carries, or touch a socket (the transport port does). | +| Relay targets | `src/daemon/relay.ts` | A worker's `relayTargets` (capability name to a function that takes a `Request`, a tenant and a lease id and answers a `Response`), and per uplink connection the relays it carries: the request body read from the relay's byte channel, the head sent as a `relay-head` push and the response body written to the channel, cancel and abort on close. `src/daemon/main.ts` registers the `agent-device` target through the option. | Name a target: the core knows none; modules register through the option. | | `OwnerRoutedFactBus` | `src/daemon/owner-routed-facts.ts` | Re-emitting lease-scoped facts with the lease's owner attached, for pushes and HTTP notices. | Emit a business fact of its own. | ## Core: device management @@ -156,7 +156,7 @@ typed against and catalog matching (ARCHITECTURE.md, "Boundaries"). | Routing | `src/gateway/routing.ts`, `src/gateway/routing/` (surface: `index.ts`) | The pure routing policy: an ordered list of stages (`takes-requests`, `can-serve`, `healthy`, `idle-queue`, `warm-hit`, `free-slot`, `ram-budget`, `free-capacity`) over worker views, selected by `gateway.routing`; a physical request skips the stages whose `appliesToPhysical` is `false` (`idle-queue`, `free-slot`, `ram-budget`, `free-capacity`) and matches the enrolled physical devices in each worker's view (`physicalMatch`). | Read anything but views; order stages from config. | | `GatewayDispatcher` | `src/gateway/dispatcher.ts` | The second implementation of the contract's handlers (ADR 0005 §32): answered from the fleet, forwarded to one worker, or fanned out to all. | Define a second contract or role check. | | Aggregate, component relay | `src/gateway/aggregate.ts`, `src/gateway/component-relay.ts` | The fleet expressed in one machine's shapes, as pure functions over views; asking every worker to install a component and collecting one outcome each. | Decide anything a worker decides. | -| `GatewayRelay` | `src/gateway/relay.ts` | Handing one HTTP exchange to a relay target on a worker over its uplink (ADR 0026): `relay.request`, the request body as `relay.body` calls (4 unanswered at most), the response from `relay-head` and `relay-chunk` pushes; the deadline, 8 relays per worker, 64 MiB of unread response, cancel and `WORKER_UNREACHABLE` on a lost uplink. | Route to a worker or know which module a target is. | +| `GatewayRelay` | `src/gateway/relay.ts` | Handing one HTTP exchange to a relay target on a worker over its uplink (ADR 0026): `relay.request`, the request body and the response body on a byte channel opened on the uplink's link, the head from a `relay-head` push; the deadline over the channel wait and the exchange, cancel and `WORKER_UNREACHABLE` on a lost uplink. | Route to a worker or know which module a target is. | | `GatewayOwnerRoutedFacts` | `src/gateway/owner-routed-facts.ts` | The gateway's owner-attributed lease facts, from relayed worker events. | Emit a fact of its own. | ## Ports diff --git a/docs/internal/adr/0028-the-uplink-carries-byte-channels-and-small-messages-go-first.md b/docs/internal/adr/0028-the-uplink-carries-byte-channels-and-small-messages-go-first.md index 55517d6f9..c0038dfd3 100644 --- a/docs/internal/adr/0028-the-uplink-carries-byte-channels-and-small-messages-go-first.md +++ b/docs/internal/adr/0028-the-uplink-carries-byte-channels-and-small-messages-go-first.md @@ -1,6 +1,6 @@ # 0028. The uplink carries byte channels beside its messages, and small messages go first -- **Status:** Accepted — partly implemented: §1–3 (the link module and the transport port, #556); §4–6 (relays on channels, the download cap, the protocol bump) follow +- **Status:** Accepted — partly implemented: §1–3 (the link module and the transport port, #556); §4 and §6 (relays on channels, the protocol bump, #558); §5 (the download cap, #557) follows - **Date:** 2026-10-14 - **Issue:** [#552](https://github.com/callstackincubator/simlock/issues/552) - **Narrows:** [ADR 0026](0026-agent-device-through-a-gateway-relays-over-the-uplink.md) diff --git a/src/admin/index.test.ts b/src/admin/index.test.ts index 262aecb33..697b11775 100644 --- a/src/admin/index.test.ts +++ b/src/admin/index.test.ts @@ -10,6 +10,7 @@ describe("simlock/admin", () => { expectTypeOf().not.toHaveProperty("relayRequest"); expectTypeOf().not.toHaveProperty("relayBody"); expectTypeOf().not.toHaveProperty("relayCancel"); + expectTypeOf().not.toHaveProperty("openChannel"); const documented = readFileSync(new URL("../../docs/CLIENT.md", import.meta.url), "utf8"); expect(Object.keys(admin).filter((name) => /relay/i.test(name))).toEqual([]); diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index 3ba5b4c73..d458a4f8f 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -1301,9 +1301,10 @@ describe("the agent-device front, through a gateway", { timeout: 60_000 }, () => const held = member.fake.leases.get(hex(1)); expect(held).toBeDefined(); member.fake.leases.set(hex(2), { ...(held as NonNullable), leaseId: hex(2) }); + // why: a lease whose requester is not its own id is never adopted, so the front's memory lacks it however soon the worker's catalog arrives. await rig.gateway.dispatch( "lease.request", - { leaseId: hex(2), platform: "ios", requesterId: hex(2), requires: ["agent-device"] }, + { leaseId: hex(2), platform: "ios", requesterId: "someone-else", requires: ["agent-device"] }, sessionFor(principals.one), ); interceptRelay(rig, async ({ request }) => { @@ -1998,8 +1999,15 @@ describe( async function restarted(rig: Rig, member: Member, leases: number): Promise { await rig.restart(); - // why: the worker's redial delay doubles with each restart in a row (1 s, 2 s, 4 s ... up to its jitter), so one test that restarts four times waits up to 8 s. - await advance(rig, 8_000, 500); + // why: the worker's redial delay doubles with each restart in a row and carries jitter, so the clock moves on until the worker is back instead of by a sum that a fourth restart can outrun. + await vi.waitFor( + async () => { + const view = await viewOf(rig, member.label); + if (view?.connection !== "connected") await advance(rig, 1_000, 500); + expect(view?.connection).toBe("connected"); + }, + { interval: 20, timeout: 30_000 }, + ); await untilRead(rig, member); await expect.poll(async () => (await fleetLeases(rig)).length).toBe(leases); } diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index ee89980da..062180752 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -8,6 +8,7 @@ import { requestedDevice, } from "./operations.js"; import { PUSH_SCHEMAS } from "./pushes.js"; +import { relayChannelSchema } from "./relay.js"; import type { Role } from "./roles.js"; import { platformCatalogSchema } from "./schemas.js"; @@ -80,7 +81,6 @@ const ROLE_MATRIX: ReadonlyArray<{ }, role: "admin", }, - { name: "relay.body", input: { end: true, relayId: "r-1" }, role: "admin" }, { name: "relay.cancel", input: { relayId: "r-1" }, role: "admin" }, ]; @@ -162,7 +162,6 @@ const EFFECT_MATRIX: ReadonlyArray<{ }, effect: "write", }, - { name: "relay.body", input: { end: true, relayId: "r-1" }, effect: "write" }, { name: "relay.cancel", input: { relayId: "r-1" }, effect: "write" }, ]; @@ -1556,3 +1555,40 @@ describe("lease.request requires", () => { ); }); }); + +describe("relay.request on a byte channel", () => { + const request = { + hasBody: false, + headers: [], + method: "GET", + relayId: "r-1", + target: "agent-device", + tenant: "gw.g.a", + url: "http://gateway.test/x", + }; + const parse = (input: Record) => + OPERATIONS["relay.request"].input.safeParse(input).success; + + it("accepts a channel of 1 to 32 characters of [A-Za-z0-9-] and refuses an empty, a 33-character and a bad-character one, and a request without one", () => { + expect(parse({ ...request, channel: "a" })).toBe(true); + expect(parse({ ...request, channel: "Ab-9".repeat(8) })).toBe(true); + expect(parse({ ...request, channel: "" })).toBe(false); + expect(parse({ ...request, channel: "a".repeat(33) })).toBe(false); + expect(parse({ ...request, channel: "a b" })).toBe(false); + expect(parse({ ...request, channel: "a_b" })).toBe(false); + expect(parse(request)).toBe(false); + }); + + it("relayChannelSchema holds the same bound the operation uses", () => { + expect(relayChannelSchema.safeParse("a".repeat(32)).success).toBe(true); + expect(relayChannelSchema.safeParse("a".repeat(33)).success).toBe(false); + expect(relayChannelSchema.safeParse("").success).toBe(false); + expect(relayChannelSchema.safeParse("a b").success).toBe(false); + }); + + it("OPERATIONS has no relay.body and PUSH_SCHEMAS has no relay-chunk", () => { + expect(Object.keys(OPERATIONS)).not.toContain("relay.body"); + expect(Object.keys(PUSH_SCHEMAS)).not.toContain("relay-chunk"); + expect(Object.keys(PUSH_SCHEMAS)).toContain("relay-head"); + }); +}); diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 7e191503c..4d140f78d 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -11,7 +11,7 @@ import { z } from "zod"; import { CONSOLE_URL_MAX_LENGTH } from "./console-url.js"; import { parseOsConstraint } from "./os-range.js"; -import { relayChunkSchema, relayHeadersSchema, relayIdSchema } from "./relay.js"; +import { relayChannelSchema, relayHeadersSchema, relayIdSchema } from "./relay.js"; import { ownsLease, type AuthorizeContext, type Role } from "./roles.js"; import { capabilityNameSchema, @@ -977,8 +977,9 @@ const relayUrlSchema = z /** * One HTTP exchange a gateway hands to a module on a worker, over the gateway's uplink. The - * response leaves as `relay-head` and `relay-chunk` pushes keyed by this call's frame id; the - * answer comes once its body has ended, or `{ cancelled: true }` once a `relay.cancel` took + * request body arrives, and the response body leaves, on the byte channel `channel` names (ADR 0028); + * the head leaves as a `relay-head` push keyed by this call's frame id. The + * answer comes once the response body has ended, or `{ cancelled: true }` once a `relay.cancel` took * effect. Admin only, and on a worker only the gateway's own uplink session may call it. */ // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. @@ -996,6 +997,7 @@ export const relayRequest = defineOperation({ tenant: z.string().min(1).max(300), leaseId: leaseIdSchema.optional(), hasBody: z.boolean(), + channel: relayChannelSchema, }) .strict() .refine((input) => !input.hasBody || (input.method !== "GET" && input.method !== "HEAD"), { @@ -1004,21 +1006,6 @@ export const relayRequest = defineOperation({ output: z.object({ cancelled: z.literal(true).optional() }), }); -/** One part of a relayed request body, in `seq` order, or its end. */ -// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. -export const relayBody = defineOperation({ - name: "relay.body", - role: "admin", - effect: "write", - input: z.union([ - z - .object({ relayId: relayIdSchema, seq: z.number().int().min(0), chunk: relayChunkSchema }) - .strict(), - z.object({ relayId: relayIdSchema, end: z.literal(true) }).strict(), - ]), - output: z.object({}), -}); - // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. export const relayCancel = defineOperation({ name: "relay.cancel", @@ -1062,7 +1049,6 @@ export const OPERATIONS = { "device.add": deviceAdd, "device.remove": deviceRemove, "relay.request": relayRequest, - "relay.body": relayBody, "relay.cancel": relayCancel, } as const; diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 4eca8d816..2df08cb0a 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 33, max: 33 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 34, max: 34 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/contract/pushes.ts b/src/contract/pushes.ts index 170fbaab6..c36192cf4 100644 --- a/src/contract/pushes.ts +++ b/src/contract/pushes.ts @@ -2,8 +2,7 @@ * why: server pushes (ADR 0003 §8). Three families, each with its correlation key required by * schema: * - * - Request-scoped (`progress`, `started`, `output`, `component-progress`, `relay-head`, - * `relay-chunk`): carries the + * - Request-scoped (`progress`, `started`, `output`, `component-progress`, `relay-head`): carries the * originating request's frame id. * - Lease-scoped (`lease-lost`, `device-unhealthy`, `device-recovered`): carries the lease id, * and goes to every live connection whose principal owns that lease (ADR 0004 §5 keeps @@ -15,7 +14,7 @@ */ import { z } from "zod"; -import { relayChunkSchema, relayHeadersSchema } from "./relay.js"; +import { relayHeadersSchema } from "./relay.js"; import { eventEnvelopeSchema, leaseProgressSchema } from "./schemas.js"; /** @@ -105,11 +104,6 @@ const relayHeadPushSchema = z.object({ headers: relayHeadersSchema, }); -const relayChunkPushSchema = z.object({ - requestId: requestIdSchema, - chunk: relayChunkSchema, -}); - const leaseLostPushSchema = z.object({ leaseId: z.string(), deviceId: z.string(), @@ -139,7 +133,6 @@ export const PUSH_SCHEMAS = { started: startedPushSchema, "component-progress": componentProgressPushSchema, "relay-head": relayHeadPushSchema, - "relay-chunk": relayChunkPushSchema, "lease-lost": leaseLostPushSchema, "device-unhealthy": deviceUnhealthyPushSchema, "device-recovered": deviceRecoveredPushSchema, diff --git a/src/contract/relay.ts b/src/contract/relay.ts index 4923101d4..93a0c8dfb 100644 --- a/src/contract/relay.ts +++ b/src/contract/relay.ts @@ -5,16 +5,14 @@ import { z } from "zod"; export const RELAY_MAX_HEADERS = 100; -export const RELAY_MAX_CHUNK_BYTES = 262_144; -/** why: the base64 length of the largest chunk, rounded up to a whole quantum of four. */ -const RELAY_MAX_CHUNK_CHARACTERS = 349_528; -export const RELAY_MAX_PUSH_BYTES = 256 * 1024; const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; -const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; export const relayIdSchema = z.string().regex(/^[A-Za-z0-9-]{1,64}$/); +// why: the channel id is wire input the worker checks before it accepts a channel (ADR 0028). +export const relayChannelSchema = z.string().regex(/^[A-Za-z0-9-]{1,32}$/); + export const relayHeadersSchema = z .array( z.tuple([ @@ -27,8 +25,6 @@ export const relayHeadersSchema = z ) .max(RELAY_MAX_HEADERS); -export const relayChunkSchema = z.string().max(RELAY_MAX_CHUNK_CHARACTERS).regex(BASE64); - // why: the relay re-creates these on each side instead of carrying them. const FRAMING_HEADERS: ReadonlySet = new Set([ "connection", diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index b4e3a092d..8d6a138e0 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(33); + expect(DAEMON_PROTOCOL_VERSION).toBe(34); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/dispatch.ts b/src/daemon/dispatch.ts index 1ccbc8865..4550ca01d 100644 --- a/src/daemon/dispatch.ts +++ b/src/daemon/dispatch.ts @@ -17,6 +17,7 @@ import type { z } from "zod"; import type { Clock } from "../ports/clock.js"; import type { Logger } from "../ports/logger.js"; +import type { LinkChannel } from "../link/index.js"; import type { RelayConnection } from "./relay.js"; import { describeSchemaIssues, @@ -122,8 +123,8 @@ export interface DispatchSession { status: number, headers: readonly (readonly [string, string])[], ) => Promise; - // why: resolved once the part is written, so a target is read only as fast as the socket takes its parts. - readonly onRelayChunk?: (chunk: string) => Promise; + // why: accepted by the server when it read the `relay.request` line, before the call parked for startup (ADR 0028). + readonly relayChannel?: LinkChannel; /** `events.subscribe`/`events.unsubscribe` stay push-shaped (ADR §2: "pushes" stay with the * transport), so the dispatcher's handler for them does nothing but call this: `true` to * (re)subscribe, returning the new subscription id; `false` to tear an existing one down. */ diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 9f2b16bd5..0a00acbbe 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -277,7 +277,6 @@ export class Dispatcher { "driver.passthrough": this.#driverPassthrough, "device.exec": this.#deviceExec, "relay.request": this.#relayRequest, - "relay.body": this.#relayBody, "relay.cancel": this.#relayCancel, "doctor.run": this.#doctorRun, "lease.release-all": this.#leaseReleaseAll, @@ -588,15 +587,19 @@ export class Dispatcher { return session.relays; } - #relayRequest: Handler<"relay.request"> = (input, session) => - this.#relays(session).request(input, { - chunk: (chunk) => session.onRelayChunk?.(chunk) ?? Promise.resolve(), - head: (status, headers) => session.onRelayHead?.(status, headers) ?? Promise.resolve(), - }); - - #relayBody: Handler<"relay.body"> = async (input, session) => { - await this.#relays(session).body(input); - return {}; + #relayRequest: Handler<"relay.request"> = (input, session) => { + const relays = this.#relays(session); + if (session.relayChannel === undefined) { + throw new DispatchError( + "BAD_REQUEST", + `The relay's channel ${input.channel} was not accepted`, + ); + } + return relays.request( + input, + { head: (status, headers) => session.onRelayHead?.(status, headers) ?? Promise.resolve() }, + session.relayChannel, + ); }; #relayCancel: Handler<"relay.cancel"> = (input, session) => { diff --git a/src/daemon/gateway-uplink.ts b/src/daemon/gateway-uplink.ts index 3d4787428..f23210443 100644 --- a/src/daemon/gateway-uplink.ts +++ b/src/daemon/gateway-uplink.ts @@ -7,7 +7,8 @@ * `DaemonServer` (which serves it) and in the gateway (which drives it). All this class decides * is *when to dial*. */ -import type { Clock, IpcConnection, Logger, TimerHandle, UplinkConnector } from "../ports/index.js"; +import { createLink, type LinkConnection } from "../link/index.js"; +import type { Clock, Logger, TimerHandle, UplinkConnector } from "../ports/index.js"; import { NoopLogger, UplinkError } from "../ports/index.js"; export interface UplinkBackoff { @@ -39,7 +40,7 @@ export interface GatewayUplinkOptions { /** This worker's instance id (`instance.json`) -- its fleet identity (§3a). */ readonly workerId: string; /** Hands an established uplink to whoever serves it (`DaemonServer#acceptUplink`). */ - readonly accept: (connection: IpcConnection) => void; + readonly accept: (connection: LinkConnection) => void; readonly logger?: Logger; readonly backoff?: UplinkBackoff; /** H1: how long a connection must stay up before `#attempt` resets to 0. Defaults to the @@ -62,7 +63,7 @@ export class GatewayUplink { readonly #random: () => number; #attempt = 0; #timer: TimerHandle | undefined; - #connection: IpcConnection | undefined; + #connection: LinkConnection | undefined; #stopped = false; /** Guards against two dials in flight at once -- a `close` arriving while a dial is pending * would otherwise schedule a second one beside it. */ @@ -131,13 +132,18 @@ export class GatewayUplink { await connection.close(); return; } - this.#connection = connection; - connection.onClose(() => this.#onClosed()); + const link = createLink(connection, { + clock: this.options.clock, + end: "worker", + logger: this.#logger, + }); + this.#connection = link; + link.onClose(() => this.#onClosed()); this.#logger.info("Uplink to gateway established", { url: this.options.url, workerId: this.options.workerId, }); - this.options.accept(connection); + this.options.accept(link); // H1: `#attempt` resets only once this link has actually stayed up for `#minStableMs` -- // not the instant `connect()` resolves. Cancelled in `#onClosed`/`stop` if the close // beats it, which is exactly the accept-then-immediately-close case this guards against. diff --git a/src/daemon/relay-gateway.e2e.test.ts b/src/daemon/relay-gateway.e2e.test.ts index bbc8a2b16..767bb74e4 100644 --- a/src/daemon/relay-gateway.e2e.test.ts +++ b/src/daemon/relay-gateway.e2e.test.ts @@ -2,7 +2,8 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { FakeDriver } from "../core/testing.js"; import { GatewayRelay, type GatewayWorkerClient, type WorkerDirectory } from "../gateway/index.js"; -import { MemoryFilesystem, NoopLogger, SystemClock, createConnectionPair } from "../ports/index.js"; +import { linkPair, TappedTransport, TYPE } from "../link/testing.js"; +import { MemoryFilesystem, NoopLogger, SystemClock } from "../ports/index.js"; import { connectSimlockClient } from "../simlock-client/client.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon } from "./main.js"; @@ -20,8 +21,8 @@ import { patternBytes, patternDigest, patternStream, - readAll, - settle, + readParts, + settleWithin, sleep, startWorker, type WorkerFixture, @@ -62,24 +63,19 @@ function buildCall(init: CallInit) { interface ClientSpy { readonly events: string[]; - unanswered: number; - maxUnanswered: number; - bodyCalls: number; } function spyOn(client: GatewayWorkerClient): { client: GatewayWorkerClient; spy: ClientSpy } { - const spy: ClientSpy = { bodyCalls: 0, events: [], maxUnanswered: 0, unanswered: 0 }; + const spy: ClientSpy = { events: [] }; const wrapHooks = (value: unknown): unknown => { if (typeof value !== "object" || value === null) return value; const hooks = { ...(value as Record) }; - for (const name of ["onRelayHead", "onRelayChunk"]) { - const original = hooks[name]; - if (typeof original === "function") { - hooks[name] = (...args: unknown[]) => { - spy.events.push(`push:${name}`); - return (original as (...rest: unknown[]) => unknown)(...args); - }; - } + const original = hooks.onRelayHead; + if (typeof original === "function") { + hooks.onRelayHead = (...args: unknown[]) => { + spy.events.push("push:onRelayHead"); + return (original as (...rest: unknown[]) => unknown)(...args); + }; } return hooks; }; @@ -95,18 +91,6 @@ function spyOn(client: GatewayWorkerClient): { client: GatewayWorkerClient; spy: return value; }; } - if (property === "relayBody") { - return async (...args: unknown[]) => { - spy.bodyCalls += 1; - spy.unanswered += 1; - spy.maxUnanswered = Math.max(spy.maxUnanswered, spy.unanswered); - try { - return await method.apply(target, args); - } finally { - spy.unanswered -= 1; - } - }; - } if (property === "relayCancel") { return async (...args: unknown[]) => { spy.events.push("cancel-sent"); @@ -155,10 +139,11 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { "agent-device": target, echo: target, }); - const [workerEnd, gatewayEnd] = createConnectionPair(); - fixture.worker.acceptUplink(workerEnd); + const pair = linkPair(); + const gatewayEnd = pair.gatewayEnd; + fixture.worker.acceptUplink(pair.worker); const connected = (await connectSimlockClient( - { connection: gatewayEnd, principal: "gw:test" }, + { connection: pair.gateway, principal: "gw:test" }, true, )) as GatewayWorkerClient; const { client, spy } = spyOn(connected); @@ -168,11 +153,14 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { ? { client: () => client, reachable: true, refresh: async () => undefined, workerId } : undefined, }; - const relay = new GatewayRelay({ - directory, - ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }), - }); - return { fixture, gatewayEnd, relay, spy }; + const makeRelay = (relayOptions: { readonly deadlineMs?: number } = {}) => + new GatewayRelay({ + directory, + ...(relayOptions.deadlineMs === undefined ? {} : { deadlineMs: relayOptions.deadlineMs }), + }); + const relay = makeRelay(options); + const opened = () => pair.gatewayTap.binaries(TYPE.OPEN).length; + return { fixture, gatewayEnd, makeRelay, opened, pair, relay, spy }; } async function startFleet(execCommand?: { args: string[]; command: string; env: object }) { @@ -180,6 +168,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { directories.push(gatewayDirectory); const port = await freeLoopbackPort(); let relay: GatewayRelay | undefined; + const taps: TappedTransport[] = []; const gateway = await startDaemon({ configOverrides: { http: { enabled: true, host: "127.0.0.1", port }, mode: "gateway" }, dataDirectory: gatewayDirectory, @@ -187,6 +176,18 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { gatewayRelay: (given) => { relay = given; }, + gatewayUplinks: (uplinks) => { + const listen = uplinks.listen.bind(uplinks); + uplinks.listen = (handlers) => + listen({ + ...handlers, + accept: (uplink) => { + const tap = new TappedTransport(uplink.connection); + taps.push(tap); + handlers.accept({ ...uplink, connection: tap }); + }, + }); + }, logger: new NoopLogger(), statePath: join(gatewayDirectory, "state.json"), version: "1.0.0-e2e", @@ -233,7 +234,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { { timeout: 10_000 }, ); expect(relay).toBeDefined(); - return { gateway, relay: relay as unknown as GatewayRelay, worker, workerId }; + return { gateway, relay: relay as unknown as GatewayRelay, taps, worker, workerId }; } const agent = (overrides: Partial = {}): DispatchSession => ({ @@ -272,24 +273,58 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(await response.text()).toBe("hello from the target"); }, 30_000); + it("through startFleet, a relayed GET opens a channel on the link between the gateway and the worker", async () => { + behavior = () => Promise.resolve(new Response("over a channel")); + const { relay, taps, workerId } = await startFleet(); + + const response = await relay.relay(workerId, buildCall({})); + const body = await response.text(); + + expect(body).toBe("over a channel"); + expect(taps.flatMap((tap) => tap.binaries(TYPE.OPEN)).length).toBeGreaterThanOrEqual(1); + }, 30_000); + it("a 20 MiB PUT body arrives at the target byte for byte, and a 20 MiB response body comes back byte for byte", async () => { let received = ""; behavior = async (request) => { - received = digestOf(await readAll(request.body)); + received = digestOf(await readParts(request.body)); return new Response(patternStream(20 * MIB, 9)); }; - const { relay, workerId } = await startFleet(); + const { relay, taps, workerId } = await startFleet(); const response = await relay.relay( workerId, buildCall({ body: patternStream(20 * MIB, 5), method: "PUT" }), ); - const back = digestOf(await readAll(response.body)); + const back = digestOf(await readParts(response.body)); + const dataBytes = taps + .flatMap((tap) => tap.binaries(TYPE.DATA)) + .reduce((total, envelope) => total + envelope.payload.length, 0); expect(received).toBe(patternDigest(20 * MIB, 5)); expect(back).toBe(patternDigest(20 * MIB, 9)); + expect(dataBytes).toBeGreaterThanOrEqual(20 * MIB); }, 120_000); + it("an empty upload (0 bytes) reaches the target as an empty body, and a GET relays as before", async () => { + const lengths: number[] = []; + behavior = async (request) => { + lengths.push((await request.arrayBuffer()).byteLength); + return new Response("fine"); + }; + const { relay, workerId } = await startFleet(); + + const put = await relay.relay( + workerId, + buildCall({ body: patternStream(0, 1), method: "PUT" }), + ); + const get = await relay.relay(workerId, buildCall({})); + + expect(await put.text()).toBe("fine"); + expect(await get.text()).toBe("fine"); + expect(lengths).toEqual([0, 0]); + }, 30_000); + it("while a 20 MiB relay runs, a lease.renew forwarded to the same worker answers", async () => { const midway = gate(); let finished = false; @@ -317,7 +352,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { buildCall({ body: patternStream(20 * MIB, 5), method: "PUT" }), ); await midway.promise; - const renewed = await settle( + const renewed = await settleWithin( gateway.dispatch("lease.renew", { leaseId: grant.lease.id }, agent()), 10_000, ); @@ -376,39 +411,13 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(output.join("")).toBe("e1e2"); }, 30_000); - it("the gateway never has more than 4 relay.body calls unanswered, checked with a target that reads its body slowly", async () => { - behavior = async (request) => { - const reader = request.body?.getReader(); - for (;;) { - const step = await reader?.read(); - if (step === undefined || step.done) break; - await sleep(25); - } - return new Response("read it all"); - }; - const { relay, spy } = await startPair(); - - const response = await relay.relay( - WORKER_ID, - buildCall({ - body: patternStream(12 * 256 * KIB, 2, { pieceSize: 256 * KIB }), - method: "PUT", - }), - ); - await response.text(); - - expect(spy.bodyCalls).toBeGreaterThan(4); - expect(spy.maxUnanswered).toBeGreaterThanOrEqual(2); - expect(spy.maxUnanswered).toBeLessThanOrEqual(4); - }, 30_000); - - it("a target that answers 401 without reading its body: the caller gets the 401, every relay.body is answered, and the gateway stops reading the caller's body", async () => { + it("a target that answers 401 without reading its 20 MiB upload: the caller gets the 401 and its body, and the gateway stops reading the caller's body", async () => { behavior = async () => { - // why: the 401 comes after the gateway has filled its window, so relay.body calls are pending when the relay settles + // why: the 401 comes after the upload has begun, so the gateway is reading the caller's body when the target answers await sleep(300); return new Response("nope", { status: 401 }); }; - const { relay, spy } = await startPair(); + const { relay } = await startPair(); let pulls = 0; let cancelled = false; const body = new ReadableStream({ @@ -431,11 +440,9 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(response.status).toBe(401); expect(text).toBe("nope"); - expect(spy.maxUnanswered).toBeGreaterThanOrEqual(1); expect(pulls).toBe(pullsAfterAnswer); expect(pulls).toBeLessThan(100); expect(cancelled).toBe(true); - expect(spy.unanswered).toBe(0); }, 30_000); it("a response the target streams in parts reaches the gateway caller part by part, before the target's body ends", async () => { @@ -463,9 +470,9 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { const response = await relay.relay(WORKER_ID, buildCall({})); const reader = response.body?.getReader(); - const first = await settle(reader?.read() ?? Promise.reject(new Error("no body")), 3_000); + const first = await settleWithin(reader?.read() ?? Promise.reject(new Error("no body")), 3_000); second.open(); - const rest = await settle(reader?.read() ?? Promise.reject(new Error("no body")), 3_000); + const rest = await settleWithin(reader?.read() ?? Promise.reject(new Error("no body")), 3_000); expect( first.state === "fulfilled" ? new TextDecoder().decode(first.value.value) : first.state, @@ -493,16 +500,17 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { }, ); - it("a caller that reads nothing while the target streams 80 MiB slowly gets its body stream errored, with a message saying the reader fell behind, once 64 MiB is buffered, and the target's request signal aborts before it has sent all 80 MiB", async () => { + it("a caller that reads nothing slows only its own transfer: another relay to the same worker completes while the first's response is unread, and the target has not sent all 80 MiB", async () => { let sent = 0; - let signal: AbortSignal | undefined; behavior = (request) => { - signal = request.signal; + if (new URL(request.url).searchParams.get("slow") === null) { + return Promise.resolve(new Response("quick")); + } return Promise.resolve( new Response( new ReadableStream({ async pull(controller) { - await sleep(20); + await sleep(5); controller.enqueue(patternBytes(MIB, 6, sent)); sent += MIB; if (sent >= 80 * MIB) controller.close(); @@ -513,15 +521,19 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { }; const { relay } = await startPair(); - const response = await relay.relay(WORKER_ID, buildCall({})); - await poll(() => signal?.aborted, 15_000).toBe(true); - const read = await settle( - response.body?.getReader().read() ?? Promise.reject(new Error("no body")), + const slow = await relay.relay( + WORKER_ID, + buildCall({ url: "http://gateway.test:4321/agent-device/rpc?slow=1" }), + ); + await sleep(500); + const quick = await settleWithin( + relay.relay(WORKER_ID, buildCall({})).then((response) => response.text()), + 5_000, ); + expect(quick).toEqual({ state: "fulfilled", value: "quick" }); expect(sent).toBeLessThan(80 * MIB); - expect(read).toMatchObject({ state: "rejected" }); - expect(read.state === "rejected" ? read.message : "").toMatch(/fell behind/); + expect(slow.status).toBe(200); }, 60_000); it("aborting the caller's request signal before the head comes fails the call; after it, it errors the caller's body stream; either way the target's request signal aborts and relay.request answers { cancelled: true } with no push after the cancel", async () => { @@ -534,7 +546,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { const before = await startPair(); const controller = new AbortController(); const pendingBefore = before.relay.relay(WORKER_ID, buildCall({ signal: controller.signal })); - const settledBefore = settle(pendingBefore); + const settledBefore = settleWithin(pendingBefore); await poll(() => signal !== undefined).toBe(true); controller.abort(new Error("caller left before the head")); const failure = await settledBefore; @@ -566,7 +578,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { const reader = response.body?.getReader(); await reader?.read(); secondController.abort(new Error("caller left after the head")); - const bodyFailure = await settle( + const bodyFailure = await settleWithin( (async () => { for (;;) { const step = await reader?.read(); @@ -593,7 +605,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { let signal: AbortSignal | undefined; behavior = async (request) => { signal = request.signal; - await readAll(request.body).catch(() => undefined); + await readParts(request.body).catch(() => undefined); await aborted(request.signal); return new Response("late"); }; @@ -607,7 +619,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { }, }); - const outcome = await settle(relay.relay(WORKER_ID, buildCall({ body, method: "PUT" }))); + const outcome = await settleWithin(relay.relay(WORKER_ID, buildCall({ body, method: "PUT" }))); expect(outcome).toMatchObject({ message: "upload broke", state: "rejected" }); await poll(() => signal?.aborted).toBe(true); @@ -621,7 +633,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { return new Response("late"); }; const never = await startPair({ deadlineMs: 200 }); - const noHead = await settle(never.relay.relay(WORKER_ID, buildCall({}))); + const noHead = await settleWithin(never.relay.relay(WORKER_ID, buildCall({}))); await poll(() => signal?.aborted).toBe(true); behavior = () => @@ -638,7 +650,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { const response = await stalling.relay.relay(WORKER_ID, buildCall({})); const reader = response.body?.getReader(); await reader?.read(); - const stalled = await settle(reader?.read() ?? Promise.reject(new Error("no body"))); + const stalled = await settleWithin(reader?.read() ?? Promise.reject(new Error("no body"))); const message = `worker ${WORKER_ID} did not finish the relayed request within 200 ms`; expect(noHead).toMatchObject({ code: "WORKER_UNREACHABLE", message, state: "rejected" }); @@ -653,9 +665,9 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { return new Response("late"); }; const before = await startPair(); - const noHead = settle(before.relay.relay(WORKER_ID, buildCall({}))); + const noHead = settleWithin(before.relay.relay(WORKER_ID, buildCall({}))); await poll(() => signal !== undefined).toBe(true); - await before.gatewayEnd.close(); + await before.pair.gatewayEnd.close(); const noHeadOutcome = await noHead; await poll(() => signal?.aborted).toBe(true); @@ -676,8 +688,8 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { const response = await after.relay.relay(WORKER_ID, buildCall({})); const reader = response.body?.getReader(); await reader?.read(); - await after.gatewayEnd.close(); - const bodyOutcome = await settle(reader?.read() ?? Promise.reject(new Error("no body"))); + await after.pair.gatewayEnd.close(); + const bodyOutcome = await settleWithin(reader?.read() ?? Promise.reject(new Error("no body"))); expect(noHeadOutcome).toMatchObject({ code: "WORKER_UNREACHABLE", state: "rejected" }); expect(bodyOutcome).toMatchObject({ code: "WORKER_UNREACHABLE", state: "rejected" }); @@ -687,7 +699,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { it("a relay to a worker with no uplink fails with WORKER_UNREACHABLE and the target sees nothing", async () => { const { relay } = await startPair(); - const outcome = await settle(relay.relay("wrk_nobody", buildCall({}))); + const outcome = await settleWithin(relay.relay("wrk_nobody", buildCall({}))); await sleep(100); expect(outcome).toMatchObject({ code: "WORKER_UNREACHABLE", state: "rejected" }); @@ -697,7 +709,7 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { it("a relay naming a target nobody registered fails with RELAY_TARGET_MISSING", async () => { const { relay } = await startPair(); - const outcome = await settle(relay.relay(WORKER_ID, buildCall({ target: "nobody" }))); + const outcome = await settleWithin(relay.relay(WORKER_ID, buildCall({ target: "nobody" }))); expect(outcome).toMatchObject({ code: "RELAY_TARGET_MISSING", state: "rejected" }); expect(targetCalls).toEqual([]); @@ -737,27 +749,192 @@ describe("a gateway relaying to a worker", { timeout: 15_000 }, () => { expect(response.headers.get("connection")).toBeNull(); }); - it("the gateway's 9th relay to one worker starts only after one of 8 ends", async () => { + it("with 63 relays to one worker held in their targets, a 64th starts at once", async () => { const release = gate(); behavior = async () => { await release.promise; return new Response("ok"); }; - const { relay } = await startPair(); + const { opened, relay } = await startPair(); + + const calls = Array.from({ length: 64 }, () => + settleWithin(relay.relay(WORKER_ID, buildCall({})), 20_000), + ); + await poll(() => targetCalls.length, 10_000).toBe(64); + const channels = opened(); + release.open(); + await Promise.all(calls); + + expect(channels).toBe(64); + }, 60_000); + + it("a 65th relay to one worker starts once one of 64 ends, and not before", async () => { + const releases: (() => void)[] = []; + behavior = async () => { + const held = gate(); + releases.push(held.open); + await held.promise; + return new Response("ok"); + }; + const { opened, relay } = await startPair(); - const calls = Array.from({ length: 9 }, () => - settle(relay.relay(WORKER_ID, buildCall({})), 10_000), + const calls = Array.from({ length: 65 }, () => + settleWithin(relay.relay(WORKER_ID, buildCall({})), 20_000), ); - await poll(() => targetCalls.length).toBe(8); + await poll(() => targetCalls.length, 10_000).toBe(64); await sleep(200); const startedBeforeRelease = targetCalls.length; - release.open(); + releases[0]?.(); + await poll(() => targetCalls.length, 10_000).toBe(65); + for (const release of releases) release(); const outcomes = await Promise.all(calls); - expect(startedBeforeRelease).toBe(8); - expect(targetCalls).toHaveLength(9); + expect(startedBeforeRelease).toBe(64); + expect(opened()).toBe(65); expect(outcomes.map((outcome) => outcome.state)).toEqual( - Array.from({ length: 9 }, () => "fulfilled"), + Array.from({ length: 65 }, () => "fulfilled"), ); - }, 30_000); + }, 60_000); + + it("a 65th relay whose 200 ms deadline passes first fails WORKER_UNREACHABLE with the deadline message, and its target is never called", async () => { + const release = gate(); + behavior = async () => { + await release.promise; + return new Response("ok"); + }; + const { makeRelay } = await startPair(); + const long = makeRelay(); + const short = makeRelay({ deadlineMs: 200 }); + const holders = Array.from({ length: 64 }, () => + settleWithin(long.relay(WORKER_ID, buildCall({})), 20_000), + ); + await poll(() => targetCalls.length, 10_000).toBe(64); + + const outcome = await settleWithin(short.relay(WORKER_ID, buildCall({}))); + release.open(); + await Promise.all(holders); + + expect(outcome).toEqual({ + code: "WORKER_UNREACHABLE", + message: `worker ${WORKER_ID} did not finish the relayed request within 200 ms`, + state: "rejected", + }); + expect(targetCalls).toHaveLength(64); + }, 60_000); + + it("a 65th relay whose caller aborts while it waits for a channel fails at once with the abort reason", async () => { + const release = gate(); + behavior = async () => { + await release.promise; + return new Response("ok"); + }; + const { relay } = await startPair(); + const holders = Array.from({ length: 64 }, () => + settleWithin(relay.relay(WORKER_ID, buildCall({})), 20_000), + ); + await poll(() => targetCalls.length, 10_000).toBe(64); + const controller = new AbortController(); + const waiting = settleWithin( + relay.relay(WORKER_ID, buildCall({ signal: controller.signal })), + 3_000, + ); + await sleep(100); + + controller.abort(new Error("caller left while waiting")); + const outcome = await waiting; + release.open(); + await Promise.all(holders); + + expect(outcome).toMatchObject({ message: "caller left while waiting", state: "rejected" }); + expect(targetCalls).toHaveLength(64); + }, 60_000); + + const leaving: readonly { + readonly name: string; + readonly run: ( + relay: GatewayRelay, + makeRelay: (o?: { deadlineMs?: number }) => GatewayRelay, + ) => Promise; + }[] = [ + { + name: "were cancelled", + run: async (relay) => { + const controller = new AbortController(); + const pending = settleWithin( + relay.relay(WORKER_ID, buildCall({ signal: controller.signal })), + ); + await sleep(20); + controller.abort(new Error("cancelled")); + return pending; + }, + }, + { + name: "timed out", + run: (_relay, makeRelay) => + settleWithin(makeRelay({ deadlineMs: 100 }).relay(WORKER_ID, buildCall({}))), + }, + { + name: "failed with a missing target", + run: (relay) => settleWithin(relay.relay(WORKER_ID, buildCall({ target: "nobody" }))), + }, + { + name: "had a target that answered without reading its upload", + run: async (relay) => { + const response = await relay.relay( + WORKER_ID, + buildCall({ body: patternStream(MIB, 3), method: "PUT" }), + ); + return settleWithin(response.text()); + }, + }, + ]; + + it.each(leaving)( + "after 64 relays to one worker that $name, a 65th starts at once", + async ({ run }) => { + const held = gate(); + behavior = async (request) => { + if (request.headers.get("x-marker") === "last") { + await held.promise; + return new Response("last"); + } + if (request.method === "PUT") return new Response("not reading"); + await aborted(request.signal); + return new Response("late"); + }; + const { makeRelay, opened, relay } = await startPair(); + + for (let batch = 0; batch < 4; batch += 1) { + await Promise.all(Array.from({ length: 16 }, () => run(relay, makeRelay))); + } + const last = settleWithin( + relay.relay(WORKER_ID, buildCall({ headers: { "x-marker": "last" } })), + 10_000, + ); + await poll(() => targetCalls.some((call) => call.headers.get("x-marker") === "last")).toBe( + true, + ); + const channels = opened(); + held.open(); + await last; + + expect(channels).toBe(65); + }, + 60_000, + ); + + it("with the worker's transport held so the {} answer overtakes a 20 MiB response, the caller still gets every byte, and its body ends only at the channel's end", async () => { + behavior = () => Promise.resolve(new Response(patternStream(20 * MIB, 9))); + const { pair, relay, spy } = await startPair(); + pair.workerEnd.hold(); + + const pending = relay.relay(WORKER_ID, buildCall({})); + await sleep(300); + pair.workerEnd.release(); + const response = await pending; + const digest = digestOf(await readParts(response.body)); + + expect(digest).toBe(patternDigest(20 * MIB, 9)); + expect(spy.events).toContain("request-answered:{}"); + }, 60_000); }); diff --git a/src/daemon/relay-worker.e2e.test.ts b/src/daemon/relay-worker.e2e.test.ts index 83ebb49fa..27a6de1e4 100644 --- a/src/daemon/relay-worker.e2e.test.ts +++ b/src/daemon/relay-worker.e2e.test.ts @@ -1,15 +1,13 @@ import { afterEach, describe, expect, it } from "vitest"; +import { creditEnvelope } from "../link/testing.js"; import type { DaemonServer } from "./server.js"; import type { RelayTarget } from "./relay.js"; -import type { SimlockWire } from "../simlock-client/wire.js"; import { adminSession, aborted, - base64Of, cleanUp, gate, - KIB, MIB, openRelay, openUplink, @@ -17,10 +15,12 @@ import { patternDigest, digestOf, patternStream, + readParts, relayInput, - settle, + settleWithin, sleep, startWorker, + type Uplink, type WorkerFixture, } from "./test-relay-support.js"; @@ -31,12 +31,12 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => const directories: string[] = []; let behavior: RelayTarget = () => Promise.resolve(new Response("ok")); let fixture: WorkerFixture; - let wire: SimlockWire; + let uplink: Uplink; async function start(): Promise { const target: RelayTarget = (request, tenant, leaseId) => behavior(request, tenant, leaseId); fixture = await startWorker(directories, daemons, { "agent-device": target, echo: target }); - ({ wire } = await openUplink(fixture.worker)); + uplink = await openUplink(fixture.worker); } afterEach(async () => { @@ -53,22 +53,65 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => return dispatch(operation, input, adminSession); } - it("sends a 20 MiB response body in relay-chunk pushes of at most 256 KiB, byte for byte", async () => { + it("sends a 20 MiB response body on the channel byte for byte, then ends it, and answers relay.request {}", async () => { behavior = () => Promise.resolve(new Response(patternStream(20 * MIB, 7))); await start(); - const relay = openRelay(wire, relayInput()); - const outcome = await settle(relay.result, 30_000); + const relay = await openRelay(uplink, relayInput()); + const body = await relay.body(30_000); + const outcome = await settleWithin(relay.result, 30_000); expect(outcome).toEqual({ state: "fulfilled", value: {} }); expect(relay.heads).toHaveLength(1); - const pieces = relay.bytes(); - expect(Math.max(...pieces.map((piece) => piece.length))).toBeLessThanOrEqual(256 * KIB); - expect(pieces.length).toBeGreaterThanOrEqual(80); - expect(digestOf(pieces)).toBe(patternDigest(20 * MIB, 7)); + expect(body.state === "fulfilled" ? digestOf([body.value]) : body.state).toBe( + patternDigest(20 * MIB, 7), + ); }, 60_000); - it("sends no relay-chunk for a 204, 205 or 304 answer or a HEAD answer", async () => { + it("hands the target a 2 MiB request body read from the channel, byte for byte", async () => { + let received = ""; + let length = 0; + behavior = async (request) => { + const parts = await readParts(request.body); + received = digestOf(parts); + length = parts.reduce((total, part) => total + part.length, 0); + return new Response("got it"); + }; + await start(); + + const relay = await openRelay(uplink, relayInput({ hasBody: true, method: "PUT" }), { + upload: patternBytes(2 * MIB, 3), + }); + const outcome = await settleWithin(relay.result); + + expect(outcome).toEqual({ state: "fulfilled", value: {} }); + expect(length).toBe(2 * MIB); + expect(received).toBe(digestOf([patternBytes(2 * MIB, 3)])); + }); + + it("answers an empty upload (0 bytes) and a GET with the target's response on the channel", async () => { + let seen = -1; + behavior = async (request) => { + seen = (await request.arrayBuffer()).byteLength; + return new Response("fine"); + }; + await start(); + + const empty = await openRelay(uplink, relayInput({ hasBody: true, method: "PUT" }), { + upload: new Uint8Array(0), + }); + const emptyBody = await empty.body(); + const get = await openRelay(uplink, relayInput()); + const getBody = await get.body(); + + expect(seen).toBe(0); + expect(emptyBody.state === "fulfilled" ? Buffer.from(emptyBody.value).toString() : "").toBe( + "fine", + ); + expect(getBody.state === "fulfilled" ? Buffer.from(getBody.value).toString() : "").toBe("fine"); + }); + + it("sends no response bytes for a 204, 205 or 304 answer or a HEAD answer, and ends the channel", async () => { await start(); const cases: { readonly status: number; @@ -80,25 +123,30 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => { body: null, method: "GET", status: 304 }, { body: "not sent for a HEAD", method: "HEAD", status: 200 }, ]; - const seen: { status: number | undefined; chunks: number; result: unknown }[] = []; + const seen: { status: number | undefined; bytes: number | string; result: unknown }[] = []; for (const entry of cases) { behavior = () => Promise.resolve(new Response(entry.body, { status: entry.status })); - const relay = openRelay(wire, relayInput({ method: entry.method })); - const outcome = await settle(relay.result); - seen.push({ chunks: relay.chunks.length, result: outcome, status: relay.heads[0]?.status }); + const relay = await openRelay(uplink, relayInput({ method: entry.method })); + const body = await relay.body(); + const outcome = await settleWithin(relay.result); + seen.push({ + bytes: body.state === "fulfilled" ? body.value.length : body.state, + result: outcome, + status: relay.heads[0]?.status, + }); } expect(seen).toEqual( cases.map((entry) => ({ - chunks: 0, + bytes: 0, result: { state: "fulfilled", value: {} }, status: entry.status, })), ); }); - it("aborts the target's request on relay.cancel, answers relay.request { cancelled: true } and sends no push after the cancel", async () => { + it("aborts the target's request on relay.cancel, answers relay.request { cancelled: true }, and aborts the channel", async () => { let signal: AbortSignal | undefined; behavior = (request) => { signal = request.signal; @@ -111,21 +159,22 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => return Promise.resolve(new Response(body)); }; await start(); - const relay = openRelay(wire, relayInput()); - await poll(() => relay.chunks.length).toBeGreaterThan(1); + const relay = await openRelay(uplink, relayInput()); + await poll(() => relay.heads.length).toBe(1); - const cancelled = await settle(wire.call("relay.cancel", { relayId: relay.relayId })); - const chunksAtCancel = relay.chunks.length; - const result = await settle(relay.result); - await sleep(150); + const cancelled = await settleWithin( + uplink.wire.call("relay.cancel", { relayId: relay.relayId }), + ); + const result = await settleWithin(relay.result); + const read = await relay.readError(); expect(cancelled).toEqual({ state: "fulfilled", value: {} }); expect(result).toEqual({ state: "fulfilled", value: { cancelled: true } }); expect(signal?.aborted).toBe(true); - expect(relay.chunks.length).toBe(chunksAtCancel); + expect(read).toEqual({ ended: false, reason: "aborted" }); }); - it("answers relay.request { cancelled: true } to a cancel that comes before the target answers", async () => { + it("answers relay.request { cancelled: true } to a cancel that comes before the target answers, and aborts the channel", async () => { let signal: AbortSignal | undefined; behavior = async (request) => { signal = request.signal; @@ -133,15 +182,17 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => return new Response("late"); }; await start(); - const relay = openRelay(wire, relayInput()); + const relay = await openRelay(uplink, relayInput()); await poll(() => signal !== undefined).toBe(true); - await wire.call("relay.cancel", { relayId: relay.relayId }); - const result = await settle(relay.result); + await uplink.wire.call("relay.cancel", { relayId: relay.relayId }); + const result = await settleWithin(relay.result); + const read = await relay.readError(); expect(result).toEqual({ state: "fulfilled", value: { cancelled: true } }); expect(signal?.aborted).toBe(true); expect(relay.heads).toEqual([]); + expect(read).toEqual({ ended: false, reason: "aborted" }); }); it("aborts the target's request when the connection the relay came on closes", async () => { @@ -152,34 +203,70 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => return new Response("late"); }; await start(); - const { wire: second, gatewayEnd } = await openUplink(fixture.worker); - const relay = openRelay(second, relayInput()); + const second = await openUplink(fixture.worker); + const relay = await openRelay(second, relayInput()); await poll(() => signal !== undefined).toBe(true); - await gatewayEnd.close(); + await second.pair.gatewayEnd.close(); await poll(() => signal?.aborted).toBe(true); - await settle(relay.result, 200); + await settleWithin(relay.result, 200); + }); + + it("aborts the target's request and answers { cancelled: true } when the gateway aborts the channel", async () => { + let signal: AbortSignal | undefined; + behavior = async (request) => { + signal = request.signal; + await aborted(request.signal); + return new Response("late"); + }; + await start(); + const relay = await openRelay(uplink, relayInput(), { keepOpen: true }); + await poll(() => signal !== undefined).toBe(true); + + relay.channel.abort("caller left"); + const result = await settleWithin(relay.result); + + expect(signal?.aborted).toBe(true); + expect(result).toEqual({ state: "fulfilled", value: { cancelled: true } }); + }); + + it("fails relay.request BAD_REQUEST and aborts the target's request when the gateway breaks a link rule on the relay's channel", async () => { + let signal: AbortSignal | undefined; + behavior = async (request) => { + signal = request.signal; + await aborted(request.signal); + return new Response("late"); + }; + await start(); + const relay = await openRelay(uplink, relayInput(), { keepOpen: true }); + await poll(() => signal !== undefined).toBe(true); + + // why: the first channel the gateway end opens is number 2; a CREDIT of 0 breaks the link's rule. + await uplink.pair.gatewayEnd.writeBinary(creditEnvelope(2, 0)); + const result = await settleWithin(relay.result); + + expect(signal?.aborted).toBe(true); + expect(result).toMatchObject({ code: "BAD_REQUEST", state: "rejected" }); }); - it("answers relay.request, relay.body and relay.cancel FORBIDDEN from an admin session that is not the gateway's uplink", async () => { + it("answers relay.request and relay.cancel FORBIDDEN from an admin session that is not the gateway's uplink", async () => { await start(); const attempts = [ - ["relay.request", relayInput()], - ["relay.body", { end: true, relayId: "relay-x" }], + ["relay.request", relayInput({ channel: "chan-1" })], ["relay.cancel", { relayId: "relay-x" }], ] as const; const codes: unknown[] = []; for (const [operation, input] of attempts) { - const outcome = await settle(callAsAdmin(operation, input)); + const outcome = await settleWithin(callAsAdmin(operation, input)); codes.push(outcome.state === "rejected" ? outcome.code : outcome.state); } - expect(codes).toEqual(["FORBIDDEN", "FORBIDDEN", "FORBIDDEN"]); + expect(codes).toEqual(["FORBIDDEN", "FORBIDDEN"]); }); - it("fails a relay.request that reuses an active relayId with BAD_REQUEST, answers {} to a relay.body for an unknown relay id, and {} to a relay.cancel for an unknown relay id", async () => { + it("fails a relay.request that reuses an active relayId with BAD_REQUEST and its channel errored aborted, leaves the first relay running, and answers {} to a relay.cancel for an unknown relay id", async () => { const release = gate(); behavior = async () => { await release.promise; @@ -187,91 +274,60 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => }; await start(); const input = relayInput(); - const first = openRelay(wire, input); - await poll(async () => (await settle(first.result, 20)).state).toBe("pending"); - - const reused = await settle(wire.call("relay.request", { ...input })); - const unknownBody = await settle( - wire.call("relay.body", { - relayId: "relay-unknown", - chunk: base64Of(patternBytes(8)), - seq: 0, - }), + const first = await openRelay(uplink, input); + await poll(async () => (await settleWithin(first.result, 20)).state).toBe("pending"); + + const second = await openRelay(uplink, { ...input }); + const reused = await settleWithin(second.result); + const unknownCancel = await settleWithin( + uplink.wire.call("relay.cancel", { relayId: "relay-unknown" }), ); - const unknownCancel = await settle(wire.call("relay.cancel", { relayId: "relay-unknown" })); + const reusedEnd = await second.readError(); release.open(); expect(reused).toMatchObject({ code: "BAD_REQUEST", state: "rejected" }); - expect(unknownBody).toEqual({ state: "fulfilled", value: {} }); + expect(reusedEnd).toEqual({ ended: false, reason: "aborted" }); expect(unknownCancel).toEqual({ state: "fulfilled", value: {} }); - expect(await settle(first.result)).toEqual({ state: "fulfilled", value: {} }); + expect(await settleWithin(first.result)).toEqual({ state: "fulfilled", value: {} }); }); it.each([ - { - name: "a seq out of order", - steps: [{ seq: 1 }], - }, - { - name: "a repeated seq", - steps: [{ seq: 0 }, { seq: 0 }], - }, - { - name: "a chunk after end", - steps: [{ seq: 0 }, { end: true }, { seq: 1 }], - }, + { channelName: "never-opened-by-gateway", name: "a channel the gateway never opened" }, + { channelName: "", name: "an empty channel" }, + { channelName: "c".repeat(33), name: "a 33-character channel" }, + { channelName: "bad channel!", name: "a channel with a character outside [A-Za-z0-9-]" }, + { channelName: null, name: "no channel" }, ])( - "fails a relay.body with $name with BAD_REQUEST and aborts the target's request", - async ({ steps }) => { - let signal: AbortSignal | undefined; - behavior = async (request) => { - signal = request.signal; - await aborted(request.signal); - return new Response("late"); - }; + "fails a relay.request naming $name with BAD_REQUEST, and one naming a channel the gateway opened succeeds", + async ({ channelName }) => { await start(); - const relayId = String(relayInput().relayId); - const relay = openRelay(wire, relayInput({ hasBody: true, method: "PUT", relayId })); - await poll(() => signal !== undefined).toBe(true); - - const outcomes: unknown[] = []; - for (const step of steps) { - const payload = - "end" in step - ? { end: true, relayId } - : { chunk: base64Of(patternBytes(16)), relayId, seq: step.seq }; - const outcome = await settle(wire.call("relay.body", payload)); - outcomes.push(outcome.state === "rejected" ? outcome.code : outcome.state); - } - expect(outcomes.slice(0, -1).every((outcome) => outcome === "fulfilled")).toBe(true); - expect(outcomes.at(-1)).toBe("BAD_REQUEST"); - await poll(() => signal?.aborted).toBe(true); - await settle(relay.result, 200); + const accepted = await openRelay(uplink, relayInput()); + const acceptedOutcome = await settleWithin(accepted.result); + const refused = await openRelay(uplink, relayInput(), { channelName }); + const refusedOutcome = await settleWithin(refused.result); + + expect(acceptedOutcome).toEqual({ state: "fulfilled", value: {} }); + expect(refusedOutcome).toMatchObject({ code: "BAD_REQUEST", state: "rejected" }); }, ); - it("fails any relay.body for a relay opened with hasBody false with BAD_REQUEST and aborts the target's request", async () => { - let signal: AbortSignal | undefined; - behavior = async (request) => { - signal = request.signal; - await aborted(request.signal); - return new Response("late"); + it("fails a relay.request naming a channel an earlier relay.request already accepted with BAD_REQUEST", async () => { + const release = gate(); + behavior = async () => { + await release.promise; + return new Response("ok"); }; await start(); - const relay = openRelay(wire, relayInput({ hasBody: false })); - await poll(() => signal !== undefined).toBe(true); + const first = await openRelay(uplink, relayInput(), { keepOpen: true }); + await poll(async () => (await settleWithin(first.result, 20)).state).toBe("pending"); - const outcome = await settle( - wire.call("relay.body", { - chunk: base64Of(patternBytes(16)), - relayId: relay.relayId, - seq: 0, - }), - ); + const again = await openRelay(uplink, relayInput(), { channelName: first.channel.id }); + const outcome = await settleWithin(again.result); + release.open(); expect(outcome).toMatchObject({ code: "BAD_REQUEST", state: "rejected" }); - await poll(() => signal?.aborted).toBe(true); + first.channel.abort("done"); }); const longName = (length: number): string => "x".repeat(length); @@ -357,8 +413,8 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => async ({ atLimit, pastLimit }) => { await start(); - const within = await settle(openRelay(wire, relayInput(atLimit)).result); - const past = await settle(openRelay(wire, relayInput(pastLimit)).result); + const within = await settleWithin((await openRelay(uplink, relayInput(atLimit))).result); + const past = await settleWithin((await openRelay(uplink, relayInput(pastLimit))).result); expect(within).toEqual({ state: "fulfilled", value: {} }); expect(past).toMatchObject({ code: "BAD_REQUEST", state: "rejected" }); @@ -367,44 +423,69 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => }, ); - it("fails a relay.body chunk that is not standard base64, and one that decodes to 262 145 bytes, with BAD_REQUEST", async () => { - const release = gate(); - behavior = async () => { - await release.promise; - return new Response("ok"); - }; - await start(); - const relay = openRelay(wire, relayInput({ hasBody: true, method: "PUT" })); - const send = (seq: number, chunk: string) => - settle(wire.call("relay.body", { chunk, relayId: relay.relayId, seq })); - - const atLimit = await send(0, base64Of(patternBytes(262_144))); - const urlSafe = await send(1, "_-_-"); - const tooLong = await send(1, base64Of(patternBytes(262_145))); - release.open(); - - expect(atLimit).toEqual({ state: "fulfilled", value: {} }); - expect(urlSafe).toMatchObject({ code: "BAD_REQUEST", state: "rejected" }); - expect(tooLong).toMatchObject({ code: "BAD_REQUEST", state: "rejected" }); - }); + const failures: readonly { + readonly name: string; + readonly target?: RelayTarget; + readonly input?: Record; + readonly code: string; + }[] = [ + { code: "BAD_REQUEST", input: { method: "TRACE" }, name: "fails on its schema" }, + { code: "RELAY_TARGET_MISSING", input: { target: "nobody" }, name: "names a missing target" }, + { + code: "INTERNAL", + name: "meets a target error", + target: () => Promise.reject(new Error("target exploded")), + }, + { + code: "INTERNAL", + name: "meets target headers out of bounds", + target: () => + Promise.resolve( + new Response("ok", { + headers: Array.from( + { length: 101 }, + (_unused, index) => [`x-h-${String(index)}`, "v"] as [string, string], + ), + }), + ), + }, + { + code: "INTERNAL", + name: "has a response body that fails after the head", + target: () => { + let step = 0; + return Promise.resolve( + new Response( + new ReadableStream({ + pull(controller) { + step += 1; + if (step === 1) controller.enqueue(new TextEncoder().encode("abc")); + else controller.error(new Error("body broke")); + }, + }), + ), + ); + }, + }, + ]; - it("fails the 17th relay on one connection with BAD_REQUEST", async () => { - const release = gate(); - behavior = async () => { - await release.promise; - return new Response("ok"); - }; - await start(); - const sixteen = Array.from({ length: 16 }, () => openRelay(wire, relayInput())); - await sleep(100); + it.each(failures)( + "a relay.request that $name leaves the gateway's end of its channel errored aborted, while an accepted one ends it cleanly", + async ({ code, input, target }) => { + await start(); + const good = await openRelay(uplink, relayInput()); + const goodEnd = await good.readError(); + behavior = target ?? behavior; - const seventeenth = await settle(openRelay(wire, relayInput()).result); - release.open(); + const failing = await openRelay(uplink, relayInput(input ?? {})); + const outcome = await settleWithin(failing.result); + const end = await failing.readError(); - expect(seventeenth).toMatchObject({ code: "BAD_REQUEST", state: "rejected" }); - const first = await Promise.all(sixteen.map((relay) => settle(relay.result))); - expect(first.every((outcome) => outcome.state === "fulfilled")).toBe(true); - }); + expect(goodEnd).toEqual({ ended: true }); + expect(outcome).toMatchObject({ code, state: "rejected" }); + expect(end).toEqual({ ended: false, reason: "aborted" }); + }, + ); it("fails the call with INTERNAL and logs the bound when a target answers 101 headers", async () => { behavior = () => @@ -418,7 +499,7 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => ); await start(); - const outcome = await settle(openRelay(wire, relayInput()).result); + const outcome = await settleWithin((await openRelay(uplink, relayInput())).result); expect(outcome).toMatchObject({ code: "INTERNAL", state: "rejected" }); expect(fixture.logger.problems()).toContain("at most 100 headers, got"); @@ -428,71 +509,79 @@ describe("a worker's relay targets over its uplink", { timeout: 15_000 }, () => behavior = () => Promise.reject(new Error("target exploded: reason-4471")); await start(); - const outcome = await settle(openRelay(wire, relayInput()).result); + const outcome = await settleWithin((await openRelay(uplink, relayInput())).result); expect(outcome).toMatchObject({ code: "INTERNAL", state: "rejected" }); expect(fixture.logger.problems()).toContain("target exploded: reason-4471"); }); - it("fails the call with INTERNAL after the chunks already sent when a response body errors after the head", async () => { - behavior = () => { - let step = 0; - return Promise.resolve( - new Response( - new ReadableStream({ - pull(controller) { - step += 1; - if (step === 1) controller.enqueue(new TextEncoder().encode("abc")); - else controller.error(new Error("body broke")); - }, - }), - ), - ); - }; + it("stops the request direction when the target answers without reading its 20 MiB upload, so the gateway's writer errors stopped", async () => { + behavior = () => Promise.resolve(new Response("nope", { status: 401 })); await start(); + const relay = await openRelay(uplink, relayInput({ hasBody: true, method: "PUT" }), { + keepOpen: true, + }); + const writer = relay.channel.writable.getWriter(); + const pushed = (async () => { + try { + for (let offset = 0; offset < 20 * MIB; offset += MIB) { + await writer.write(patternBytes(MIB, 4, offset)); + } + await writer.close(); + return "wrote everything"; + } catch (error: unknown) { + return (error as { reason?: string }).reason ?? String(error); + } + })(); - const relay = openRelay(wire, relayInput()); - const outcome = await settle(relay.result); + const outcome = await settleWithin(pushed, 10_000); + const result = await settleWithin(relay.result); - expect(outcome).toMatchObject({ code: "INTERNAL", state: "rejected" }); - expect(relay.heads).toHaveLength(1); - expect(Buffer.concat(relay.bytes()).toString()).toBe("abc"); + expect(result).toEqual({ state: "fulfilled", value: {} }); + expect(outcome).toEqual({ state: "fulfilled", value: "stopped" }); }); - it("never drops a relay.body frame sent right behind its relay.request frame (seq 0 plus end, 50 times)", async () => { - behavior = async (request) => new Response(String((await request.arrayBuffer()).byteLength)); + it("errors a request body the target reads after it answered, rather than ending it as if the upload were complete", async () => { + let held: Request | undefined; + behavior = (request) => { + held = request; + return Promise.resolve(new Response("nope", { status: 401 })); + }; await start(); - const outcomes: unknown[] = []; - - for (let round = 0; round < 50; round += 1) { - const input = relayInput({ hasBody: true, method: "PUT" }); - const relayId = String(input.relayId); - const relay = openRelay(wire, input); - const first = wire.call("relay.body", { - chunk: base64Of(patternBytes(100)), - relayId, - seq: 0, - }); - const end = wire.call("relay.body", { end: true, relayId }); - const [result, firstAnswer, endAnswer] = await Promise.all([ - settle(relay.result, 2_000), - settle(first), - settle(end), - ]); - outcomes.push({ - body: Buffer.concat(relay.bytes()).toString(), - end: endAnswer, - first: firstAnswer, - result, - }); - } + const relay = await openRelay(uplink, relayInput({ hasBody: true, method: "PUT" }), { + keepOpen: true, + }); + const result = await settleWithin(relay.result); + + const late = held === undefined ? undefined : await settleWithin(held.text()); + + expect(result).toEqual({ state: "fulfilled", value: {} }); + expect(late).toMatchObject({ state: "rejected" }); + }); - const expected = { - body: "100", - end: { state: "fulfilled", value: {} }, - first: { state: "fulfilled", value: {} }, - result: { state: "fulfilled", value: {} }, + it("stops a hasBody false relay's request direction at once, so bytes the gateway still writes error its writer stopped", async () => { + const release = gate(); + behavior = async () => { + await release.promise; + return new Response("ok"); }; - expect(outcomes).toEqual(Array.from({ length: 50 }, () => expected)); - }, 60_000); + await start(); + const relay = await openRelay(uplink, relayInput({ hasBody: false }), { keepOpen: true }); + const writer = relay.channel.writable.getWriter(); + const pushed = (async () => { + try { + for (let offset = 0; offset < 8 * MIB; offset += MIB) { + await writer.write(patternBytes(MIB, 4, offset)); + } + return "wrote everything"; + } catch (error: unknown) { + return (error as { reason?: string }).reason ?? String(error); + } + })(); + + const outcome = await settleWithin(pushed, 10_000); + release.open(); + + expect(outcome).toEqual({ state: "fulfilled", value: "stopped" }); + }); }); diff --git a/src/daemon/relay.test.ts b/src/daemon/relay.test.ts index 63ed89da5..6e8e8e775 100644 --- a/src/daemon/relay.test.ts +++ b/src/daemon/relay.test.ts @@ -1,8 +1,11 @@ import { describe, expect, it } from "vitest"; +import { LinkChannelError, type LinkChannel } from "../link/index.js"; + import type { Logger } from "../ports/index.js"; +import { linkPair } from "../link/testing.js"; import { RelayConnection, type RelayPush, type RelayTarget } from "./relay.js"; -import { relayInput, settle } from "./test-relay-support.js"; +import { gate, relayInput, settleWithin } from "./test-relay-support.js"; const logger: Logger = { child: () => logger, @@ -14,6 +17,12 @@ const logger: Logger = { type Input = Parameters[0]; +async function acceptedChannel() { + const pair = linkPair(); + const opened = await pair.gateway.openChannel({ signal: new AbortController().signal }); + return pair.worker.acceptChannel(opened.id); +} + describe("a worker's relay connection", () => { it("answers { cancelled: true } and never runs the target for a request that arrives after the connection closed", async () => { let ran = false; @@ -22,10 +31,12 @@ describe("a worker's relay connection", () => { return Promise.resolve(new Response("late")); }; const relays = new RelayConnection({ echo: target }, logger); - const push: RelayPush = { chunk: () => Promise.resolve(), head: () => Promise.resolve() }; + const push: RelayPush = { head: () => Promise.resolve() }; relays.abortAll(); - const outcome = await settle(relays.request(relayInput() as Input, push)); + const outcome = await settleWithin( + relays.request(relayInput() as Input, push, await acceptedChannel()), + ); expect(outcome).toEqual({ state: "fulfilled", value: { cancelled: true } }); expect(ran).toBe(false); @@ -47,16 +58,69 @@ describe("a worker's relay connection", () => { const relays = new RelayConnection({ echo: target }, logger); const input = relayInput() as Input; const push: RelayPush = { - chunk: () => Promise.resolve(), head: () => { relays.cancel(input.relayId); return Promise.resolve(); }, }; - const outcome = await settle(relays.request(input, push)); + const outcome = await settleWithin(relays.request(input, push, await acceptedChannel())); expect(outcome).toEqual({ state: "fulfilled", value: { cancelled: true } }); expect(bodyCancelled).toBe(true); }); + + it("runs the target once and fails the second of two same-id requests BAD_REQUEST while the first waits for credit", async () => { + let runs = 0; + const target: RelayTarget = () => { + runs += 1; + return Promise.resolve(new Response("ok")); + }; + const relays = new RelayConnection({ echo: target }, logger); + const push: RelayPush = { head: () => Promise.resolve() }; + const input = relayInput() as Input; + const held = await acceptedChannel(); + const credit = gate(); + const first = relays.request( + input, + push, + Object.assign(Object.create(held) as LinkChannel, { whenCredit: () => credit.promise }), + ); + const second = await settleWithin(relays.request({ ...input }, push, await acceptedChannel())); + credit.open(); + await settleWithin(first); + + expect(second).toMatchObject({ code: "BAD_REQUEST", state: "rejected" }); + expect(runs).toBe(1); + }); + + it("aborts the target's request, aborts the channel and answers { cancelled: true } when the channel fails stalled", async () => { + let signal: AbortSignal | undefined; + const target: RelayTarget = (request) => { + signal = request.signal; + return request.arrayBuffer().then(() => new Response("never")); + }; + const relays = new RelayConnection({ echo: target }, logger); + const push: RelayPush = { head: () => Promise.resolve() }; + const held = await acceptedChannel(); + let aborts = 0; + const failing = new ReadableStream({ + pull: () => Promise.reject(new LinkChannelError("stalled")), + }); + const channel = Object.assign(Object.create(held) as LinkChannel, { + abort: () => { + aborts += 1; + }, + readable: failing, + whenCredit: () => Promise.resolve(), + }); + + const outcome = await settleWithin( + relays.request(relayInput({ hasBody: true, method: "PUT" }) as Input, push, channel), + ); + + expect(outcome).toEqual({ state: "fulfilled", value: { cancelled: true } }); + expect(signal?.aborted).toBe(true); + expect(aborts).toBeGreaterThan(0); + }); }); diff --git a/src/daemon/relay.ts b/src/daemon/relay.ts index fbfbc9b85..75d3ad574 100644 --- a/src/daemon/relay.ts +++ b/src/daemon/relay.ts @@ -6,13 +6,12 @@ import type { z } from "zod"; import { OPERATIONS, - RELAY_MAX_CHUNK_BYTES, RELAY_MAX_HEADERS, - RELAY_MAX_PUSH_BYTES, isRelayFramingHeader, relayHeaderPairs, relayHeadersSchema, } from "../contract/index.js"; +import { LinkChannelError, type LinkChannel } from "../link/index.js"; import type { Logger } from "../ports/index.js"; import { DispatchError } from "./dispatch.js"; @@ -25,90 +24,33 @@ export type RelayTarget = ( export type RelayTargets = Readonly>; type RelayRequestInput = z.infer<(typeof OPERATIONS)["relay.request"]["input"]>; -type RelayBodyInput = z.infer<(typeof OPERATIONS)["relay.body"]["input"]>; -// why: each call resolves once the frame is on the socket, so the relay reads its target only as fast as the socket drains. +// why: the call resolves once the frame is on the socket, so the relay writes the response body only after its head. export interface RelayPush { head(status: number, headers: readonly (readonly [string, string])[]): Promise; - chunk(base64: string): Promise; } -const MAX_ACTIVE_RELAYS = 16; +type RelayResult = { readonly cancelled?: true }; + const NO_BODY_STATUSES: ReadonlySet = new Set([204, 205, 304]); interface ActiveRelay { readonly controller: AbortController; - readonly feed: RelayBodyFeed | undefined; + readonly channel: LinkChannel; // why: the Request's signal follows ours through a weak reference, so a target that keeps only the signal would never see an abort once the Request is collected. request: Request | undefined; -} - -// why: a `relay.body` call is answered once the stream has handed its chunk to the target, which is what holds the gateway's sender back. - -class RelayBodyFeed { - readonly stream: ReadableStream; - readonly #queue: { readonly bytes: Uint8Array; readonly handed: () => void }[] = []; - #wake: (() => void) | undefined; - #nextSeq = 0; - #ended = false; - #aborted = false; - - constructor() { - this.stream = new ReadableStream({ - pull: async (controller) => { - while (this.#queue.length === 0 && !this.#ended && !this.#aborted) { - await new Promise((resolve) => { - this.#wake = resolve; - }); - } - const next = this.#queue.shift(); - if (next !== undefined) { - controller.enqueue(next.bytes); - next.handed(); - } else if (this.#aborted) { - controller.error(new Error("The relay ended before its body did")); - } else { - controller.close(); - } - }, - }); - } - - push(seq: number, bytes: Uint8Array): Promise { - if (this.#aborted) return Promise.resolve(); - if (this.#ended) throw new Error("A chunk arrived after the end of the body"); - if (seq !== this.#nextSeq) - throw new Error(`Expected chunk ${String(this.#nextSeq)}, got ${String(seq)}`); - this.#nextSeq += 1; - return new Promise((handed) => { - this.#queue.push({ bytes, handed }); - this.#signal(); - }); - } - - end(): void { - if (this.#aborted) return; - if (this.#ended) throw new Error("The body already ended"); - this.#ended = true; - this.#signal(); - } - - // why: a sender must never wait on a target that stopped reading. - abort(): void { - this.#aborted = true; - for (const item of this.#queue.splice(0)) item.handed(); - this.#signal(); - } - - #signal(): void { - const wake = this.#wake; - this.#wake = undefined; - wake?.(); - } + // why: the first failure the channel reports decides how the call answers (ADR 0028's failure table). + failure: unknown; + // why: set once the target has answered; what the target has not read of the request body is dropped from then on. + abandoned: boolean; + reader: ReadableStreamDefaultReader | undefined; + readonly writer: WritableStreamDefaultWriter; } export class RelayConnection { readonly #active = new Map(); + // why: an id is taken from the duplicate check until the call ends, so two lines with one id in one read cannot both run their target while the first waits for credit. + readonly #reserved = new Set(); #closed = false; constructor( @@ -116,18 +58,45 @@ export class RelayConnection { private readonly logger: Logger, ) {} - async request(input: RelayRequestInput, push: RelayPush): Promise<{ readonly cancelled?: true }> { + // why: every way the call fails or is cancelled aborts the channel it owns; only a `{}` answer leaves it to end on its own. + async request( + input: RelayRequestInput, + push: RelayPush, + channel: LinkChannel, + ): Promise { + try { + const result = await this.#request(input, push, channel); + if (result.cancelled === true) channel.abort(); + return result; + } catch (error: unknown) { + channel.abort(); + throw error; + } + } + + async #request( + input: RelayRequestInput, + push: RelayPush, + channel: LinkChannel, + ): Promise { // why: a request parked behind the startup gate reaches here after its connection closed; running its target would answer nobody. if (this.#closed) return { cancelled: true }; - if (this.#active.has(input.relayId)) { + if (this.#reserved.has(input.relayId)) { throw new DispatchError("BAD_REQUEST", `Relay ${input.relayId} is already active`); } - if (this.#active.size >= MAX_ACTIVE_RELAYS) { - throw new DispatchError( - "BAD_REQUEST", - `A connection holds at most ${String(MAX_ACTIVE_RELAYS)} active relays`, - ); + this.#reserved.add(input.relayId); + try { + return await this.#admitted(input, push, channel); + } finally { + this.#reserved.delete(input.relayId); } + } + + async #admitted( + input: RelayRequestInput, + push: RelayPush, + channel: LinkChannel, + ): Promise { const target = Object.hasOwn(this.targets, input.target) ? this.targets[input.target] : undefined; @@ -140,50 +109,84 @@ export class RelayConnection { }, ); } + // why: a channel that failed while the request waited for startup answers by the failure table without running its target. + try { + await channel.whenCredit(); + } catch (error: unknown) { + return this.#answerFailure(error); + } const controller = new AbortController(); - const feed = input.hasBody ? new RelayBodyFeed() : undefined; - const active: ActiveRelay = { controller, feed, request: undefined }; + const active: ActiveRelay = { + abandoned: false, + channel, + controller, + failure: undefined, + reader: undefined, + request: undefined, + writer: channel.writable.getWriter(), + }; + // why: the writable errors the moment the channel fails or the peer stops this direction, so a target that never reads its body still ends with its channel. + active.writer.closed.catch((error: unknown) => this.#note(active, error)); + controller.signal.addEventListener("abort", () => channel.abort(), { once: true }); this.#active.set(input.relayId, active); try { return await this.#run(input, target, active, push); } finally { - feed?.abort(); this.#active.delete(input.relayId); } } - // why: a relay the worker does not hold answers `{}`; the gateway learns the outcome from `relay.request`. - // fallow-ignore-next-line unused-class-member -- reached only through the dispatcher's session (`session.relays`), which the audit cannot follow. - body(input: RelayBodyInput): Promise { - const relay = this.#active.get(input.relayId); - if (relay === undefined) return Promise.resolve(); - try { - if (relay.feed === undefined) throw new Error("The relay was opened without a body"); - if ("end" in input) { - relay.feed.end(); - return Promise.resolve(); - } - const bytes = Buffer.from(input.chunk, "base64"); - if (bytes.length > RELAY_MAX_CHUNK_BYTES) { - throw new Error(`A chunk is at most ${String(RELAY_MAX_CHUNK_BYTES)} bytes`); - } - return relay.feed.push(input.seq, bytes); - } catch (violation: unknown) { - relay.controller.abort(); + cancel(relayId: string): void { + this.#active.get(relayId)?.controller.abort(); + } + + abortAll(): void { + this.#closed = true; + for (const relay of this.#active.values()) relay.controller.abort(); + } + + #note(active: ActiveRelay, error: unknown): void { + if (active.failure !== undefined || active.controller.signal.aborted) return; + active.failure = error; + active.controller.abort(); + } + + // why: a peer that broke a link rule is the one failure the worker reports to its caller; every other reason ends the call as a cancel. + #answerFailure(error: unknown): RelayResult { + if (error instanceof LinkChannelError && error.reason === "invalid") { throw new DispatchError( "BAD_REQUEST", - violation instanceof Error ? violation.message : String(violation), + `The relay's channel broke a link rule: ${error.message}`, ); } + return { cancelled: true }; } - cancel(relayId: string): void { - this.#active.get(relayId)?.controller.abort(); + #finished(active: ActiveRelay): RelayResult { + return active.failure === undefined ? { cancelled: true } : this.#answerFailure(active.failure); } - abortAll(): void { - this.#closed = true; - for (const relay of this.#active.values()) relay.controller.abort(); + #requestBody(active: ActiveRelay): ReadableStream { + const reader = active.channel.readable.getReader(); + active.reader = reader; + return new ReadableStream( + { + cancel: () => reader.cancel().catch(() => undefined), + pull: async (controller) => { + try { + const step = await reader.read(); + if (active.abandoned) { + controller.error(new Error("The relay answered before its request body ended")); + } else if (step.done) controller.close(); + else controller.enqueue(step.value); + } catch (error: unknown) { + this.#note(active, error); + controller.error(error); + } + }, + }, + { highWaterMark: 0 }, + ); } async #run( @@ -191,19 +194,22 @@ export class RelayConnection { target: RelayTarget, active: ActiveRelay, push: RelayPush, - ): Promise<{ readonly cancelled?: true }> { - const { controller, feed } = active; + ): Promise { + const { controller } = active; const { signal } = controller; const cancelled = new Promise<"cancelled">((resolve) => { signal.addEventListener("abort", () => resolve("cancelled"), { once: true }); }); let request: Request; try { + const body = input.hasBody ? this.#requestBody(active) : undefined; + // why: a relay with no body reads nothing, so the peer is told to stop that direction at once. + if (body === undefined) void active.channel.readable.cancel().catch(() => undefined); request = new Request(input.url, { headers: new Headers(input.headers.filter(([name]) => !isRelayFramingHeader(name))), method: input.method, signal, - ...(feed === undefined ? {} : { body: feed.stream, duplex: "half" }), + ...(body === undefined ? {} : { body, duplex: "half" }), } as RequestInit); } catch (error: unknown) { throw new DispatchError( @@ -221,25 +227,29 @@ export class RelayConnection { void answered .then((late) => ("response" in late ? late.response.body?.cancel() : undefined)) .catch(() => undefined); - return { cancelled: true }; + return this.#finished(active); } if ("error" in first) { - if (signal.aborted) return { cancelled: true }; + if (signal.aborted) return this.#finished(active); this.logger.error("Relay target failed", { message: describe(first.error), target: input.target, }); throw new Error("The relay target failed"); } - return this.#respond(input, first.response, signal, push); + // why: the target has answered, so the unread rest of the request body is stopped on the channel. + active.abandoned = true; + void active.reader?.cancel().catch(() => undefined); + return this.#respond(input, first.response, active, push); } async #respond( input: RelayRequestInput, response: Response, - signal: AbortSignal, + active: ActiveRelay, push: RelayPush, - ): Promise<{ readonly cancelled?: true }> { + ): Promise { + const { signal } = active.controller; const headers = relayHeaderPairs(response.headers, { dropCredentials: false }); const broken = headerViolation(headers); if (broken !== undefined) { @@ -252,47 +262,63 @@ export class RelayConnection { } if (signal.aborted) { void response.body?.cancel().catch(() => undefined); - return { cancelled: true }; + return this.#finished(active); } - await push.head(response.status, headers); + try { + await push.head(response.status, headers); + } catch (error: unknown) { + void response.body?.cancel().catch(() => undefined); + throw error; + } + const { writer } = active; const noBody = input.method === "HEAD" || NO_BODY_STATUSES.has(response.status) || response.body === null; if (noBody) { void response.body?.cancel().catch(() => undefined); - return signal.aborted ? { cancelled: true } : {}; + return this.#close(active, writer); } - return this.#stream(input, response.body, signal, push); + return this.#stream(input, response.body, active, writer); + } + + async #close( + active: ActiveRelay, + writer: WritableStreamDefaultWriter, + ): Promise { + try { + await writer.close(); + } catch (error: unknown) { + this.#note(active, error); + return this.#finished(active); + } + return active.controller.signal.aborted ? this.#finished(active) : {}; } async #stream( input: RelayRequestInput, body: ReadableStream, - signal: AbortSignal, - push: RelayPush, - ): Promise<{ readonly cancelled?: true }> { + active: ActiveRelay, + writer: WritableStreamDefaultWriter, + ): Promise { + const { signal } = active.controller; const reader = body.getReader(); const stop = () => void reader.cancel().catch(() => undefined); - // why: a cancel that landed while the head was being written already fired its event, so no listener would ever stop this reader. - if (signal.aborted) { - stop(); - return { cancelled: true }; - } signal.addEventListener("abort", stop, { once: true }); + if (signal.aborted) stop(); try { for (;;) { const step = await reader.read(); - if (signal.aborted) return { cancelled: true }; - if (step.done) return {}; - for (let offset = 0; offset < step.value.length; offset += RELAY_MAX_PUSH_BYTES) { - const piece = step.value.subarray(offset, offset + RELAY_MAX_PUSH_BYTES); - await push.chunk( - Buffer.from(piece.buffer, piece.byteOffset, piece.byteLength).toString("base64"), - ); - if (signal.aborted) return { cancelled: true }; + if (signal.aborted) return this.#finished(active); + if (step.done) break; + try { + await writer.write(step.value); + } catch (error: unknown) { + this.#note(active, error); + return this.#finished(active); } + if (signal.aborted) return this.#finished(active); } } catch (error: unknown) { - if (signal.aborted) return { cancelled: true }; + if (signal.aborted) return this.#finished(active); this.logger.error("Relay target's response body failed", { message: describe(error), target: input.target, @@ -301,6 +327,7 @@ export class RelayConnection { } finally { signal.removeEventListener("abort", stop); } + return this.#close(active, writer); } } diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index ddb58a133..de5ab8f6a 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -17,7 +17,6 @@ import { } from "../core/index.js"; import { PROTOCOL_VERSION_RANGE, type ProtocolRange } from "../contract/index.js"; import { - createConnectionPair, CryptoTokenSecrets, FakeClock, FakeSystemStats, @@ -42,6 +41,12 @@ import { Dispatcher } from "./dispatcher.js"; import { describeLeaseRequestFailure } from "./error-code.js"; import { AdminAuthenticationFailedError, type SessionRoleResolver } from "./session.js"; import { DaemonServer } from "./server.js"; +import { GatewayRelay, type GatewayWorkerClient, type WorkerDirectory } from "../gateway/index.js"; +import { linkPair } from "../link/testing.js"; +import { connectSimlockClient } from "../simlock-client/client.js"; +import { SimlockWire } from "../simlock-client/wire.js"; +import type { RelayTargets } from "./relay.js"; +import * as relaySupport from "./test-relay-support.js"; import { AdminSecretManager } from "./admin-secret.js"; import { type PhysicalDeviceWatcher } from "../leasing/index.js"; import { createTestEngine } from "../leasing/testing.js"; @@ -197,8 +202,9 @@ describe("DaemonServer", () => { 32, "cannot read status.get's capabilities, send lease.request's requires, or call relay.request", ], + [33, "cannot send relay.request's channel, or read a relayed body from its byte channel"], ])( - "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 33, to a client on protocol %i, which %s", + "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 34, to a client on protocol %i, which %s", async (version) => { const harness = await createHarness(); const previous = await createClient(harness.socketPath); @@ -208,7 +214,7 @@ describe("DaemonServer", () => { ).resolves.toMatchObject({ error: { code: "PROTOCOL_VERSION_UNSUPPORTED", - details: { client: { min: version, max: version }, daemon: { min: 33, max: 33 } }, + details: { client: { min: version, max: version }, daemon: { min: 34, max: 34 } }, }, ok: false, }); @@ -1471,6 +1477,160 @@ describe("DaemonServer stored lease requests", () => { }); }); +describe("DaemonServer relays during startup", () => { + async function startParked(relayTargets: RelayTargets) { + const converge = deferred(); + const harness = await createHarness({ + converge: () => converge.promise, + relayTargets, + start: false, + }); + const startPromise = harness.daemon.start(); + startPromise.catch(() => undefined); + const pair = linkPair(); + harness.daemon.acceptUplink(pair.worker); + return { converge, harness, pair, startPromise }; + } + + async function wireOf(pair: ReturnType) { + const wire = new SimlockWire(pair.gateway); + await wire.hello({ principal: "gw:test" }); + await wire.call("status.get", {}); + return { link: pair.gateway, wire }; + } + + async function gatewayRelayOf(pair: ReturnType) { + const client = (await connectSimlockClient( + { connection: pair.gateway, principal: "gw:test" }, + true, + )) as GatewayWorkerClient; + const directory: WorkerDirectory = { + target: (workerId) => + workerId === "wrk_a" + ? { client: () => client, reachable: true, refresh: async () => undefined, workerId } + : undefined, + }; + return new GatewayRelay({ directory }); + } + + it("a relay sent while the worker is still starting holds its channel, and its 8 MiB upload, twice the 4 MiB window, only finishes once startup converges and arrives in full", async () => { + let received = ""; + let length = 0; + let calls = 0; + const { converge, pair, startPromise } = await startParked({ + echo: async (request) => { + calls += 1; + const parts = await relaySupport.readParts(request.body); + received = relaySupport.digestOf(parts); + length = parts.reduce((total, part) => total + part.length, 0); + return new Response("ok"); + }, + }); + const uplink = await wireOf(pair); + + const relay = await relaySupport.openRelay( + uplink, + relaySupport.relayInput({ hasBody: true, method: "PUT" }), + { keepOpen: true }, + ); + // why: 8 MiB is twice the 4 MiB window, so a sender can only finish once the worker reads; a channel accepted but parked would let it write at most the window. + const upload = relaySupport.patternBytes(8 * relaySupport.MIB, 5); + const writer = relay.channel.writable.getWriter(); + let written = 0; + const writing = (async () => { + for (let offset = 0; offset < upload.length; offset += relaySupport.MIB) { + await writer.write(upload.subarray(offset, offset + relaySupport.MIB)); + written += relaySupport.MIB; + } + await writer.close(); + })(); + await relaySupport.sleep(200); + const callsWhileStarting = calls; + const writtenWhileStarting = written; + converge.resolve(); + await startPromise; + const outcome = await relaySupport.settleWithin(relay.result); + await writing; + + expect(callsWhileStarting).toBe(0); + // why: bytes written while startup is parked prove the channel was accepted; none written would also pass "< 8 MiB" if nothing were accepted. + expect(writtenWhileStarting).toBeGreaterThan(0); + expect(writtenWhileStarting).toBeLessThan(upload.length); + expect(outcome).toEqual({ state: "fulfilled", value: {} }); + expect(length).toBe(upload.length); + expect(received).toBe(relaySupport.digestOf([upload])); + }); + + it("a relay whose 8 MiB upload stays parked by worker startup for 60 s fails INTERNAL on the gateway with the 60 s message", async () => { + const { converge, pair, startPromise } = await startParked({ + echo: () => Promise.resolve(new Response("ok")), + }); + const relay = await gatewayRelayOf(pair); + const request = new Request("http://gateway.test:4321/agent-device/rpc", { + body: relaySupport.patternStream(8 * relaySupport.MIB, 2), + duplex: "half", + method: "PUT", + } as RequestInit); + + const pending = relaySupport.settleWithin( + relay.relay("wrk_a", { request, target: "echo", tenant: "gw.g1.alice" }), + 10_000, + ); + await relaySupport.sleep(300); + pair.clock.advance(60_000); + const outcome = await pending; + converge.resolve(); + await startPromise; + + expect(outcome).toEqual({ + code: "INTERNAL", + message: "worker wrk_a did not read the relayed request body for 60 s", + state: "rejected", + }); + }); + + it("a parked relay whose channel failed while it waited answers { cancelled: true } without running its target", async () => { + let calls = 0; + const { converge, pair, startPromise } = await startParked({ + echo: () => { + calls += 1; + return Promise.resolve(new Response("ok")); + }, + }); + const uplink = await wireOf(pair); + const relay = await relaySupport.openRelay(uplink, relaySupport.relayInput(), { + keepOpen: true, + }); + await relaySupport.sleep(100); + + relay.channel.abort("caller left while the worker started"); + await relaySupport.sleep(100); + converge.resolve(); + await startPromise; + const outcome = await relaySupport.settleWithin(relay.result); + + expect(outcome).toEqual({ state: "fulfilled", value: { cancelled: true } }); + expect(calls).toBe(0); + }); + + it("a parked relay whose startup fails answers DAEMON_STARTUP_FAILED and leaves its channel errored aborted", async () => { + const { converge, pair, startPromise } = await startParked({ + echo: () => Promise.resolve(new Response("ok")), + }); + const uplink = await wireOf(pair); + const relay = await relaySupport.openRelay(uplink, relaySupport.relayInput()); + await relaySupport.sleep(100); + + converge.reject(new Error("boom")); + await startPromise.catch(() => undefined); + const outcome = await relaySupport.settleWithin(relay.result); + const read = await relay.readError(); + + expect(outcome).toMatchObject({ code: "DAEMON_STARTUP_FAILED", state: "rejected" }); + expect(read).toEqual({ ended: false, reason: "aborted" }); + }); +}); + async function createClientRetrying(socketPath: string, timeoutMs = 2_000): Promise { const deadline = Date.now() + timeoutMs; for (;;) { @@ -2858,9 +3018,9 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { */ it("grants an accepted uplink the admin role without a credential (ADR 0005 §5)", async () => { const harness = await createHarness({ resolveRole: { resolve: () => "agent" } }); - const [workerEnd, gatewayEnd] = createConnectionPair(); - harness.daemon.acceptUplink(workerEnd); - const gateway = driveConnection(gatewayEnd); + const pair = linkPair(); + harness.daemon.acceptUplink(pair.worker); + const gateway = driveConnection(pair.gateway); const reply = await gateway.request("hello", { clientVersion: "gateway", @@ -2888,9 +3048,9 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { it("negotiates the protocol range over an uplink exactly as over the socket (ADR 0005 §31)", async () => { const harness = await createHarness({ resolveRole: { resolve: () => "agent" } }); - const [workerEnd, gatewayEnd] = createConnectionPair(); - harness.daemon.acceptUplink(workerEnd); - const gateway = driveConnection(gatewayEnd); + const pair = linkPair(); + harness.daemon.acceptUplink(pair.worker); + const gateway = driveConnection(pair.gateway); const reply = await gateway.request("hello", { clientVersion: "gateway", @@ -2912,9 +3072,9 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { protocolVersion: previous, resolveRole: { resolve: () => "admin" }, }); - const [workerEnd, gatewayEnd] = createConnectionPair(); - harness.daemon.acceptUplink(workerEnd); - const gateway = driveConnection(gatewayEnd); + const pair = linkPair(); + harness.daemon.acceptUplink(pair.worker); + const gateway = driveConnection(pair.gateway); const reply = await gateway.request("hello", { clientVersion: "gateway", @@ -3008,6 +3168,7 @@ async function createHarness( readonly host?: ConnectionHost; readonly protocolVersion?: ProtocolRange; readonly includeEnrollment?: boolean; + readonly relayTargets?: RelayTargets; } = {}, ) { const directory = @@ -3079,6 +3240,7 @@ async function createHarness( components: wiring.components, config, ...(options.converge === undefined ? {} : { converge: options.converge }), + ...(options.relayTargets === undefined ? {} : { relayTargets: options.relayTargets }), ...(options.driverRejections === undefined ? {} : { driverRejections: options.driverRejections }), diff --git a/src/daemon/server.ts b/src/daemon/server.ts index df04fc447..e469cb12d 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -38,12 +38,14 @@ import { normalizeProtocolVersion, PROTOCOL_VERSION_RANGE, PUSH_SCHEMAS, + relayChannelSchema, type ComponentProgress, type OperationName, type OPERATIONS, type ProtocolRange, type Role, } from "../contract/index.js"; +import type { LinkChannel, LinkConnection } from "../link/index.js"; import type { ConnectionHost } from "./connection-host.js"; import type { TokenStore } from "../http/token-store.js"; import { @@ -101,6 +103,8 @@ interface Connection { * site that is actually the uplink, so a future forced role elsewhere cannot be mistaken for it. */ readonly isGatewayUplink: boolean; + // why: set with `isGatewayUplink`; the link accepts the byte channels a relay names (ADR 0028). + readonly link: LinkConnection | undefined; /** * Lease ids this connection is *currently* explicitly releasing (`lease.release`/ * `lease.release-all`), added right before the dispatched call and consumed by @@ -325,6 +329,8 @@ export class DaemonServer { #stopPromise: Promise | undefined; #health: DaemonHealth = "starting"; #readyPromise: Promise | undefined; + // why: a request that arrives on an uplink before `start()` has claimed its socket parks here, so it never runs ahead of convergence. + readonly #beforeReady = quietDeferred(); /** * Every `#dispatchLine` call that starts while `#health` is still `"starting"`, * tracked so a convergence failure can genuinely drain them -- await each one's @@ -445,6 +451,15 @@ export class DaemonServer { * well before this promise settles. */ async start(): Promise { + try { + await this.#start(); + } catch (error: unknown) { + this.#beforeReady.reject(error); + throw error; + } + } + + async #start(): Promise { await this.options.host.start((connection) => this.#accept(connection)); // ADR §5: written only after the socket claim above has succeeded -- a daemon that loses // the start race throws out of `host.start()` and never reaches this line, so it never @@ -455,6 +470,7 @@ export class DaemonServer { await this.options.adminSecret?.persist(); const readyPromise = this.#converge(); this.#readyPromise = readyPromise; + readyPromise.then(this.#beforeReady.resolve, this.#beforeReady.reject); // See `onSocketClaimed`'s doc: fired only after `#readyPromise` is assigned, so a request // the auxiliary frontend starts serving as an immediate result of this call already parks // on it correctly via `#awaitReady()`. @@ -586,9 +602,8 @@ export class DaemonServer { } async #awaitReady(): Promise { - if (this.#readyPromise === undefined) return; try { - await this.#readyPromise; + await (this.#readyPromise ?? this.#beforeReady.promise); } catch { throw new StartupFailedError(); } @@ -648,11 +663,11 @@ export class DaemonServer { * kind of statement §5 says admin authority may come from. An operator who does not want a * gateway administering this machine removes two config keys. */ - acceptUplink(connection: IpcConnection): void { - this.#accept(connection, "admin", true); + acceptUplink(connection: LinkConnection): void { + this.#accept(connection, "admin", connection); } - #accept(socket: IpcConnection, forcedRole?: Role, isGatewayUplink = false): void { + #accept(socket: IpcConnection, forcedRole?: Role, link?: LinkConnection): void { if (this.#stopping) { void socket.close(); return; @@ -662,7 +677,8 @@ export class DaemonServer { closed: false, forcedRole, helloReceived: false, - isGatewayUplink, + isGatewayUplink: link !== undefined, + link, // Overwritten by `#handleHello` before any dispatched request can read them -- every // path that reaches `#handleRequest` has `connection.helloReceived === true` by // construction (`#dispatchLine` routes to `#handleHello` until then). @@ -743,6 +759,9 @@ export class DaemonServer { return; } + // why: accepted here, in the same turn the line was read, so a request that parks for startup already holds its channel (ADR 0028). + const relayChannel = this.#acceptRelayChannel(connection, frame); + // `daemon.stop` is a frozen exception (ADR 0003 §6), but only with respect to the // *protocol-version* gate: "the daemon accepts it at any protocol version it has ever // spoken". It is not frozen with respect to authentication or role -- §3's operation matrix @@ -773,6 +792,7 @@ export class DaemonServer { } if (connection.protocolMismatch) { + relayChannel?.abort(); await this.#respondError( connection.socket, frame.id, @@ -784,6 +804,7 @@ export class DaemonServer { } if (this.#stopping) { + relayChannel?.abort(); await this.#respondError( connection.socket, frame.id, @@ -794,9 +815,10 @@ export class DaemonServer { } try { - const payload = await this.#handleRequest(connection, frame); + const payload = await this.#handleRequest(connection, frame, relayChannel); await writeFrame(connection.socket, { id: frame.id, ok: true, payload }); } catch (error: unknown) { + relayChannel?.abort(); const code = errorCode(error); // A handled error is already on the dispatcher's `operation` line; this one adds the stack. if (code === "INTERNAL") { @@ -974,7 +996,11 @@ export class DaemonServer { * on failure, only a push to suppress while it is in flight. */ // fallow-ignore-next-line complexity -- one case per request type; the switch is the transport's whole surface. - async #handleRequest(connection: Connection, frame: RequestFrame): Promise { + async #handleRequest( + connection: Connection, + frame: RequestFrame, + relayChannel: LinkChannel | undefined, + ): Promise { switch (frame.type) { case "lease.request": return this.#requestLease(connection, frame.id, frame.payload); @@ -1106,9 +1132,7 @@ export class DaemonServer { // per-call push wiring `lease.request` needs, and gets it the same way. return this.#execDevice(connection, frame.id, frame.payload); case "relay.request": - return this.#relayRequest(connection, frame.id, frame.payload); - case "relay.body": - return this.#dispatcher.dispatch("relay.body", frame.payload, this.#session(connection)); + return this.#relayRequest(connection, frame.id, frame.payload, relayChannel); case "relay.cancel": return this.#dispatcher.dispatch("relay.cancel", frame.payload, this.#session(connection)); case "config.get": @@ -1181,6 +1205,20 @@ export class DaemonServer { } } + // why: `channel` is wire input, so its shape is checked before it names a channel; a name that fails, or one the link never saw, accepts nothing and the call fails `BAD_REQUEST` later. + #acceptRelayChannel(connection: Connection, frame: RequestFrame): LinkChannel | undefined { + if (frame.type !== "relay.request" || connection.link === undefined) return undefined; + const payload: unknown = frame.payload; + if (typeof payload !== "object" || payload === null) return undefined; + const name = relayChannelSchema.safeParse((payload as { channel?: unknown }).channel); + if (!name.success) return undefined; + try { + return connection.link.acceptChannel(name.data); + } catch { + return undefined; + } + } + #session(connection: Connection): DispatchSession { return { isGatewayUplink: connection.isGatewayUplink, @@ -1309,20 +1347,15 @@ export class DaemonServer { } } - // why: each push resolves once it is on the socket, so the relay reads its target only as fast as the socket takes the parts. - - #relayRequest(connection: Connection, requestId: RequestId, value: unknown): Promise { + #relayRequest( + connection: Connection, + requestId: RequestId, + value: unknown, + relayChannel: LinkChannel | undefined, + ): Promise { return this.#dispatcher.dispatch("relay.request", value, { ...this.#session(connection), - onRelayChunk: (chunk) => - writeFrame(connection.socket, { - push: "relay-chunk", - payload: this.#parseOutput( - PUSH_SCHEMAS["relay-chunk"], - { chunk, requestId }, - "push:relay-chunk", - ), - }), + ...(relayChannel === undefined ? {} : { relayChannel }), onRelayHead: (status, headers) => writeFrame(connection.socket, { push: "relay-head", @@ -1580,6 +1613,22 @@ export class DaemonServer { } } +// why: nobody may be parked on the gate when it rejects, and an unobserved rejection would end the process. +function quietDeferred(): { + readonly promise: Promise; + readonly resolve: () => void; + readonly reject: (error: unknown) => void; +} { + let resolve!: () => void; + let reject!: (error: unknown) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + promise.catch(() => undefined); + return { promise, reject, resolve }; +} + /** * An `OwnerRoutedFacts` that never emits -- what a gateway gets, since it has no local leases * to report facts about (see the constructor's comment). A named function rather than an inline diff --git a/src/daemon/test-relay-support.ts b/src/daemon/test-relay-support.ts index a2dc9729c..a5477c071 100644 --- a/src/daemon/test-relay-support.ts +++ b/src/daemon/test-relay-support.ts @@ -5,13 +5,9 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { FakeDriver } from "../core/testing.js"; -import { - createConnectionPair, - MemoryFilesystem, - SystemClock, - type IpcConnection, - type Logger, -} from "../ports/index.js"; +import { MemoryFilesystem, SystemClock, type Logger } from "../ports/index.js"; +import type { LinkChannel, LinkConnection } from "../link/index.js"; +import { linkPair, type LinkPair } from "../link/testing.js"; import type { DispatchSession } from "./dispatch.js"; import { startDaemon, type StartDaemonOptions } from "./main.js"; import type { RelayTargets } from "./relay.js"; @@ -73,7 +69,7 @@ export type Settled = | { readonly state: "rejected"; readonly code?: unknown; readonly message: string } | { readonly state: "pending" }; -export async function settle(promise: Promise, withinMs = 5_000): Promise> { +export async function settleWithin(promise: Promise, withinMs = 5_000): Promise> { const outcome = promise.then( (value): Settled => ({ state: "fulfilled", value }), (error: unknown): Settled => ({ @@ -133,7 +129,7 @@ export function patternStream( }); } -export async function readAll(stream: ReadableStream | null): Promise { +export async function readParts(stream: ReadableStream | null): Promise { const parts: Uint8Array[] = []; if (stream === null) return parts; const reader = stream.getReader(); @@ -181,14 +177,18 @@ export async function startWorker( return { directory, logger, worker }; } -export async function openUplink( - worker: DaemonServer, -): Promise<{ readonly wire: SimlockWire; readonly gatewayEnd: IpcConnection }> { - const [workerEnd, gatewayEnd] = createConnectionPair(); - worker.acceptUplink(workerEnd); - const wire = new SimlockWire(gatewayEnd); +export interface Uplink { + readonly wire: SimlockWire; + readonly link: LinkConnection; + readonly pair: LinkPair; +} + +export async function openUplink(worker: DaemonServer): Promise { + const pair = linkPair(); + worker.acceptUplink(pair.worker); + const wire = new SimlockWire(pair.gateway); await wire.hello({ principal: "gw:test" }); - return { gatewayEnd, wire }; + return { link: pair.gateway, pair, wire }; } let relaySequence = 0; @@ -212,32 +212,63 @@ export function relayInput(overrides: Record = {}): Record; readonly heads: RelayHead[]; - readonly chunks: string[]; - readonly bytes: () => Uint8Array[]; + readonly body: (withinMs?: number) => Promise>; + readonly readError: () => Promise<{ readonly reason?: string; readonly ended: boolean }>; +} + +export interface OpenRelayOptions { + readonly upload?: Uint8Array; + readonly keepOpen?: boolean; + readonly channelName?: string | null; } -export function openRelay(wire: SimlockWire, input: Record): OpenedRelay { +export async function openRelay( + uplink: Pick, + input: Record, + options: OpenRelayOptions = {}, +): Promise { + const channel = await uplink.link.openChannel({ signal: new AbortController().signal }); const heads: RelayHead[] = []; - const chunks: string[] = []; - const hooks: CallHooks = { - onRelayChunk: (chunk) => chunks.push(chunk), - onRelayHead: (head) => heads.push(head), - }; - const result = wire.call("relay.request", input, hooks); + const hooks: CallHooks = { onRelayHead: (head) => heads.push(head) }; + const named = options.channelName === null ? {} : { channel: options.channelName ?? channel.id }; + const result = uplink.wire.call("relay.request", { ...input, ...named }, hooks); result.catch(() => undefined); - return { - bytes: () => chunks.map((chunk) => new Uint8Array(Buffer.from(chunk, "base64"))), - chunks, - heads, - relayId: String(input.relayId), - result, + if (options.keepOpen !== true) { + const writer = channel.writable.getWriter(); + if (options.upload !== undefined) { + void writer + .write(options.upload) + .then(() => writer.close()) + .catch(() => undefined); + } else { + void writer.close().catch(() => undefined); + } + } + const body = async (withinMs = 3_000): Promise> => { + const read = (async () => { + const parts = await readParts(channel.readable); + return new Uint8Array(Buffer.concat(parts)); + })(); + return settleWithin(read, withinMs); }; -} - -export function base64Of(bytes: Uint8Array): string { - return Buffer.from(bytes).toString("base64"); + const readError = async (): Promise<{ reason?: string; ended: boolean }> => { + const read = (async (): Promise<{ reason?: string; ended: boolean }> => { + try { + await readParts(channel.readable); + return { ended: true }; + } catch (error: unknown) { + return { ended: false, reason: (error as { reason?: string }).reason ?? String(error) }; + } + })(); + return Promise.race([ + read, + sleep(3_000).then(() => ({ ended: false, reason: "still open after 3 s" })), + ]); + }; + return { body, channel, heads, readError, relayId: String(input.relayId), result }; } export async function cleanUp(daemons: DaemonServer[], directories: string[]): Promise { diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index ccee2a78b..76e0ac18f 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -199,7 +199,6 @@ export class GatewayDispatcher { "lease.release-all": this.#leaseReleaseAll, "device.exec": this.#deviceExec, "relay.request": relayRefused, - "relay.body": relayRefused, "relay.cancel": relayRefused, // "daemon.stop" is absent for the same reason it is absent from the worker's table: the // transport intercepts it ahead of any dispatch (ADR 0003 §6's frozen exception). diff --git a/src/gateway/relay.test.ts b/src/gateway/relay.test.ts index 7ec34a94b..9164ffd2b 100644 --- a/src/gateway/relay.test.ts +++ b/src/gateway/relay.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it, vi } from "vitest"; +import { LinkChannelError } from "../link/index.js"; +import type { LinkChannel, LinkChannelErrorReason, LinkConnection } from "../link/index.js"; import { connectSimlockClient } from "../simlock-client/client.js"; import { completeHello, ScriptedConnection } from "../simlock-client/test-support.js"; import type { SentFrame } from "../simlock-client/test-support.js"; @@ -14,8 +16,101 @@ function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } -async function setup() { - const connection = new ScriptedConnection(); +class FakeChannel implements LinkChannel { + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly written: Uint8Array[] = []; + readonly credit = 0; + writableClosed = false; + aborted = false; + abortReason: string | undefined; + #readController!: ReadableStreamDefaultController; + #writeController!: WritableStreamDefaultController; + + constructor(readonly id: string) { + this.readable = new ReadableStream({ + start: (controller) => { + this.#readController = controller; + }, + }); + this.writable = new WritableStream({ + close: () => { + this.writableClosed = true; + }, + start: (controller) => { + this.#writeController = controller; + }, + write: (chunk) => { + this.written.push(chunk); + }, + }); + } + + whenCredit(): Promise { + return Promise.resolve(); + } + + abort(reason?: string): void { + this.aborted = true; + this.abortReason = reason; + try { + this.#readController.error(new LinkChannelError("aborted")); + } catch { + // why: the readable had already ended or failed. + } + } + + feed(bytes: Uint8Array): void { + this.#readController.enqueue(bytes); + } + + end(): void { + this.#readController.close(); + } + + fail(reason: LinkChannelErrorReason): void { + try { + this.#readController.error(new LinkChannelError(reason)); + } catch { + // why: already ended. + } + try { + this.#writeController.error(new LinkChannelError(reason)); + } catch { + // why: already closed. + } + } + + failWritable(reason: LinkChannelErrorReason): void { + this.#writeController.error(new LinkChannelError(reason)); + } +} + +class FakeLink extends ScriptedConnection implements LinkConnection { + readonly channels: FakeChannel[] = []; + holdOpen = false; + + openChannel(options: { readonly signal: AbortSignal }): Promise { + if (this.holdOpen) { + return new Promise((_resolve, reject) => { + const fail = () => reject(options.signal.reason as Error); + if (options.signal.aborted) fail(); + else options.signal.addEventListener("abort", fail, { once: true }); + }); + } + const channel = new FakeChannel(`chan-${String(this.channels.length + 1)}`); + this.channels.push(channel); + return Promise.resolve(channel); + } + + acceptChannel(id: string): LinkChannel { + throw new Error(`the gateway accepts no channel: ${id}`); + } +} + +async function setup(options: { readonly deadlineMs?: number; readonly holdOpen?: boolean } = {}) { + const connection = new FakeLink(); + connection.holdOpen = options.holdOpen ?? false; const connecting = connectSimlockClient({ connection, credential: "secret" }, true); await vi.waitFor(() => expect(connection.lastSentOf("hello")).toBeDefined()); completeHello(connection, { role: "admin" }); @@ -26,14 +121,24 @@ async function setup() { ? { client: () => client, reachable: true, refresh: async () => undefined, workerId } : undefined, }; - return { connection, relay: new GatewayRelay({ directory }) }; + return { + connection, + relay: new GatewayRelay({ + directory, + ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }), + }), + }; } -function call(body?: ReadableStream) { +function call( + body?: ReadableStream, + signal?: AbortSignal, +): { request: Request; target: string; tenant: string } { return { request: new Request("http://gateway.test:4321/agent-device/rpc", { method: body === undefined ? "GET" : "PUT", ...(body === undefined ? {} : { body, duplex: "half" }), + ...(signal === undefined ? {} : { signal }), } as RequestInit), target: "echo", tenant: "gw:g1:alice", @@ -60,33 +165,413 @@ function relayIdOf(frame: SentFrame): unknown { return (frame.payload as { relayId?: unknown }).relayId; } -describe("GatewayRelay against a worker that breaks the protocol", () => { - it("fails the relay with INTERNAL naming the worker, and sends relay.cancel, on a relay-head with status 101", async () => { +async function readFailure(response: Response) { + return outcome(response.body?.getReader().read() ?? Promise.reject(new Error("no body"))); +} + +async function openedChannel(connection: FakeLink): Promise { + await vi.waitFor(() => expect(connection.channels).toHaveLength(1)); + return connection.channels[0] as FakeChannel; +} + +describe("GatewayRelay on a byte channel", () => { + it("opens a channel, names it in relay.request, closes its writable at once for a GET, and sends no relay.body", async () => { const { connection, relay } = await setup(); - const pending = outcome(relay.relay(WORKER_ID, call())); + + const pending = relay.relay(WORKER_ID, call()); const request = await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + await vi.waitFor(() => expect(channel.writableClosed).toBe(true)); + connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); + connection.reply(request.id, {}); + channel.end(); + await pending; - connection.push("relay-head", { headers: [], requestId: request.id, status: 101 }); + expect((request.payload as { channel?: unknown }).channel).toBe(channel.id); + expect(connection.sent.filter((frame) => frame.type === "relay.body")).toEqual([]); + }); - expect(await pending).toEqual({ + it("writes the caller's request body into the channel's writable, byte for byte, and then closes it", async () => { + const { connection, relay } = await setup(); + let piece = 0; + const body = new ReadableStream({ + pull(controller) { + piece += 1; + controller.enqueue(new Uint8Array(64 * KIB).fill(piece)); + if (piece === 4) controller.close(); + }, + }); + + const pending = relay.relay(WORKER_ID, call(body)); + const request = await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + await vi.waitFor(() => expect(channel.writableClosed).toBe(true)); + connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); + connection.reply(request.id, {}); + channel.end(); + await pending; + + const written = Buffer.concat(channel.written); + expect(written.length).toBe(4 * 64 * KIB); + expect([written[0], written[64 * KIB], written[3 * 64 * KIB]]).toEqual([1, 2, 4]); + }); + + it("settles the call on a {} answer but ends the caller's body only at the channel's end", async () => { + const { connection, relay } = await setup(); + const pending = relay.relay(WORKER_ID, call()); + const request = await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); + const response = await pending; + const reader = response.body?.getReader(); + + connection.reply(request.id, {}); + channel.feed(new TextEncoder().encode("late bytes")); + const first = await reader?.read(); + const beforeEnd = await Promise.race([ + reader?.read().then(() => "settled"), + sleep(150).then(() => "still open"), + ]); + channel.end(); + const last = await reader?.read(); + + expect(new TextDecoder().decode(first?.value)).toBe("late bytes"); + expect(beforeEnd).toBe("still open"); + expect(last?.done).toBe(true); + }); + + it("cancels the caller's request body and clears its deadline timer when the channel ends", async () => { + const deadlineMs = 123_456; + const handles: unknown[] = []; + const realSetTimeout = globalThis.setTimeout; + const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout").mockImplementation((( + handler: () => void, + delay?: number, + ) => { + const handle = realSetTimeout(handler, delay); + if (delay === deadlineMs) handles.push(handle); + return handle; + }) as unknown as typeof setTimeout); + const clearSpy = vi.spyOn(globalThis, "clearTimeout"); + let cancelled = false; + const body = new ReadableStream({ + cancel: () => { + cancelled = true; + }, + pull: () => new Promise(() => undefined), + }); + try { + const { connection, relay } = await setup({ deadlineMs }); + const pending = relay.relay(WORKER_ID, call(body)); + const request = await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); + const response = await pending; + const reader = response.body?.getReader(); + + channel.end(); + const last = await reader?.read(); + + expect(last?.done).toBe(true); + await vi.waitFor(() => expect(cancelled).toBe(true)); + expect(handles).toHaveLength(1); + expect(clearSpy).toHaveBeenCalledWith(handles[0]); + } finally { + setTimeoutSpy.mockRestore(); + clearSpy.mockRestore(); + } + }); + + it("errors the caller's body saying the worker ended the response early when the channel is aborted by the peer after the {} answer", async () => { + const { connection, relay } = await setup(); + const pending = relay.relay(WORKER_ID, call()); + const request = await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); + const response = await pending; + connection.reply(request.id, {}); + await sleep(20); + + channel.fail("aborted"); + const read = await readFailure(response); + + expect(read).toEqual({ code: "INTERNAL", - message: `worker ${WORKER_ID} sent an invalid relay response`, + message: `worker ${WORKER_ID} ended the relayed response early`, state: "rejected", }); + }); + + it("errors the caller's body with the deadline message when the worker answers {} and never ends the channel", async () => { + const { connection, relay } = await setup({ deadlineMs: 100 }); + const pending = relay.relay(WORKER_ID, call()); + const request = await sentFrame(connection, "relay.request"); + await openedChannel(connection); + connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); + const response = await pending; + connection.reply(request.id, {}); + + const read = await readFailure(response); + + expect(read).toMatchObject({ + message: `worker ${WORKER_ID} did not finish the relayed request within 100 ms`, + state: "rejected", + }); + }); + + it.each([ + { + name: "a worker failure before the head", + run: (connection: FakeLink, id: number | string) => + connection.fail(id, "INTERNAL", "worker side exploded"), + }, + { name: "no answer by the deadline", run: () => undefined }, + ])("aborts its channel when the exchange ends on $name", async ({ run }) => { + const { connection, relay } = await setup({ deadlineMs: 150 }); + const pending = outcome(relay.relay(WORKER_ID, call())); + const request = await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + + run(connection, request.id); + await pending; + + expect(channel.aborted).toBe(true); + }); + + it("aborts its channel, and sends relay.cancel, when the caller cancels the body stream", async () => { + const { connection, relay } = await setup(); + const pending = relay.relay(WORKER_ID, call()); + const request = await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); + const response = await pending; + + await response.body?.cancel(new Error("caller left")); + const cancel = await sentFrame(connection, "relay.cancel"); expect(relayIdOf(cancel)).toBe(relayIdOf(request)); + expect(channel.aborted).toBe(true); }); - it("fails the relay with INTERNAL naming the worker, and sends relay.cancel, on a relay-head whose header value `Headers` refuses", async () => { + it("aborts its channel when the caller's signal aborts before the head", async () => { + const { connection, relay } = await setup(); + const controller = new AbortController(); + const pending = outcome(relay.relay(WORKER_ID, call(undefined, controller.signal))); + await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + + controller.abort(new Error("caller left before the head")); + const failure = await pending; + + expect(failure).toMatchObject({ message: "caller left before the head", state: "rejected" }); + expect(channel.aborted).toBe(true); + }); + + it("stops reading the caller's body once the channel's writable errors stopped", async () => { + const { connection, relay } = await setup(); + let pulls = 0; + let cancelled = false; + const body = new ReadableStream({ + async pull(controller) { + pulls += 1; + await sleep(5); + controller.enqueue(new Uint8Array(16 * KIB)); + if (pulls >= 200) controller.close(); + }, + cancel() { + cancelled = true; + }, + }); + const pending = relay.relay(WORKER_ID, call(body)); + const request = await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + await vi.waitFor(() => expect(channel.written.length).toBeGreaterThan(0)); + + channel.failWritable("stopped"); + connection.push("relay-head", { headers: [], requestId: request.id, status: 401 }); + connection.reply(request.id, {}); + await pending; + await sleep(100); + const pullsAfter = pulls; + await sleep(100); + + expect(cancelled).toBe(true); + expect(pulls).toBe(pullsAfter); + expect(pulls).toBeLessThan(200); + }); + + it("counts the wait for a channel against the deadline, sends no relay.request while it waits, and fails WORKER_UNREACHABLE with the deadline message", async () => { + const { connection, relay } = await setup({ deadlineMs: 100, holdOpen: true }); + + const failure = await outcome(relay.relay(WORKER_ID, call())); + + expect(failure).toEqual({ + code: "WORKER_UNREACHABLE", + message: `worker ${WORKER_ID} did not finish the relayed request within 100 ms`, + state: "rejected", + }); + expect(connection.sent.filter((frame) => frame.type === "relay.request")).toEqual([]); + }); + + it("fails at once with the abort reason, and sends no relay.request, when the caller aborts while it waits for a channel", async () => { + const { connection, relay } = await setup({ holdOpen: true }); + const controller = new AbortController(); + const pending = outcome(relay.relay(WORKER_ID, call(undefined, controller.signal))); + await sleep(50); + + controller.abort(new Error("caller left while waiting")); + const failure = await pending; + + expect(failure).toMatchObject({ message: "caller left while waiting", state: "rejected" }); + expect(connection.sent.filter((frame) => frame.type === "relay.request")).toEqual([]); + }); +}); + +describe("GatewayRelay mapping a channel failure", () => { + const before: readonly { + readonly reason: LinkChannelErrorReason; + readonly code: string; + readonly message: string; + }[] = [ + { + code: "INTERNAL", + message: `worker ${WORKER_ID} sent an invalid relay response`, + reason: "invalid", + }, + { + code: "INTERNAL", + message: `worker ${WORKER_ID} did not read the relayed request body for 60 s`, + reason: "stalled", + }, + { + code: "WORKER_UNREACHABLE", + message: `worker ${WORKER_ID} did not take the relayed request within 30 s`, + reason: "not-accepted", + }, + ]; + + it.each(before)( + "fails $reason before the head with $code and the message the table names", + async ({ code, message, reason }) => { + const { connection, relay } = await setup(); + const pending = outcome(relay.relay(WORKER_ID, call())); + await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + + channel.fail(reason); + + expect(await pending).toEqual({ code, message, state: "rejected" }); + }, + ); + + it("fails closed before the head with WORKER_UNREACHABLE", async () => { + const { connection, relay } = await setup(); + const pending = outcome(relay.relay(WORKER_ID, call())); + await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + + channel.fail("closed"); + + expect(await pending).toMatchObject({ code: "WORKER_UNREACHABLE", state: "rejected" }); + }); + + it("lets the relay.request answer decide when the peer aborts before the head", async () => { const { connection, relay } = await setup(); const pending = outcome(relay.relay(WORKER_ID, call())); const request = await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); - connection.push("relay-head", { - headers: [["x-note", "\u20ac"]], - requestId: request.id, - status: 200, + channel.fail("aborted"); + connection.fail(request.id, "INTERNAL", "worker side exploded"); + + expect(await pending).toEqual({ + code: "INTERNAL", + message: "worker side exploded", + state: "rejected", }); + }); + + it("fails with the deadline error when the peer aborts before the head and no answer comes", async () => { + const { connection, relay } = await setup({ deadlineMs: 150 }); + const pending = outcome(relay.relay(WORKER_ID, call())); + await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + + channel.fail("aborted"); + + expect(await pending).toEqual({ + code: "WORKER_UNREACHABLE", + message: `worker ${WORKER_ID} did not finish the relayed request within 150 ms`, + state: "rejected", + }); + }); + + const after: readonly { + readonly name: string; + readonly run: (connection: FakeLink, channel: FakeChannel, id: number | string) => void; + readonly expected: Record; + }[] = [ + { + expected: { + message: `worker ${WORKER_ID} sent an invalid relay response`, + state: "rejected", + }, + name: "invalid", + run: (_connection, channel) => channel.fail("invalid"), + }, + { + expected: { code: "WORKER_UNREACHABLE", state: "rejected" }, + name: "closed", + run: (_connection, channel) => channel.fail("closed"), + }, + { + expected: { message: expect.stringMatching(/fell behind for 60 s/), state: "rejected" }, + name: "stalled", + run: (_connection, channel) => channel.fail("stalled"), + }, + { + expected: { message: "worker side exploded", state: "rejected" }, + name: "aborted by the peer, with a failed relay.request answer", + run: (connection, channel, id) => { + channel.fail("aborted"); + connection.fail(id, "INTERNAL", "worker side exploded"); + }, + }, + { + expected: { + message: `worker ${WORKER_ID} ended the relayed response early`, + state: "rejected", + }, + name: "aborted by the peer, with a relay.request that settles without an error", + run: (connection, channel, id) => { + channel.fail("aborted"); + connection.reply(id, {}); + }, + }, + ]; + + it.each(after)("errors the caller's body for $name after the head", async ({ expected, run }) => { + const { connection, relay } = await setup(); + const pending = relay.relay(WORKER_ID, call()); + const request = await sentFrame(connection, "relay.request"); + const channel = await openedChannel(connection); + connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); + const response = await pending; + + run(connection, channel, request.id); + const read = await readFailure(response); + + expect(read).toMatchObject(expected); + }); +}); + +describe("GatewayRelay against a worker that breaks the protocol", () => { + it("fails the relay with INTERNAL naming the worker, and sends relay.cancel, on a relay-head with status 101", async () => { + const { connection, relay } = await setup(); + const pending = outcome(relay.relay(WORKER_ID, call())); + const request = await sentFrame(connection, "relay.request"); + + connection.push("relay-head", { headers: [], requestId: request.id, status: 101 }); expect(await pending).toEqual({ code: "INTERNAL", @@ -97,18 +582,17 @@ describe("GatewayRelay against a worker that breaks the protocol", () => { expect(relayIdOf(cancel)).toBe(relayIdOf(request)); }); - it("fails the relay with INTERNAL naming the worker, and sends relay.cancel, on a relay-chunk that is not base64", async () => { + it("errors the caller's body with INTERNAL naming the worker, and sends relay.cancel, on a second relay-head", async () => { const { connection, relay } = await setup(); const pending = relay.relay(WORKER_ID, call()); const request = await sentFrame(connection, "relay.request"); + await openedChannel(connection); connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); const response = await pending; - connection.push("relay-chunk", { chunk: "not base64 !!", requestId: request.id }); + connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); + const read = await readFailure(response); - const read = await outcome( - response.body?.getReader().read() ?? Promise.reject(new Error("no body")), - ); expect(read).toEqual({ code: "INTERNAL", message: `worker ${WORKER_ID} sent an invalid relay response`, @@ -118,6 +602,26 @@ describe("GatewayRelay against a worker that breaks the protocol", () => { expect(relayIdOf(cancel)).toBe(relayIdOf(request)); }); + it("fails the relay with INTERNAL naming the worker, and sends relay.cancel, on a relay-head whose header value `Headers` refuses", async () => { + const { connection, relay } = await setup(); + const pending = outcome(relay.relay(WORKER_ID, call())); + const request = await sentFrame(connection, "relay.request"); + + connection.push("relay-head", { + headers: [["x-note", "€"]], + requestId: request.id, + status: 200, + }); + + expect(await pending).toEqual({ + code: "INTERNAL", + message: `worker ${WORKER_ID} sent an invalid relay response`, + state: "rejected", + }); + const cancel = await sentFrame(connection, "relay.cancel"); + expect(relayIdOf(cancel)).toBe(relayIdOf(request)); + }); + it.each([ { answer: {}, name: "{} with no head" }, { answer: { cancelled: true }, name: "{ cancelled: true } when no cancel was sent" }, @@ -147,9 +651,7 @@ describe("GatewayRelay against a worker that breaks the protocol", () => { connection.fail(request.id, "INTERNAL", "worker side exploded"); - const read = await outcome( - response.body?.getReader().read() ?? Promise.reject(new Error("no body")), - ); + const read = await readFailure(response); expect(read).toMatchObject({ message: "worker side exploded", state: "rejected" }); }); @@ -162,42 +664,4 @@ describe("GatewayRelay against a worker that breaks the protocol", () => { expect(await pending).toMatchObject({ code: "WORKER_UNREACHABLE", state: "rejected" }); }); - - it("sends the request body as relay.body calls with at most 4 sent and not yet answered", async () => { - const { connection, relay } = await setup(); - let piece = 0; - const body = new ReadableStream({ - pull(controller) { - piece += 1; - controller.enqueue(new Uint8Array(256 * KIB).fill(piece)); - if (piece === 10) controller.close(); - }, - }); - const pending = relay.relay(WORKER_ID, call(body)); - const request = await sentFrame(connection, "relay.request"); - const bodyFrames = () => connection.sent.filter((frame) => frame.type === "relay.body"); - - await vi.waitFor(() => expect(bodyFrames().length).toBeGreaterThanOrEqual(4)); - await sleep(100); - const firstWindow = bodyFrames().length; - let answered = 0; - let maxUnanswered = 0; - const isEnd = (frame: SentFrame) => (frame.payload as { end?: boolean }).end === true; - while (!(bodyFrames().some(isEnd) && answered === bodyFrames().length) && answered < 40) { - maxUnanswered = Math.max(maxUnanswered, bodyFrames().length - answered); - const next = bodyFrames()[answered]; - if (next !== undefined) { - connection.reply(next.id, {}); - answered += 1; - } - await sleep(30); - } - connection.push("relay-head", { headers: [], requestId: request.id, status: 200 }); - connection.reply(request.id, {}); - await pending; - - expect(firstWindow).toBe(4); - expect(maxUnanswered).toBeLessThanOrEqual(4); - expect(bodyFrames().length).toBe(11); - }, 30_000); }); diff --git a/src/gateway/relay.ts b/src/gateway/relay.ts index 2cc3f0da9..daf80e2fa 100644 --- a/src/gateway/relay.ts +++ b/src/gateway/relay.ts @@ -1,8 +1,9 @@ -// why: every wait of a relayed exchange is bounded (architecture rule on cross-process waits): a deadline for the whole -// exchange, 4 unanswered request-body calls, 8 relays per worker and 64 MiB of response a caller has not read. +// why: every wait of a relayed exchange is bounded (architecture rule on cross-process waits): one deadline covers the +// channel wait, the exchange and the response body; the link bounds the channels open to a worker (ADR 0028). import { isSimlockError, relayHeaderPairs, type AnySimlockError } from "../contract/index.js"; import { DispatchError } from "../daemon/dispatch.js"; +import { LinkChannelError, type LinkChannel } from "../link/index.js"; import { isUplinkLost, liveClient, type WorkerDirectory } from "./fleet-ports.js"; import type { GatewayWorkerClient } from "./worker-client.js"; @@ -21,23 +22,12 @@ export interface GatewayRelayCall { // why: agent-device's proxy allows 300 s per exchange; the rest is a margin. const DEFAULT_DEADLINE_MS = 330_000; type RelayMethod = Parameters[0]["method"]; -const MAX_RELAYS_PER_WORKER = 8; -const MAX_BODY_CALLS_UNANSWERED = 4; -const MAX_BODY_CHUNK_BYTES = 256 * 1024; -const MAX_UNREAD_BYTES = 64 * 1024 * 1024; const NO_BODY_STATUSES: ReadonlySet = new Set([204, 205, 304]); export class GatewayRelay { - readonly #slots = new Map(); - constructor(private readonly options: GatewayRelayOptions) {} relay(workerId: string, call: GatewayRelayCall): Promise { - let slots = this.#slots.get(workerId); - if (slots === undefined) { - slots = new WorkerSlots(); - this.#slots.set(workerId, slots); - } return new Promise((resolve, reject) => { const exchange = new Exchange({ call, @@ -45,7 +35,6 @@ export class GatewayRelay { deadlineMs: this.options.deadlineMs ?? DEFAULT_DEADLINE_MS, reject, resolve, - slots, workerId, }); exchange.start(); @@ -53,87 +42,31 @@ export class GatewayRelay { } } -class WorkerSlots { - #active = 0; - readonly #waiters: (() => void)[] = []; - - acquire(): SlotHandle { - if (this.#active < MAX_RELAYS_PER_WORKER) { - this.#active += 1; - return { granted: Promise.resolve(), release: this.#releaseOnce() }; - } - let waiting = true; - let grant!: () => void; - const granted = new Promise((resolve) => { - grant = resolve; - }); - const waiter = () => { - waiting = false; - grant(); - }; - this.#waiters.push(waiter); - let released = false; - return { - granted, - release: () => { - if (released) return; - released = true; - if (!waiting) { - this.#free(); - return; - } - this.#waiters.splice(this.#waiters.indexOf(waiter), 1); - grant(); - }, - }; - } - - #releaseOnce(): () => void { - let released = false; - return () => { - if (released) return; - released = true; - this.#free(); - }; - } - - #free(): void { - const next = this.#waiters.shift(); - if (next === undefined) this.#active -= 1; - else next(); - } -} - -interface SlotHandle { - readonly granted: Promise; - readonly release: () => void; -} - interface ExchangeInit { readonly call: GatewayRelayCall; readonly client: () => GatewayWorkerClient | undefined; readonly deadlineMs: number; readonly resolve: (response: Response) => void; readonly reject: (error: unknown) => void; - readonly slots: WorkerSlots; readonly workerId: string; } class Exchange { readonly #relayId = crypto.randomUUID(); + readonly #opening = new AbortController(); #client: GatewayWorkerClient | undefined; - #slot: SlotHandle | undefined; - #timer: ReturnType | undefined; + #channel: LinkChannel | undefined; #reader: ReadableStreamDefaultReader | undefined; + #ahead: Promise> | undefined; + #timer: ReturnType | undefined; + #callerBody: ReadableStreamDefaultReader | undefined; #requestSent = false; #cancelSent = false; #done = false; #headed = false; + #answered = false; + #peerAborted = false; #bodyController: ReadableStreamDefaultController | undefined; - #wakeBody: (() => void) | undefined; - readonly #chunks: Uint8Array[] = []; - #unreadBytes = 0; - #bodyEnded = false; readonly #abortListener = () => this.#fail(this.init.call.request.signal.reason); constructor(private readonly init: ExchangeInit) {} @@ -159,26 +92,33 @@ class Exchange { } async #run(): Promise { - const slot = this.init.slots.acquire(); - this.#slot = slot; - await slot.granted; - if (this.#done) return; const client = this.init.client(); if (client === undefined) { - this.#fail( - new DispatchError("WORKER_UNREACHABLE", `Worker ${this.init.workerId} is not reachable`, { - workerId: this.init.workerId, - }), - ); + this.#fail(this.#unreachable()); return; } this.#client = client; + let channel: LinkChannel; + try { + channel = await client.openChannel({ signal: this.#opening.signal }); + } catch (error: unknown) { + this.#fail(error instanceof DispatchError ? error : this.#unreachable()); + return; + } + if (this.#done) { + channel.abort(); + return; + } + this.#channel = channel; + this.#reader = channel.readable.getReader(); + this.#look(); const { request } = this.init.call; const body = request.body; this.#requestSent = true; client .relayRequest( { + channel: channel.id, hasBody: body !== null, headers: relayHeaderPairs(request.headers, { dropCredentials: true }), method: request.method as RelayMethod, @@ -189,7 +129,6 @@ class Exchange { ...(this.init.call.leaseId === undefined ? {} : { leaseId: this.init.call.leaseId }), }, { - onRelayChunk: (chunk) => this.#onChunk(chunk), onRelayHead: (head) => this.#onHead(head.status, head.headers), onRelayInvalid: () => this.#invalid(), }, @@ -198,49 +137,47 @@ class Exchange { (answer) => this.#onAnswer(answer), (error: unknown) => this.#onCallError(error), ); - if (body !== null) await this.#upload(client, body); + await this.#upload(channel, body); } - async #upload(client: GatewayWorkerClient, body: ReadableStream): Promise { + async #upload(channel: LinkChannel, body: ReadableStream | null): Promise { + const writer = channel.writable.getWriter(); + if (body === null) { + await writer.close().catch(() => undefined); + return; + } const reader = body.getReader(); - this.#reader = reader; - const unanswered = new Set>(); - const send = async (input: Parameters[0]): Promise => { - while (unanswered.size >= MAX_BODY_CALLS_UNANSWERED) await Promise.race(unanswered); - if (this.#done) return; - const call: Promise = client.relayBody(input).then( - () => void unanswered.delete(call), - (error: unknown) => { - unanswered.delete(call); - this.#onCallError(error); - }, - ); - unanswered.add(call); - }; + this.#callerBody = reader; try { - let seq = 0; for (;;) { - while (unanswered.size >= MAX_BODY_CALLS_UNANSWERED) await Promise.race(unanswered); - if (this.#done) return; const step = await reader.read(); if (this.#done) return; if (step.done) break; - for (let offset = 0; offset < step.value.length; offset += MAX_BODY_CHUNK_BYTES) { - const piece = step.value.subarray(offset, offset + MAX_BODY_CHUNK_BYTES); - await send({ - chunk: Buffer.from(piece.buffer, piece.byteOffset, piece.byteLength).toString("base64"), - relayId: this.#relayId, - seq, - }); - seq += 1; - } + await writer.write(step.value); } - await send({ end: true, relayId: this.#relayId }); + await writer.close(); } catch (error: unknown) { + if (this.#done) return; + if (error instanceof LinkChannelError) { + // why: the worker stopped reading this direction, so the caller's body is no longer read. + if (error.reason === "stopped") reader.cancel().catch(() => undefined); + else this.#onChannelError(error); + return; + } this.#fail(error); } } + // why: a single read is kept ahead so a channel that fails before the head is seen without anyone reading the body. + #look(): Promise> { + if (this.#ahead === undefined) { + const read = (this.#reader as ReadableStreamDefaultReader).read(); + read.catch((error: unknown) => this.#onChannelError(error)); + this.#ahead = read; + } + return this.#ahead; + } + #onHead(status: number, headers: readonly (readonly [string, string])[]): void { if (this.#done) return; if (this.#headed) { @@ -259,6 +196,7 @@ class Exchange { const method = this.init.call.request.method; if (method === "HEAD" || NO_BODY_STATUSES.has(status)) { this.init.resolve(new Response(null, { headers: responseHeaders, status })); + void this.#drain(); return; } const stream = new ReadableStream( @@ -275,43 +213,37 @@ class Exchange { } async #pull(controller: ReadableStreamDefaultController): Promise { - for (;;) { - const chunk = this.#chunks.shift(); - if (chunk !== undefined) { - this.#unreadBytes -= chunk.length; - controller.enqueue(chunk); - return; - } - if (this.#bodyEnded) { - controller.close(); - return; - } - if (this.#done) return; - await new Promise((resolve) => { - this.#wakeBody = resolve; - }); + let step: ReadableStreamReadResult; + try { + step = await this.#look(); + } catch { + return; } - } - - #onChunk(chunk: string): void { + this.#ahead = undefined; if (this.#done) return; - if (!this.#headed) { - this.#invalid(); + if (step.done) { + controller.close(); + this.#finish(); return; } - const bytes = new Uint8Array(Buffer.from(chunk, "base64")); - this.#chunks.push(bytes); - this.#unreadBytes += bytes.length; - if (this.#unreadBytes > MAX_UNREAD_BYTES) { - this.#fail( - new DispatchError( - "INTERNAL", - `the reader of worker ${this.init.workerId}'s relayed response fell behind: more than 64 MiB was buffered`, - ), - ); - return; + controller.enqueue(step.value); + } + + // why: a response with no body still ends with the channel's end, which frees the channel and the deadline. + async #drain(): Promise { + try { + for (;;) { + const step = await this.#look(); + this.#ahead = undefined; + if (this.#done) return; + if (step.done) { + this.#finish(); + return; + } + } + } catch { + // why: a failed channel is reported by `#onChannelError`. } - this.#wake(); } #invalid(): void { @@ -320,8 +252,69 @@ class Exchange { ); } + #unreachable(): DispatchError { + return new DispatchError( + "WORKER_UNREACHABLE", + `Worker ${this.init.workerId} is not reachable`, + { + workerId: this.init.workerId, + }, + ); + } + + #onChannelError(error: unknown): void { + if (this.#done) return; + const { workerId } = this.init; + if (!(error instanceof LinkChannelError)) { + this.#fail(error); + return; + } + switch (error.reason) { + case "aborted": + // why: the worker's `relay.request` answer says why it aborted; the deadline ends the wait when none comes. + this.#peerAborted = true; + if (this.#answered) this.#fail(this.#endedEarly()); + return; + case "closed": + this.#fail(this.#unreachable()); + return; + case "not-accepted": + this.#fail( + new DispatchError( + "WORKER_UNREACHABLE", + `worker ${workerId} did not take the relayed request within 30 s`, + { workerId }, + ), + ); + return; + case "stalled": + this.#fail( + new DispatchError( + "INTERNAL", + this.#headed + ? `the reader of worker ${workerId}'s relayed response fell behind for 60 s` + : `worker ${workerId} did not read the relayed request body for 60 s`, + ), + ); + return; + default: + this.#invalid(); + } + } + + #endedEarly(): DispatchError { + const { workerId } = this.init; + return this.#headed + ? new DispatchError("INTERNAL", `worker ${workerId} ended the relayed response early`) + : new DispatchError("INTERNAL", `worker ${workerId} ended the relay without a response`); + } + #onAnswer(answer: { readonly cancelled?: true | undefined }): void { if (this.#done) return; + if (this.#peerAborted) { + this.#fail(this.#endedEarly()); + return; + } if (answer.cancelled === true || !this.#headed) { this.#fail( new DispatchError( @@ -331,9 +324,8 @@ class Exchange { ); return; } - this.#bodyEnded = true; - this.#wake(); - this.#finish(); + // why: the body ends at the channel's end, not at this answer, which may overtake the body's last bytes. + this.#answered = true; } #onCallError(error: unknown): void { @@ -353,17 +345,17 @@ class Exchange { #abandon(): void { if (this.#done) return; this.#sendCancel(); + this.#channel?.abort(); this.#finish(); } #fail(error: unknown): void { if (this.#done) return; this.#sendCancel(); - if (this.#headed) { - this.#chunks.length = 0; - this.#unreadBytes = 0; - this.#bodyController?.error(error); - } else this.init.reject(error); + this.#opening.abort(error); + this.#channel?.abort(); + if (this.#headed) this.#bodyController?.error(error); + else this.init.reject(error); this.#finish(); } @@ -373,19 +365,11 @@ class Exchange { this.#client.relayCancel({ relayId: this.#relayId }).catch(() => undefined); } - #wake(): void { - const wake = this.#wakeBody; - this.#wakeBody = undefined; - wake?.(); - } - #finish(): void { if (this.#done) return; this.#done = true; if (this.#timer !== undefined) clearTimeout(this.#timer); this.init.call.request.signal.removeEventListener("abort", this.#abortListener); - this.#reader?.cancel().catch(() => undefined); - this.#slot?.release(); - this.#wake(); + this.#callerBody?.cancel().catch(() => undefined); } } diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index 6250c3d47..2bfdf5724 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -1207,7 +1207,7 @@ describe("GatewayService", () => { min: PROTOCOL_VERSION_RANGE.max - 1, max: PROTOCOL_VERSION_RANGE.max - 1, }; - expect(PROTOCOL_VERSION_RANGE.max).toBe(33); + expect(PROTOCOL_VERSION_RANGE.max).toBe(34); expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, previous)).toBeUndefined(); const harness = fleet(); await harness.service.start(); diff --git a/src/gateway/service.ts b/src/gateway/service.ts index 375f3a9f3..bfc07946f 100644 --- a/src/gateway/service.ts +++ b/src/gateway/service.ts @@ -19,6 +19,7 @@ import type { import { WORKER_VIEW_REFRESH_INTERVAL_MS } from "../contract/index.js"; import { NoopLogger, uplinkOutcome } from "../ports/index.js"; import type { DrainStore } from "./drain-store.js"; +import { createLink } from "../link/index.js"; import { WorkerLink, type WorkerClientFactory } from "./worker-link.js"; import { WorkerRegistry } from "./worker-registry.js"; @@ -247,7 +248,14 @@ export class GatewayService { }, principal: this.options.principal, registry: this.#registry, - uplink, + uplink: { + ...uplink, + connection: createLink(uplink.connection, { + clock: this.options.clock, + end: "gateway", + logger: this.#logger, + }), + }, ...(this.options.connect === undefined ? {} : { connect: this.options.connect }), }); this.#links.set(uplink.workerId, link); diff --git a/src/gateway/worker-link.ts b/src/gateway/worker-link.ts index 5f4496ecb..6b29f4b9a 100644 --- a/src/gateway/worker-link.ts +++ b/src/gateway/worker-link.ts @@ -24,7 +24,8 @@ import { } from "../contract/index.js"; import type { StatusGetOutput } from "../admin/index.js"; import { connectSimlockClient } from "../simlock-client/client.js"; -import type { AcceptedUplink, Clock, IpcConnection, Logger } from "../ports/index.js"; +import type { LinkConnection } from "../link/index.js"; +import type { AcceptedUplink, Clock, Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; import type { GatewayWorkerClient } from "./worker-client.js"; import type { WorkerGrantedDevice, WorkerRegistry } from "./worker-registry.js"; @@ -78,12 +79,12 @@ class WorkerCallTimeoutError extends Error { /** How the gateway turns an accepted uplink into a driven session. Injected so a test can * script a worker without a `DaemonServer` behind it. */ export type WorkerClientFactory = ( - connection: IpcConnection, + connection: LinkConnection, principal: string, ) => Promise; export interface WorkerLinkOptions { - readonly uplink: AcceptedUplink; + readonly uplink: Omit & { readonly connection: LinkConnection }; readonly registry: WorkerRegistry; readonly eventBus: EventBus; readonly clock: Clock; diff --git a/src/link/index.ts b/src/link/index.ts index ed110f2ab..7821dd249 100644 --- a/src/link/index.ts +++ b/src/link/index.ts @@ -12,9 +12,7 @@ import { } from "./envelope.js"; import { Scheduler } from "./scheduler.js"; -// fallow-ignore-next-line unused-export -- the link's public surface; #558 is its first user. export { LinkChannelError } from "./channel.js"; -// fallow-ignore-next-line unused-type -- the link's public surface; #558 is its first user. export type { LinkChannel, LinkChannelErrorReason } from "./channel.js"; export interface LinkConnection extends IpcConnection { diff --git a/src/link/link-channels.test.ts b/src/link/link-channels.test.ts index cf38724b2..71e10717d 100644 --- a/src/link/link-channels.test.ts +++ b/src/link/link-channels.test.ts @@ -17,13 +17,13 @@ import { RecordingLogger, settle, signal, - startWebSocketPair, TappedTransport, TYPE, writeAndClose, writeUntilBlocked, type LinkPair, -} from "./test-support.js"; +} from "./testing.js"; +import { startWebSocketPair } from "./test-websocket.js"; import { FakeClock } from "../ports/index.js"; async function openPair(pair: LinkPair): Promise<{ g: LinkChannel; w: LinkChannel }> { diff --git a/src/link/link-lanes.test.ts b/src/link/link-lanes.test.ts index af0c93a51..651f50c70 100644 --- a/src/link/link-lanes.test.ts +++ b/src/link/link-lanes.test.ts @@ -1,15 +1,6 @@ import { describe, expect, it } from "vitest"; -import { - KiB, - linkPair, - MiB, - pattern, - settle, - signal, - TYPE, - type LinkPair, -} from "./test-support.js"; +import { KiB, linkPair, MiB, pattern, settle, signal, TYPE, type LinkPair } from "./testing.js"; async function openPair(pair: LinkPair) { const g = await pair.gateway.openChannel({ signal: signal() }); diff --git a/src/link/link-messages.test.ts b/src/link/link-messages.test.ts index a390267a2..b70685a88 100644 --- a/src/link/link-messages.test.ts +++ b/src/link/link-messages.test.ts @@ -7,9 +7,9 @@ import { linkPair, settle, signal, - startWebSocketPair, RecordingLogger, -} from "./test-support.js"; +} from "./testing.js"; +import { startWebSocketPair } from "./test-websocket.js"; import { FakeClock } from "../ports/index.js"; const MESSAGES = ['{"id":1,"type":"hello"}\n', "second é — ünïcode\n", "third\n"]; diff --git a/src/link/link-rules.test.ts b/src/link/link-rules.test.ts index 7ec68ee32..c2147ec16 100644 --- a/src/link/link-rules.test.ts +++ b/src/link/link-rules.test.ts @@ -14,7 +14,7 @@ import { settle, TYPE, type RawPeer, -} from "./test-support.js"; +} from "./testing.js"; async function acceptRaw(peer: RawPeer, number = 2, id = "raw-a") { await peer.raw.writeBinary(openEnvelope(number, id)); diff --git a/src/link/test-websocket.ts b/src/link/test-websocket.ts new file mode 100644 index 000000000..b42fbe154 --- /dev/null +++ b/src/link/test-websocket.ts @@ -0,0 +1,43 @@ +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +import type { UplinkTransportConnection } from "../ports/index.js"; +import { WebSocketUplinkConnector, WebSocketUplinkListenerFactory } from "../ports/testing.js"; + +export async function startWebSocketPair(): Promise<{ + worker: UplinkTransportConnection; + gateway: UplinkTransportConnection; + close(): Promise; +}> { + const factory = new WebSocketUplinkListenerFactory(); + let accepted: ((connection: UplinkTransportConnection) => void) | undefined; + const acceptedConnection = new Promise((resolve) => { + accepted = resolve; + }); + const listener = await factory.listen({ + accept: (uplink) => accepted?.(uplink.connection), + authenticate: () => Promise.resolve("accept"), + }); + const server: Server = createServer((_request, response) => { + response.writeHead(404).end(); + }); + factory.attach(server); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + const worker = await new WebSocketUplinkConnector().connect({ + token: "join", + url: `ws://127.0.0.1:${String(port)}`, + workerId: "wrk_1", + }); + const gateway = await acceptedConnection; + return { + close: async () => { + await worker.close(); + await gateway.close(); + await listener.close(); + await new Promise((resolve) => server.close(() => resolve())); + }, + gateway, + worker, + }; +} diff --git a/src/link/test-support.ts b/src/link/testing.ts similarity index 87% rename from src/link/test-support.ts rename to src/link/testing.ts index 84ea2532b..61a819f4a 100644 --- a/src/link/test-support.ts +++ b/src/link/testing.ts @@ -1,6 +1,4 @@ import { createHash } from "node:crypto"; -import { createServer, type Server } from "node:http"; -import type { AddressInfo } from "node:net"; import { createConnectionPair, @@ -9,7 +7,6 @@ import { type MemoryTransportConnection, type UplinkTransportConnection, } from "../ports/index.js"; -import { WebSocketUplinkConnector, WebSocketUplinkListenerFactory } from "../ports/testing.js"; import { createLink, type LinkChannel, type LinkConnection } from "./index.js"; export const KiB = 1024; @@ -251,44 +248,6 @@ export function linkWithRawPeer(): RawPeer { return { clock, link, log, linkText, raw, received, receivedText, tap }; } -export async function startWebSocketPair(): Promise<{ - worker: UplinkTransportConnection; - gateway: UplinkTransportConnection; - close(): Promise; -}> { - const factory = new WebSocketUplinkListenerFactory(); - let accepted: ((connection: UplinkTransportConnection) => void) | undefined; - const acceptedConnection = new Promise((resolve) => { - accepted = resolve; - }); - const listener = await factory.listen({ - accept: (uplink) => accepted?.(uplink.connection), - authenticate: () => Promise.resolve("accept"), - }); - const server: Server = createServer((_request, response) => { - response.writeHead(404).end(); - }); - factory.attach(server); - await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); - const { port } = server.address() as AddressInfo; - const worker = await new WebSocketUplinkConnector().connect({ - token: "join", - url: `ws://127.0.0.1:${String(port)}`, - workerId: "wrk_1", - }); - const gateway = await acceptedConnection; - return { - close: async () => { - await worker.close(); - await gateway.close(); - await listener.close(); - await new Promise((resolve) => server.close(() => resolve())); - }, - gateway, - worker, - }; -} - export function pattern(offset: number, size: number): Uint8Array { const bytes = new Uint8Array(size); for (let i = 0; i < size; i += 1) bytes[i] = (offset + i) % 251; diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index 1843a0f99..5b3f4d45f 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -24,6 +24,7 @@ import { type OperationName, type Role, } from "../contract/index.js"; +import type { LinkChannel, LinkConnection } from "../link/index.js"; import type { IpcConnection, IpcConnector } from "../ports/index.js"; import { SimlockWire, WireCallError, type CallHooks, type LeaseScopedPush } from "./wire.js"; import type { @@ -311,9 +312,10 @@ type OperationOutput = z.infer<(typeof OPERATIONS)[N export interface RelayClientMethods { relayRequest( input: OperationInput<"relay.request">, - hooks: Pick, + hooks: Pick, ): Promise>; - relayBody(input: OperationInput<"relay.body">): Promise>; + // why: rejects on a connection that holds no link, since a channel is a link's (ADR 0028). + openChannel(options: { readonly signal: AbortSignal }): Promise; relayCancel(input: OperationInput<"relay.cancel">): Promise>; } @@ -351,7 +353,13 @@ export async function connectSimlockClient( await connection.close(); throw error; } - const impl = new SimlockClientImpl(wire, hello.role, hello.principal, hello.daemonVersion); + const impl = new SimlockClientImpl( + wire, + hello.role, + hello.principal, + hello.daemonVersion, + isLinkConnection(connection) ? connection : undefined, + ); return admin ? impl.asAdmin() : impl; } @@ -444,12 +452,16 @@ function buildDegradedClient( addDevice: () => rejected(), removeDevice: () => rejected(), relayRequest: () => rejected(), - relayBody: () => rejected(), + openChannel: () => rejected(), relayCancel: () => rejected(), }; return client; } +function isLinkConnection(connection: IpcConnection): connection is LinkConnection { + return typeof (connection as Partial).openChannel === "function"; +} + async function resolveConnection(options: ConnectOptions): Promise { if (options.connection !== undefined) return options.connection; if (options.connector !== undefined && options.endpoint !== undefined) { @@ -462,6 +474,7 @@ async function resolveConnection(options: ConnectOptions): Promise void>(); readonly #deviceUnhealthyListeners = new Set<(push: DeviceUnhealthyPush) => void>(); readonly #deviceRecoveredListeners = new Set<(push: DeviceRecoveredPush) => void>(); @@ -473,8 +486,10 @@ class SimlockClientImpl { readonly role: Role, readonly principal: string, readonly daemonVersion: string, + link?: LinkConnection, ) { this.#wire = wire; + this.#link = link; wire.onLeaseScopedPush((push) => this.#handleLeaseScopedPush(push)); wire.onDeath((error) => this.#handleConnectionLost(error)); } @@ -578,14 +593,16 @@ class SimlockClientImpl { async relayRequest( input: OperationInput<"relay.request">, - hooks: Pick, + hooks: Pick, ): Promise> { const payload = await this.#callRaw("relay.request", input, hooks); return this.#parseOutput("relay.request", payload); } - relayBody(input: OperationInput<"relay.body">): Promise> { - return this.#call("relay.body", input); + openChannel(options: { readonly signal: AbortSignal }): Promise { + const link = this.#link; + if (link === undefined) return Promise.reject(new Error("The connection carries no link")); + return link.openChannel(options); } relayCancel(input: OperationInput<"relay.cancel">): Promise> { diff --git a/src/simlock-client/wire.ts b/src/simlock-client/wire.ts index b4fd72759..166500cbd 100644 --- a/src/simlock-client/wire.ts +++ b/src/simlock-client/wire.ts @@ -56,7 +56,6 @@ export interface CallHooks { | ((progress: ComponentInstallProgress, workerId: string | undefined) => void) | undefined; readonly onRelayHead?: ((head: RelayHead) => void) | undefined; - readonly onRelayChunk?: ((chunk: string) => void) | undefined; readonly onRelayInvalid?: (() => void) | undefined; } @@ -331,22 +330,15 @@ export class SimlockWire { this.#pending.get(id)?.onComponentProgress?.(parsed.data.progress, parsed.data.workerId); return; } - case "relay-head": - case "relay-chunk": { + case "relay-head": { // why: routed by `requestId` before the rest of the push is checked, so a push that breaks its schema still reaches its relay as invalid instead of being dropped (ADR 0026). const id = relayRequestId(payload); const pending = id === undefined ? undefined : this.#pending.get(id); if (pending === undefined) return; - if (push === "relay-head") { - const parsed = PUSH_SCHEMAS["relay-head"].safeParse(payload); - if (parsed.success) { - pending.onRelayHead?.({ headers: parsed.data.headers, status: parsed.data.status }); - } else pending.onRelayInvalid?.(); - } else { - const parsed = PUSH_SCHEMAS["relay-chunk"].safeParse(payload); - if (parsed.success) pending.onRelayChunk?.(parsed.data.chunk); - else pending.onRelayInvalid?.(); - } + const parsed = PUSH_SCHEMAS["relay-head"].safeParse(payload); + if (parsed.success) { + pending.onRelayHead?.({ headers: parsed.data.headers, status: parsed.data.status }); + } else pending.onRelayInvalid?.(); return; } case "lease-lost": {