From 43b6585b76f1b60d9d615de5874bcc176320d536 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 14:32:16 +0200 Subject: [PATCH 1/8] test: the uplink carries byte channels beside its messages, and small messages go first (#556) --- src/daemon/gateway-uplink.test.ts | 7 +- src/link/index.ts | 65 +++ src/link/link-channels.test.ts | 707 +++++++++++++++++++++++++++++ src/link/link-lanes.test.ts | 100 ++++ src/link/link-messages.test.ts | 166 +++++++ src/link/link-rules.test.ts | 236 ++++++++++ src/link/test-support.ts | 384 ++++++++++++++++ src/ports/index.ts | 2 + src/ports/uplink-websocket.test.ts | 108 ++++- src/ports/uplink-websocket.ts | 19 +- src/ports/uplink.test.ts | 53 +++ src/ports/uplink.ts | 41 +- 12 files changed, 1874 insertions(+), 14 deletions(-) create mode 100644 src/link/index.ts create mode 100644 src/link/link-channels.test.ts create mode 100644 src/link/link-lanes.test.ts create mode 100644 src/link/link-messages.test.ts create mode 100644 src/link/link-rules.test.ts create mode 100644 src/link/test-support.ts diff --git a/src/daemon/gateway-uplink.test.ts b/src/daemon/gateway-uplink.test.ts index 7478bc22e..15a484654 100644 --- a/src/daemon/gateway-uplink.test.ts +++ b/src/daemon/gateway-uplink.test.ts @@ -8,6 +8,7 @@ import { type IpcConnection, type UplinkConnector, type UplinkDialOptions, + type UplinkTransportConnection, } from "../ports/index.js"; import { GatewayUplink } from "./gateway-uplink.js"; @@ -22,7 +23,7 @@ class ScriptedConnector implements UplinkConnector { this.#outcomes.push(...outcomes); } - async connect(options: UplinkDialOptions): Promise { + async connect(options: UplinkDialOptions): Promise { this.dials.push(options); const outcome = this.#outcomes.shift() ?? "connect"; if (outcome !== "connect") throw outcome; @@ -260,8 +261,8 @@ describe("GatewayUplink", () => { }); it("closes a connection that lands after a stop rather than serving it", async () => { - let release: ((connection: IpcConnection) => void) | undefined; - const pending = new Promise((resolve) => { + let release: ((connection: UplinkTransportConnection) => void) | undefined; + const pending = new Promise((resolve) => { release = resolve; }); const connector: UplinkConnector = { connect: async () => pending }; diff --git a/src/link/index.ts b/src/link/index.ts new file mode 100644 index 000000000..51cfd0778 --- /dev/null +++ b/src/link/index.ts @@ -0,0 +1,65 @@ +import type { Clock, IpcConnection, Logger, UplinkTransportConnection } from "../ports/index.js"; + +export type LinkChannelErrorReason = + | "aborted" + | "invalid" + | "not-accepted" + | "stalled" + | "closed" + | "stopped"; + +export class LinkChannelError extends Error { + constructor( + readonly reason: LinkChannelErrorReason, + message?: string, + ) { + super(message ?? reason); + this.name = "LinkChannelError"; + } +} + +export interface LinkChannel { + readonly id: string; + readonly readable: ReadableStream; + readonly writable: WritableStream; + abort(reason?: string): void; + readonly credit: number; + whenCredit(): Promise; +} + +export interface LinkConnection extends IpcConnection { + openChannel(options: { readonly signal: AbortSignal }): Promise; + acceptChannel(id: string): LinkChannel; +} + +export interface LinkOptions { + readonly end: "worker" | "gateway"; + readonly clock: Clock; + readonly logger: Logger; + readonly firstChannelNumber?: number; +} + +export function createLink( + _transport: UplinkTransportConnection, + _options: LinkOptions, +): LinkConnection { + return { + closed: false, + onData: () => () => {}, + onClose: () => () => {}, + onError: () => () => {}, + write: async () => {}, + close: async () => {}, + openChannel: () => Promise.reject(new Error("the link module is not built yet")), + acceptChannel: (id) => ({ + abort: () => {}, + credit: 0, + id, + readable: new ReadableStream({ + start: (controller) => controller.error(new LinkChannelError("closed")), + }), + whenCredit: () => Promise.resolve(), + writable: new WritableStream(), + }), + }; +} diff --git a/src/link/link-channels.test.ts b/src/link/link-channels.test.ts new file mode 100644 index 000000000..eb61481d8 --- /dev/null +++ b/src/link/link-channels.test.ts @@ -0,0 +1,707 @@ +import { afterEach, describe, expect, it } from "vitest"; + +import { createLink, type LinkChannel } from "./index.js"; +import { + drain, + endChannel, + errorOfRead, + errorOfWritable, + KiB, + linkPair, + MiB, + pattern, + patternHash, + pump, + readAll, + RecordingLogger, + settle, + signal, + startWebSocketPair, + TappedTransport, + TYPE, + writeAndClose, + writeUntilBlocked, + type LinkPair, +} from "./test-support.js"; +import { FakeClock } from "../ports/index.js"; + +async function openPair(pair: LinkPair): Promise<{ g: LinkChannel; w: LinkChannel }> { + const g = await pair.gateway.openChannel({ signal: signal() }); + await settle(); + return { g, w: pair.worker.acceptChannel(g.id) }; +} + +async function readAtLeast(reader: ReadableStreamDefaultReader, bytes: number) { + let total = 0; + while (total < bytes) { + const { done, value } = await reader.read(); + if (done) break; + total += value.length; + } + return total; +} + +async function fillWindow(writable: WritableStream) { + const writer = writable.getWriter(); + for (let i = 0; i < 64; i += 1) await writer.write(pattern(i * 64 * KiB, 64 * KiB)); + return writer; +} + +describe("link byte channels: transfer", () => { + const cleanups: Array<() => Promise> = []; + afterEach(async () => { + await Promise.all(cleanups.splice(0).map((cleanup) => cleanup())); + }); + + async function realLinks() { + const sockets = await startWebSocketPair(); + cleanups.push(() => sockets.close()); + const clock = new FakeClock(0); + const worker = createLink(sockets.worker, { + clock, + end: "worker", + logger: new RecordingLogger(), + }); + const gateway = createLink(sockets.gateway, { + clock, + end: "gateway", + logger: new RecordingLogger(), + }); + return { gateway, worker }; + } + + it("20 MiB written to a channel arrives byte for byte at the accepted channel, each way at once, over the real WebSocket", async () => { + const { gateway, worker } = await realLinks(); + const g = await gateway.openChannel({ signal: signal() }); + await settle(); + const w = worker.acceptChannel(g.id); + const total = 20 * MiB; + + const [, atWorker, , atGateway] = await Promise.all([ + pump(g.writable, total), + drain(w.readable), + pump(w.writable, total), + drain(g.readable), + ]); + + const expected = { hash: patternHash(total), length: total }; + expect(atWorker).toEqual(expected); + expect(atGateway).toEqual(expected); + }, 60_000); + + it("over the real WebSocket, a 20 MiB channel transfer puts at most 20.2 MiB on the socket, in binary messages", async () => { + const sockets = await startWebSocketPair(); + cleanups.push(() => sockets.close()); + const tapped = new TappedTransport(sockets.gateway); + const clock = new FakeClock(0); + const worker = createLink(sockets.worker, { + clock, + end: "worker", + logger: new RecordingLogger(), + }); + const gateway = createLink(tapped, { clock, end: "gateway", logger: new RecordingLogger() }); + const g = await gateway.openChannel({ signal: signal() }); + await settle(); + const w = worker.acceptChannel(g.id); + + await Promise.all([pump(g.writable, 20 * MiB), drain(w.readable)]); + + const onSocket = tapped.sent.reduce( + (sum, entry) => sum + (entry.kind === "binary" ? entry.size : Number.NaN), + 0, + ); + expect(onSocket).toBeGreaterThanOrEqual(20 * MiB); + expect(onSocket).toBeLessThanOrEqual(20.2 * MiB); + }, 60_000); + + it("a text message written right after openChannel resolves never reaches the peer before the channel's OPEN, even with the transport held", async () => { + const pair = linkPair(); + pair.gatewayEnd.hold(); + const failures: unknown[] = []; + const seen: string[] = []; + let opened: LinkChannel | undefined; + pair.worker.onData((chunk) => { + try { + pair.worker.acceptChannel(opened?.id ?? "unopened"); + seen.push(chunk); + } catch (error: unknown) { + failures.push(error); + } + }); + opened = await pair.gateway.openChannel({ signal: signal() }); + + const write = pair.gateway.write("after-open\n"); + pair.gatewayEnd.release(); + await write; + await settle(); + + expect(failures).toEqual([]); + expect(seen).toEqual(["after-open\n"]); + const order = pair.gatewayTap.sent.map((entry) => + entry.kind === "text" ? "text" : String(entry.envelope.type), + ); + expect(order.indexOf(String(TYPE.OPEN))).toBeLessThan(order.indexOf("text")); + }); + + it("bytes written right after openChannel, before the peer accepts, arrive once it accepts", async () => { + const pair = linkPair(); + const g = await pair.gateway.openChannel({ signal: signal() }); + await writeAndClose(g, pattern(0, 100 * KiB)); + await settle(); + + const w = pair.worker.acceptChannel(g.id); + + await expect(readAll(w.readable)).resolves.toEqual(pattern(0, 100 * KiB)); + }); + + it("with credit left but the bulk lane held, the writable takes the chunks that fit in credit and then at most 64 KiB more before its writer waits", async () => { + const pair = linkPair(); + const { g } = await openPair(pair); + pair.gatewayEnd.hold(); + const credit = g.credit; + expect(credit).toBe(4 * MiB); + + const accepted = await writeUntilBlocked(g.writable.getWriter()); + + expect(accepted).toBeGreaterThanOrEqual(credit); + expect(accepted).toBeLessThanOrEqual(credit + 64 * KiB); + }); + + it("a writer whose peer never accepts stops after 4 MiB; 30 s after the open its streams error with not-accepted, and the peer's acceptChannel for that id then throws", async () => { + const pair = linkPair(); + const g = await pair.gateway.openChannel({ signal: signal() }); + await settle(); + const writer = g.writable.getWriter(); + + const accepted = await writeUntilBlocked(writer); + expect(accepted).toBeGreaterThanOrEqual(4 * MiB); + expect(accepted).toBeLessThanOrEqual(4 * MiB + 64 * KiB); + pair.clock.advance(30_000); + await settle(); + + await expect(writer.closed).rejects.toMatchObject({ reason: "not-accepted" }); + await expect(errorOfRead(g.readable)).resolves.toMatchObject({ reason: "not-accepted" }); + expect(() => pair.worker.acceptChannel(g.id)).toThrow(); + }); + + it("a reader that stops reading holds its writer after 4 MiB unread, and reading again lets it go on", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + const writer = g.writable.getWriter(); + + const first = await writeUntilBlocked(writer); + expect(first).toBeGreaterThanOrEqual(4 * MiB); + expect(first).toBeLessThanOrEqual(4 * MiB + 64 * KiB); + expect(await readAtLeast(w.readable.getReader(), MiB)).toBeGreaterThanOrEqual(MiB); + await settle(); + const more = await writeUntilBlocked(writer); + + expect(more).toBeGreaterThan(0); + }); + + it("a single 20 MiB write goes through in parts as credit arrives, and resolves once all of it is taken", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + const writer = g.writable.getWriter(); + let resolved = false; + + const write = writer.write(pattern(0, 20 * MiB)).then(() => { + resolved = true; + }); + await settle(); + expect(resolved).toBe(false); + const received = drain(w.readable); + await write; + await writer.close(); + + expect(await received).toEqual({ hash: patternHash(20 * MiB), length: 20 * MiB }); + }); + + it("one channel's stalled reader does not slow another channel on the same link", async () => { + const pair = linkPair(); + const stalled = await openPair(pair); + const live = await openPair(pair); + await writeUntilBlocked(stalled.g.writable.getWriter()); + + const outcome = await Promise.race([ + Promise.all([pump(live.g.writable, 2 * MiB), drain(live.w.readable)]).then( + ([, received]) => received, + ), + new Promise((resolve) => + setTimeout(() => resolve("stuck behind the stalled channel"), 10_000), + ), + ]); + + expect(outcome).toEqual({ hash: patternHash(2 * MiB), length: 2 * MiB }); + }); +}); + +describe("link byte channels: credit and stalls", () => { + it("a write that waits 60 s with no credit arriving errors both sides' streams with stalled", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + const writer = g.writable.getWriter(); + await writeUntilBlocked(writer); + + pair.clock.advance(60_000); + await settle(); + + await expect(writer.closed).rejects.toMatchObject({ reason: "stalled" }); + await expect(errorOfRead(g.readable)).resolves.toMatchObject({ reason: "stalled" }); + await expect(errorOfRead(w.readable)).resolves.toMatchObject({ reason: "stalled" }); + await expect(errorOfWritable(w.writable)).resolves.toMatchObject({ reason: "stalled" }); + }); + + it("a reader that reads 64 KiB every 50 s keeps a 10 MiB transfer going without a reset", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + const total = 10 * MiB; + const sending = pump(g.writable, total); + const reader = w.readable.getReader(); + let received = 0; + + while (received < total) { + const { done, value } = await reader.read(); + if (done) break; + received += value.length; + pair.clock.advance(50_000); + await settle(); + } + await sending; + + expect(received).toBe(total); + expect(pair.gatewayLog.problems()).toEqual([]); + expect(pair.workerLog.problems()).toEqual([]); + }, 60_000); + + it("credit counts down as the writer writes and up as the peer reads", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + expect(g.credit).toBe(4 * MiB); + const writer = g.writable.getWriter(); + + for (let i = 0; i < 16; i += 1) await writer.write(pattern(i * 64 * KiB, 64 * KiB)); + expect(g.credit).toBe(3 * MiB); + await readAtLeast(w.readable.getReader(), MiB); + await settle(); + + expect(g.credit).toBeGreaterThan(3 * MiB); + expect(g.credit).toBeLessThanOrEqual(4 * MiB); + }); + + it("whenCredit() resolves when credit arrives", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + await fillWindow(g.writable); + expect(g.credit).toBe(0); + let resolved = false; + const waiting = g.whenCredit().then(() => { + resolved = true; + }); + await settle(); + expect(resolved).toBe(false); + + await readAtLeast(w.readable.getReader(), 64 * KiB); + await waiting; + + expect(g.credit).toBeGreaterThan(0); + }); + + it("whenCredit() rejects when the channel fails", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + await fillWindow(g.writable); + const failed = expect(g.whenCredit()).rejects.toMatchObject({ reason: "aborted" }); + + w.abort(); + + await failed; + }); + + it("whenCredit() rejects when the peer stops that direction", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + await fillWindow(g.writable); + const stopped = expect(g.whenCredit()).rejects.toMatchObject({ reason: "stopped" }); + + await w.readable.cancel(); + + await stopped; + }); + + it("whenCredit() rejects when this side closes its own writable", async () => { + const pair = linkPair(); + const { g } = await openPair(pair); + const writer = await fillWindow(g.writable); + const ended = expect(g.whenCredit()).rejects.toBeInstanceOf(Error); + + await writer.close(); + + await ended; + }); + + it("a whenCredit() pending 60 s, with the peer holding every byte and granting nothing, errors the channel stalled", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + await fillWindow(g.writable); + const waiting = expect(g.whenCredit()).rejects.toMatchObject({ reason: "stalled" }); + + pair.clock.advance(60_000); + await waiting; + + await expect(errorOfRead(w.readable)).resolves.toMatchObject({ reason: "stalled" }); + }); + + it("with the transport held for 90 s and a write waiting behind it, the channel is not reset", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + const writer = g.writable.getWriter(); + pair.gatewayEnd.hold(); + const write = writer.write(pattern(0, 8 * MiB)); + await settle(); + + pair.clock.advance(90_000); + await settle(); + pair.gatewayEnd.release(); + const received = drain(w.readable); + await write; + await writer.close(); + + expect(await received).toEqual({ hash: patternHash(8 * MiB), length: 8 * MiB }); + expect(pair.gatewayLog.problems()).toEqual([]); + }); + + it("a writer that writes no more than credit, against a reader that reads nothing for 10 minutes, is never reset", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + const writer = await fillWindow(g.writable); + + pair.clock.advance(600_000); + await settle(); + await writer.close(); + + await expect(drain(w.readable)).resolves.toEqual({ + hash: patternHash(4 * MiB), + length: 4 * MiB, + }); + }); + + it("a channel whose peer sends nothing for 10 minutes, with no write waiting, stays open", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + + pair.clock.advance(600_000); + await settle(); + await writeAndClose(g, pattern(0, 10)); + + await expect(readAll(w.readable)).resolves.toEqual(pattern(0, 10)); + }); +}); + +describe("link byte channels: ending", () => { + it("closing a writable ends the peer's readable", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + + await writeAndClose(g, pattern(0, 1000)); + + await expect(readAll(w.readable)).resolves.toEqual(pattern(0, 1000)); + }); + + it("cancelling a readable errors the peer's writable with stopped, and the other direction still carries bytes to its end", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + const writer = g.writable.getWriter(); + + await w.readable.cancel(); + await settle(); + + await expect(writer.closed).rejects.toMatchObject({ reason: "stopped" }); + await writeAndClose(w, pattern(0, 500)); + await expect(readAll(g.readable)).resolves.toEqual(pattern(0, 500)); + }); + + it("DATA still in flight when a readable is cancelled is dropped without a reset, and the peer's acknowledging END arrives", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + const writer = g.writable.getWriter(); + pair.gatewayEnd.hold(); + await writer.write(pattern(0, 10 * KiB)); + await settle(); + const before = pair.gatewayTap.binaries(TYPE.DATA).length; + expect(before).toBe(1); + + await w.readable.cancel(); + await settle(); + pair.gatewayEnd.release(); + await settle(); + + expect(pair.workerTap.binaries(TYPE.RESET)).toEqual([]); + expect(pair.gatewayTap.binaries(TYPE.RESET)).toEqual([]); + expect(pair.workerLog.problems()).toEqual([]); + const types = pair.gatewayTap.binaries().map((entry) => entry.type); + expect(types.indexOf(TYPE.END)).toBeGreaterThan(types.indexOf(TYPE.DATA)); + }); + + it("a STOP and an END for the same direction crossing on the wire end that direction on both sides with no reset and no second END", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + pair.gatewayEnd.hold(); + pair.workerEnd.hold(); + const gWriter = g.writable.getWriter(); + + const closing = gWriter.close(); + void w.readable.cancel(); + await settle(); + pair.gatewayEnd.release(); + pair.workerEnd.release(); + await closing; + await settle(); + await writeAndClose(w, pattern(0, 10)); + await readAll(g.readable); + await settle(); + + expect(pair.gatewayTap.binaries(TYPE.END)).toHaveLength(1); + expect(pair.gatewayTap.binaries(TYPE.RESET)).toEqual([]); + expect(pair.workerTap.binaries(TYPE.RESET)).toEqual([]); + expect(pair.gatewayLog.problems()).toEqual([]); + expect(pair.workerLog.problems()).toEqual([]); + }); + + it("cancelling a readable after its END arrived sends nothing", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + await writeAndClose(g, pattern(0, 10)); + const reader = w.readable.getReader(); + await readAtLeast(reader, 10); + await reader.read(); + await settle(); + + await reader.cancel(); + await settle(); + + expect(pair.workerTap.binaries(TYPE.STOP)).toEqual([]); + }); + + it("abort(\"why\") on one side errors both streams on both sides with aborted; the aborting side's error message is why and the peer's carries no reason string", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + + g.abort("why"); + await settle(); + + const own = [await errorOfRead(g.readable), await errorOfWritable(g.writable)]; + const peer = [await errorOfRead(w.readable), await errorOfWritable(w.writable)]; + for (const error of own) { + expect(error).toMatchObject({ message: "why", reason: "aborted" }); + } + for (const error of peer) { + expect(error).toMatchObject({ reason: "aborted" }); + expect((error as Error).message).not.toContain("why"); + } + }); +}); + +describe("link byte channels: ids and numbers", () => { + it("acceptChannel throws for an id never opened", () => { + const pair = linkPair(); + + expect(() => pair.worker.acceptChannel("never-opened")).toThrow(); + }); + + it("acceptChannel throws for an id already accepted", async () => { + const pair = linkPair(); + const { g } = await openPair(pair); + + expect(() => pair.worker.acceptChannel(g.id)).toThrow(); + }); + + it("acceptChannel throws for an id already ended", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + await endChannel(g, w); + await settle(); + + expect(() => pair.worker.acceptChannel(g.id)).toThrow(); + }); + + it("channel ids match [A-Za-z0-9-]{1,32}, checked over 200 channels from each end", async () => { + const pair = linkPair(); + const ids: string[] = []; + + for (let i = 0; i < 200; i += 1) { + const g = await pair.gateway.openChannel({ signal: signal() }); + const w = await pair.worker.openChannel({ signal: signal() }); + ids.push(g.id, w.id); + await settle(); + const gAccepted = pair.worker.acceptChannel(g.id); + const wAccepted = pair.gateway.acceptChannel(w.id); + await Promise.all([endChannel(g, gAccepted), endChannel(w, wAccepted)]); + } + + expect(ids).toHaveLength(400); + for (const id of ids) expect(id).toMatch(/^[A-Za-z0-9-]{1,32}$/); + }, 60_000); + + it("50 channels opened at once from each end never collide", async () => { + const pair = linkPair(); + + const [fromGateway, fromWorker] = await Promise.all([ + Promise.all(Array.from({ length: 50 }, () => pair.gateway.openChannel({ signal: signal() }))), + Promise.all(Array.from({ length: 50 }, () => pair.worker.openChannel({ signal: signal() }))), + ]); + await settle(); + + const reads: Array> = []; + fromGateway.forEach((channel, index) => { + const accepted = pair.worker.acceptChannel(channel.id); + void writeAndClose(channel, new TextEncoder().encode(`g-${String(index)}`)); + reads.push( + readAll(accepted.readable).then((bytes) => { + expect(new TextDecoder().decode(bytes)).toBe(`g-${String(index)}`); + }), + ); + }); + fromWorker.forEach((channel, index) => { + const accepted = pair.gateway.acceptChannel(channel.id); + void writeAndClose(channel, new TextEncoder().encode(`w-${String(index)}`)); + reads.push( + readAll(accepted.readable).then((bytes) => { + expect(new TextDecoder().decode(bytes)).toBe(`w-${String(index)}`); + }), + ); + }); + await Promise.all(reads); + + const numbers = (tap: LinkPair["gatewayTap"]) => tap.binaries(TYPE.OPEN).map((e) => e.number); + expect(new Set(numbers(pair.gatewayTap)).size).toBe(50); + expect(new Set(numbers(pair.workerTap)).size).toBe(50); + expect(numbers(pair.gatewayTap).every((n) => n % 2 === 0)).toBe(true); + expect(numbers(pair.workerTap).every((n) => n % 2 === 1)).toBe(true); + }); + + it("200 channels opened and ended one after another each get a new number", async () => { + const pair = linkPair(); + + for (let i = 0; i < 200; i += 1) { + const { g, w } = await openPair(pair); + await writeAndClose(g, new TextEncoder().encode(`n-${String(i)}`)); + expect(new TextDecoder().decode(await readAll(w.readable))).toBe(`n-${String(i)}`); + await Promise.all([w.writable.getWriter().close(), drain(g.readable)]); + } + + const numbers = pair.gatewayTap.binaries(TYPE.OPEN).map((entry) => entry.number); + expect(numbers).toHaveLength(200); + expect(new Set(numbers).size).toBe(200); + }, 60_000); + + it("with this side's numbers exhausted, the next openChannel rejects and the link logs it", async () => { + const pair = linkPair({ gatewayFirstNumber: 0xfffffffe }); + const outcomes: string[] = []; + + for (let i = 0; i < 3; i += 1) { + outcomes.push( + await pair.gateway.openChannel({ signal: signal() }).then( + () => "opened", + () => "rejected", + ), + ); + } + + expect(outcomes.slice(1)).toEqual(["rejected", "rejected"]); + expect(pair.gatewayLog.problems().length).toBeGreaterThan(0); + }); +}); + +describe("link byte channels: the 64 channel limit", () => { + async function open64(pair: LinkPair) { + const opened: LinkChannel[] = []; + for (let i = 0; i < 64; i += 1) { + opened.push(await pair.gateway.openChannel({ signal: signal() })); + } + await settle(); + return opened.map((g) => ({ g, w: pair.worker.acceptChannel(g.id) })); + } + + it("the 65th openChannel waits, and resolves once one ends", async () => { + const pair = linkPair(); + const open = await open64(pair); + let state = "pending"; + const next = pair.gateway.openChannel({ signal: signal() }).then( + () => (state = "opened"), + () => (state = "rejected"), + ); + await settle(); + expect(state).toBe("pending"); + + await endChannel(open[0]!.g, open[0]!.w); + await next; + + expect(state).toBe("opened"); + }); + + it("the 65th openChannel rejects with the signal's reason when its signal aborts first", async () => { + const pair = linkPair(); + await open64(pair); + const controller = new AbortController(); + const reason = new Error("caller gave up"); + const next = pair.gateway.openChannel({ signal: controller.signal }); + await settle(); + + controller.abort(reason); + + await expect(next).rejects.toBe(reason); + }); + + it("the 65th openChannel rejects with closed when the connection closes", async () => { + const pair = linkPair(); + await open64(pair); + const next = expect(pair.gateway.openChannel({ signal: signal() })).rejects.toMatchObject({ + reason: "closed", + }); + await settle(); + + await pair.gateway.close(); + + await next; + }); + + it("three waiters get slots in the order they asked", async () => { + const pair = linkPair(); + const open = await open64(pair); + const order: number[] = []; + [1, 2, 3].forEach((n) => { + void pair.gateway.openChannel({ signal: signal() }).then(() => order.push(n)); + }); + await settle(); + expect(order).toEqual([]); + + await endChannel(open[0]!.g, open[0]!.w); + await settle(); + expect(order).toEqual([1]); + await endChannel(open[1]!.g, open[1]!.w); + await settle(); + expect(order).toEqual([1, 2]); + await endChannel(open[2]!.g, open[2]!.w); + await settle(); + + expect(order).toEqual([1, 2, 3]); + }); + + it("with 64 channels open, ending one and opening another at once never makes the peer see 65, even with the transport held", async () => { + const pair = linkPair(); + const open = await open64(pair); + pair.gatewayEnd.hold(); + + const next = pair.gateway.openChannel({ signal: signal() }); + const ending = endChannel(open[0]!.g, open[0]!.w); + await settle(); + pair.gatewayEnd.release(); + await ending; + const channel = await next; + await settle(); + + expect(pair.workerLog.problems()).toEqual([]); + expect(() => pair.worker.acceptChannel(channel.id)).not.toThrow(); + }); +}); diff --git a/src/link/link-lanes.test.ts b/src/link/link-lanes.test.ts new file mode 100644 index 000000000..af0c93a51 --- /dev/null +++ b/src/link/link-lanes.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from "vitest"; + +import { + KiB, + linkPair, + MiB, + pattern, + settle, + signal, + TYPE, + type LinkPair, +} from "./test-support.js"; + +async function openPair(pair: LinkPair) { + const g = await pair.gateway.openChannel({ signal: signal() }); + await settle(); + return { g, w: pair.worker.acceptChannel(g.id) }; +} + +function dataBytes(entries: LinkPair["gatewayTap"]["sent"]): number { + return entries.reduce( + (sum, entry) => + entry.kind === "binary" && entry.envelope.type === TYPE.DATA + ? sum + entry.envelope.payload.length + : sum, + 0, + ); +} + +describe("link lanes", () => { + it("with the transport held and 1 MiB of channel bytes queued, a text message written next is sent before all but at most 256 KiB plus one 64 KiB message of them", async () => { + const pair = linkPair(); + const { g } = await openPair(pair); + pair.gatewayEnd.hold(); + await g.writable.getWriter().write(pattern(0, MiB)); + await settle(); + + void pair.gateway.write("urgent\n"); + await settle(); + + const sent = pair.gatewayTap.sent; + const at = sent.findIndex((entry) => entry.kind === "text" && entry.text === "urgent\n"); + expect(at).toBeGreaterThanOrEqual(0); + expect(dataBytes(sent.slice(0, at))).toBeLessThanOrEqual(256 * KiB + 64 * KiB); + pair.gatewayEnd.release(); + await settle(); + expect(dataBytes(pair.gatewayTap.sent.slice(at))).toBeGreaterThanOrEqual( + MiB - (256 * KiB + 64 * KiB), + ); + }); + + it("with text messages written without pause and channel bytes queued, at least one channel message goes out per 64 KiB of text", async () => { + const pair = linkPair(); + const { g } = await openPair(pair); + pair.gatewayTap.setUnsent(300 * KiB); + await g.writable.getWriter().write(pattern(0, MiB)); + await settle(); + expect(dataBytes(pair.gatewayTap.sent)).toBe(0); + const text = "x".repeat(8 * KiB); + + pair.gatewayTap.setUnsent(0); + pair.gatewayTap.fireSent(); + for (let i = 0; i < 100; i += 1) void pair.gateway.write(text); + await settle(); + + const sent = pair.gatewayTap.sent; + const lastText = sent.map((entry) => entry.kind).lastIndexOf("text"); + expect(dataBytes(sent.slice(0, lastText)) / (64 * KiB)).toBeGreaterThanOrEqual(12); + let run = 0; + let longest = 0; + for (const entry of sent) { + if (entry.kind === "text") run += entry.text.length; + else if (entry.envelope.type === TYPE.DATA) run = 0; + longest = Math.max(longest, run); + } + expect(longest).toBeLessThanOrEqual(64 * KiB + 8 * KiB); + }); + + it("two channels with bytes queued take turns, one message each", async () => { + const pair = linkPair(); + const a = await openPair(pair); + const b = await openPair(pair); + pair.gatewayTap.setUnsent(300 * KiB); + await Promise.all([ + a.g.writable.getWriter().write(pattern(0, 512 * KiB)), + b.g.writable.getWriter().write(pattern(0, 512 * KiB)), + ]); + await settle(); + expect(pair.gatewayTap.binaries(TYPE.DATA)).toEqual([]); + + pair.gatewayTap.setUnsent(0); + pair.gatewayTap.fireSent(); + await settle(); + + const numbers = pair.gatewayTap.binaries(TYPE.DATA).map((envelope) => envelope.number); + expect(numbers).toHaveLength(16); + expect(new Set(numbers).size).toBe(2); + for (let i = 1; i < numbers.length; i += 1) expect(numbers[i]).not.toBe(numbers[i - 1]); + }); +}); diff --git a/src/link/link-messages.test.ts b/src/link/link-messages.test.ts new file mode 100644 index 000000000..4da190add --- /dev/null +++ b/src/link/link-messages.test.ts @@ -0,0 +1,166 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { createLink } from "./index.js"; +import { + errorOfRead, + errorOfWritable, + linkPair, + settle, + signal, + startWebSocketPair, + RecordingLogger, +} from "./test-support.js"; +import { FakeClock } from "../ports/index.js"; + +const MESSAGES = ['{"id":1,"type":"hello"}\n', "second é — ünïcode\n", "third\n"]; + +async function expectInOrder( + writer: { write(contents: string): Promise }, + onData: (listener: (chunk: string) => void) => unknown, +): Promise { + const received: string[] = []; + onData((chunk) => received.push(chunk)); + for (const message of MESSAGES) await writer.write(message); + await vi.waitFor(() => expect(received).toEqual(MESSAGES)); +} + +describe("link text messages", () => { + const cleanups: Array<() => Promise> = []; + afterEach(async () => { + await Promise.all(cleanups.splice(0).map((cleanup) => cleanup())); + }); + + it("text messages written on one link arrive on the other unchanged and in order, over the in-memory pair", async () => { + const { gateway, worker } = linkPair(); + + await expectInOrder(gateway, (listener) => worker.onData(listener)); + }); + + it("text messages written on one link arrive on the other unchanged and in order, over the real WebSocket", async () => { + const sockets = await startWebSocketPair(); + cleanups.push(() => sockets.close()); + const clock = new FakeClock(0); + const worker = createLink(sockets.worker, { + clock, + end: "worker", + logger: new RecordingLogger(), + }); + const gateway = createLink(sockets.gateway, { + clock, + end: "gateway", + logger: new RecordingLogger(), + }); + + await expectInOrder(gateway, (listener) => worker.onData(listener)); + }); + + it("text that arrives before the first onData is delivered to it", async () => { + const { gateway, worker } = linkPair(); + await gateway.write("early-1\n"); + await gateway.write("early-2\n"); + await settle(); + + const received: string[] = []; + worker.onData((chunk) => received.push(chunk)); + + expect(received).toEqual(["early-1\n", "early-2\n"]); + }); + + it("an onClose attached after the close fires at once", async () => { + const { gateway, worker } = linkPair(); + await worker.close(); + await settle(); + + const closed = vi.fn(); + gateway.onClose(closed); + + expect(closed).toHaveBeenCalledTimes(1); + }); + + it("a pair's fail(error) reaches onError", async () => { + const { gatewayEnd, gateway } = linkPair(); + const errors: Error[] = []; + gateway.onError((error) => errors.push(error)); + + gatewayEnd.fail(new Error("socket reset")); + await settle(); + + expect(errors.map((error) => error.message)).toEqual(["socket reset"]); + }); + + it("closing the transport fails every open channel with closed", async () => { + const { gateway, gatewayEnd, worker } = linkPair(); + const opened = await gateway.openChannel({ signal: signal() }); + const accepted = worker.acceptChannel(opened.id); + + await gatewayEnd.close(); + await settle(); + + await expect(errorOfRead(opened.readable)).resolves.toMatchObject({ reason: "closed" }); + await expect(errorOfWritable(opened.writable)).resolves.toMatchObject({ reason: "closed" }); + await expect(errorOfRead(accepted.readable)).resolves.toMatchObject({ reason: "closed" }); + await expect(errorOfWritable(accepted.writable)).resolves.toMatchObject({ reason: "closed" }); + }); + + it("closing the link closes the transport", async () => { + const { gateway, gatewayEnd, workerEnd } = linkPair(); + + await gateway.close(); + + expect(gatewayEnd.closed).toBe(true); + expect(workerEnd.closed).toBe(true); + }); + + it("write resolves when the transport's write resolves", async () => { + const { gateway, gatewayEnd, worker } = linkPair(); + const received: string[] = []; + worker.onData((chunk) => received.push(chunk)); + gatewayEnd.hold(); + let resolved = false; + + const write = gateway.write("held\n").then(() => { + resolved = true; + }); + await settle(); + expect(resolved).toBe(false); + expect(received).toEqual([]); + + gatewayEnd.release(); + await write; + + expect(received).toEqual(["held\n"]); + }); + + it("a text message queued at close resolves unsent, also when the pair was held", async () => { + const { gateway, gatewayEnd, worker } = linkPair(); + const received: string[] = []; + worker.onData((chunk) => received.push(chunk)); + await gateway.write("before\n"); + await settle(); + expect(received).toEqual(["before\n"]); + gatewayEnd.hold(); + + const write = gateway.write("queued\n"); + await settle(); + await gateway.close(); + await write; + await settle(); + + expect(received).toEqual(["before\n"]); + }); + + it("a text message written after the connection closed resolves without being sent", async () => { + const { gateway, worker } = linkPair(); + const received: string[] = []; + worker.onData((chunk) => received.push(chunk)); + await gateway.write("before\n"); + await settle(); + expect(received).toEqual(["before\n"]); + await gateway.close(); + + await gateway.write("late\n"); + await settle(); + + expect(received).toEqual(["before\n"]); + }); +}); diff --git a/src/link/link-rules.test.ts b/src/link/link-rules.test.ts new file mode 100644 index 000000000..ad4b3461f --- /dev/null +++ b/src/link/link-rules.test.ts @@ -0,0 +1,236 @@ +import { describe, expect, it } from "vitest"; + +import { + creditEnvelope, + dataEnvelope, + envelope, + errorOfRead, + KiB, + linkWithRawPeer, + openEnvelope, + pattern, + RESET_CODE, + resetEnvelope, + settle, + TYPE, + type RawPeer, +} from "./test-support.js"; + +async function acceptRaw(peer: RawPeer, number = 2, id = "raw-a") { + await peer.raw.writeBinary(openEnvelope(number, id)); + await settle(); + return peer.link.acceptChannel(id); +} + +async function expectTextFlows(peer: RawPeer): Promise { + await peer.link.write("ping\n"); + await peer.raw.write("pong\n"); + await settle(); + expect(peer.receivedText).toContain("ping\n"); + expect(peer.linkText).toContain("pong\n"); +} + +function resets(peer: RawPeer, number: number) { + return peer.received.filter((e) => e.type === TYPE.RESET && e.number === number); +} + +interface Break { + readonly name: string; + readonly run: (peer: RawPeer) => Promise; +} + +const channelBreaks: Break[] = [ + { + name: "DATA past the allowed bytes", + run: async (peer) => { + const channel = await acceptRaw(peer); + for (let i = 0; i < 64; i += 1) await peer.raw.writeBinary(dataEnvelope(2, 64 * KiB)); + await settle(); + expect(resets(peer, 2)).toEqual([]); + await peer.raw.writeBinary(dataEnvelope(2, 1)); + return channel; + }, + }, + { + name: "DATA over 64 KiB", + run: async (peer) => { + const channel = await acceptRaw(peer); + await peer.raw.writeBinary(dataEnvelope(2, 64 * KiB)); + await settle(); + expect(resets(peer, 2)).toEqual([]); + await peer.raw.writeBinary(dataEnvelope(2, 64 * KiB + 1)); + return channel; + }, + }, + { + name: "DATA after that direction ended", + run: async (peer) => { + const channel = await acceptRaw(peer); + await peer.raw.writeBinary(envelope(TYPE.END, 2)); + await settle(); + expect(resets(peer, 2)).toEqual([]); + await peer.raw.writeBinary(dataEnvelope(2, 10)); + return channel; + }, + }, + { + name: "END after that direction ended", + run: async (peer) => { + const channel = await acceptRaw(peer); + await peer.raw.writeBinary(envelope(TYPE.END, 2)); + await settle(); + expect(resets(peer, 2)).toEqual([]); + await peer.raw.writeBinary(envelope(TYPE.END, 2)); + return channel; + }, + }, + { + name: "a CREDIT of 0", + run: async (peer) => { + const channel = await acceptRaw(peer); + await channel.writable.getWriter().write(pattern(0, KiB)); + await peer.raw.writeBinary(creditEnvelope(2, KiB)); + await settle(); + expect(resets(peer, 2)).toEqual([]); + await peer.raw.writeBinary(creditEnvelope(2, 0)); + return channel; + }, + }, + { + name: "credit beyond 4 MiB outstanding", + run: async (peer) => { + const channel = await acceptRaw(peer); + await channel.writable.getWriter().write(pattern(0, 64 * KiB)); + await peer.raw.writeBinary(creditEnvelope(2, 64 * KiB)); + await settle(); + expect(resets(peer, 2)).toEqual([]); + await peer.raw.writeBinary(creditEnvelope(2, 1)); + return channel; + }, + }, +]; + +describe("link rule breaks that name a held channel", () => { + for (const rule of channelBreaks) { + it(`${rule.name} is dropped, resets the channel it names with invalid, is logged, and leaves text flowing`, async () => { + const peer = linkWithRawPeer(); + const channel = (await rule.run(peer)) as Awaited>; + await settle(); + + const named = resets(peer, 2); + expect(named).toHaveLength(1); + expect(named[0]?.payload[0]).toBe(RESET_CODE.invalid); + await expect(errorOfRead(channel.readable)).resolves.toMatchObject({ reason: "invalid" }); + expect(peer.log.problems().length).toBeGreaterThan(0); + await expectTextFlows(peer); + }); + } +}); + +interface Dropped { + readonly name: string; + readonly run: (peer: RawPeer) => Promise; + readonly neverAccepted?: string; +} + +const dropped: Dropped[] = [ + { + name: "a channel number the peer never opened", + run: async (peer) => { + await acceptRaw(peer); + await peer.raw.writeBinary(dataEnvelope(10, 5)); + }, + }, + { + name: "an OPEN reusing a live number", + neverAccepted: "raw-b", + run: async (peer) => { + await acceptRaw(peer); + await peer.raw.writeBinary(openEnvelope(2, "raw-b")); + }, + }, + { + name: "an OPEN with the wrong parity", + neverAccepted: "raw-c", + run: async (peer) => { + await peer.raw.writeBinary(openEnvelope(3, "raw-c")); + }, + }, + { + name: "a 65th OPEN from the peer", + neverAccepted: "raw-65", + run: async (peer) => { + for (let i = 1; i <= 64; i += 1) { + await peer.raw.writeBinary(openEnvelope(i * 2, `raw-${String(i)}`)); + } + await settle(); + expect(peer.log.problems()).toEqual([]); + expect(() => peer.link.acceptChannel("raw-64")).not.toThrow(); + await peer.raw.writeBinary(openEnvelope(130, "raw-65")); + }, + }, + { + name: "an unknown envelope type", + run: async (peer) => { + await peer.raw.writeBinary(envelope(99, 4)); + }, + }, + { + name: "a message too short to read", + run: async (peer) => { + await peer.raw.writeBinary(new Uint8Array([TYPE.DATA, 0, 0])); + }, + }, +]; + +describe("link rule breaks that name no held channel", () => { + for (const rule of dropped) { + it(`${rule.name} is dropped and logged and leaves text flowing`, async () => { + const peer = linkWithRawPeer(); + await rule.run(peer); + await settle(); + + expect(peer.log.problems().length).toBeGreaterThan(0); + if (rule.neverAccepted !== undefined) { + expect(() => peer.link.acceptChannel(rule.neverAccepted as string)).toThrow(); + } + await expectTextFlows(peer); + }); + } +}); + +describe("link late traffic for an ended channel", () => { + it("a RESET for a channel this side does not hold is dropped and not answered", async () => { + const peer = linkWithRawPeer(); + await acceptRaw(peer); + await peer.raw.writeBinary(resetEnvelope(2, "aborted")); + await settle(); + const before = peer.received.length; + const problems = peer.log.problems().length; + + await peer.raw.writeBinary(resetEnvelope(2, "aborted")); + await settle(); + + expect(peer.received).toHaveLength(before); + expect(peer.log.problems()).toHaveLength(problems); + await expectTextFlows(peer); + }); + + it("a STOP that arrives after its channel ended on this side is dropped quietly: no log, no reset, no answer", async () => { + const peer = linkWithRawPeer(); + const channel = await acceptRaw(peer); + await channel.writable.getWriter().close(); + await settle(); + expect(peer.received.some((e) => e.type === TYPE.END && e.number === 2)).toBe(true); + await peer.raw.writeBinary(envelope(TYPE.END, 2)); + await settle(); + const before = peer.received.length; + const records = peer.log.records.length; + + await peer.raw.writeBinary(envelope(TYPE.STOP, 2)); + await settle(); + + expect(peer.received).toHaveLength(before); + expect(peer.log.records).toHaveLength(records); + }); +}); diff --git a/src/link/test-support.ts b/src/link/test-support.ts new file mode 100644 index 000000000..1267a3396 --- /dev/null +++ b/src/link/test-support.ts @@ -0,0 +1,384 @@ +import { createHash } from "node:crypto"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; + +import { + createConnectionPair, + FakeClock, + type Logger, + type MemoryTransportConnection, + type UplinkTransportConnection, +} from "../ports/index.js"; +import { + WebSocketUplinkConnector, + WebSocketUplinkListenerFactory, +} from "../ports/uplink-websocket.js"; +import { createLink, type LinkChannel, type LinkConnection } from "./index.js"; + +export const KiB = 1024; +export const MiB = 1024 * KiB; + +export const TYPE = { OPEN: 1, DATA: 2, END: 3, STOP: 4, CREDIT: 5, RESET: 6 } as const; +export const RESET_CODE = { aborted: 1, stalled: 2, "not-accepted": 3, invalid: 4 } as const; + +export interface Envelope { + readonly type: number; + readonly number: number; + readonly payload: Uint8Array; +} + +export function envelope(type: number, number: number, payload = new Uint8Array(0)): Uint8Array { + const bytes = new Uint8Array(5 + payload.length); + bytes[0] = type; + new DataView(bytes.buffer).setUint32(1, number); + bytes.set(payload, 5); + return bytes; +} + +export function parseEnvelope(bytes: Uint8Array): Envelope { + return { + type: bytes[0] ?? -1, + number: new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(1), + payload: bytes.slice(5), + }; +} + +export function openEnvelope(number: number, id: string): Uint8Array { + return envelope(TYPE.OPEN, number, new TextEncoder().encode(id)); +} + +export function dataEnvelope(number: number, size: number): Uint8Array { + return envelope(TYPE.DATA, number, new Uint8Array(size).fill(7)); +} + +export function creditEnvelope(number: number, amount: number): Uint8Array { + const payload = new Uint8Array(4); + new DataView(payload.buffer).setUint32(0, amount); + return envelope(TYPE.CREDIT, number, payload); +} + +export function resetEnvelope(number: number, reason: keyof typeof RESET_CODE): Uint8Array { + return envelope(TYPE.RESET, number, new Uint8Array([RESET_CODE[reason]])); +} + +export type Sent = + | { readonly kind: "text"; readonly text: string } + | { readonly kind: "binary"; readonly size: number; readonly envelope: Envelope }; + +export class TappedTransport implements UplinkTransportConnection { + readonly sent: Sent[] = []; + readonly #sentListeners = new Set<() => void>(); + #extraUnsent = 0; + + constructor(readonly inner: UplinkTransportConnection) { + inner.onSent(() => this.fireSent()); + } + + get closed(): boolean { + return this.inner.closed; + } + + get unsentBytes(): number { + return this.inner.unsentBytes + this.#extraUnsent; + } + + setUnsent(bytes: number): void { + this.#extraUnsent = bytes; + } + + fireSent(): void { + for (const listener of this.#sentListeners) listener(); + } + + onData(listener: (chunk: string) => void): () => void { + return this.inner.onData(listener); + } + + onClose(listener: () => void): () => void { + return this.inner.onClose(listener); + } + + onError(listener: (error: Error) => void): () => void { + return this.inner.onError(listener); + } + + onBinary(listener: (bytes: Uint8Array) => void): () => void { + return this.inner.onBinary(listener); + } + + onSent(listener: () => void): () => void { + this.#sentListeners.add(listener); + return () => this.#sentListeners.delete(listener); + } + + write(contents: string): Promise { + this.sent.push({ kind: "text", text: contents }); + return this.inner.write(contents); + } + + writeBinary(bytes: Uint8Array): Promise { + this.sent.push({ kind: "binary", size: bytes.length, envelope: parseEnvelope(bytes) }); + return this.inner.writeBinary(bytes); + } + + close(): Promise { + return this.inner.close(); + } + + binaries(type?: number): Envelope[] { + const out: Envelope[] = []; + for (const entry of this.sent) { + if (entry.kind === "binary" && (type === undefined || entry.envelope.type === type)) { + out.push(entry.envelope); + } + } + return out; + } +} + +export class RecordingLogger implements Logger { + readonly records: { readonly level: string; readonly message: string }[] = []; + debug(message: string): void { + this.records.push({ level: "debug", message }); + } + info(message: string): void { + this.records.push({ level: "info", message }); + } + warn(message: string): void { + this.records.push({ level: "warn", message }); + } + error(message: string): void { + this.records.push({ level: "error", message }); + } + child(): Logger { + return this; + } + problems(): string[] { + return this.records + .filter((record) => record.level === "warn" || record.level === "error") + .map((record) => record.message); + } +} + +export async function settle(): Promise { + for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setImmediate(resolve)); +} + +export interface LinkPair { + readonly clock: FakeClock; + readonly worker: LinkConnection; + readonly gateway: LinkConnection; + readonly workerTap: TappedTransport; + readonly gatewayTap: TappedTransport; + readonly workerEnd: MemoryTransportConnection; + readonly gatewayEnd: MemoryTransportConnection; + readonly workerLog: RecordingLogger; + readonly gatewayLog: RecordingLogger; +} + +export function linkPair(options: { gatewayFirstNumber?: number } = {}): LinkPair { + const clock = new FakeClock(0); + const [workerEnd, gatewayEnd] = createConnectionPair(); + const workerTap = new TappedTransport(workerEnd); + const gatewayTap = new TappedTransport(gatewayEnd); + const workerLog = new RecordingLogger(); + const gatewayLog = new RecordingLogger(); + const worker = createLink(workerTap, { clock, end: "worker", logger: workerLog }); + const gateway = createLink(gatewayTap, { + clock, + end: "gateway", + logger: gatewayLog, + ...(options.gatewayFirstNumber === undefined + ? {} + : { firstChannelNumber: options.gatewayFirstNumber }), + }); + return { + clock, + gateway, + gatewayEnd, + gatewayLog, + gatewayTap, + worker, + workerEnd, + workerLog, + workerTap, + }; +} + +export interface RawPeer { + readonly clock: FakeClock; + readonly link: LinkConnection; + readonly tap: TappedTransport; + readonly raw: MemoryTransportConnection; + readonly log: RecordingLogger; + readonly received: Envelope[]; + readonly receivedText: string[]; + readonly linkText: string[]; +} + +export function linkWithRawPeer(): RawPeer { + const clock = new FakeClock(0); + const [linkEnd, raw] = createConnectionPair(); + const tap = new TappedTransport(linkEnd); + const log = new RecordingLogger(); + const link = createLink(tap, { clock, end: "worker", logger: log }); + const received: Envelope[] = []; + const receivedText: string[] = []; + const linkText: string[] = []; + raw.onBinary((bytes) => received.push(parseEnvelope(bytes))); + raw.onData((chunk) => receivedText.push(chunk)); + link.onData((chunk) => linkText.push(chunk)); + 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; + return bytes; +} + +export function patternHash(total: number): string { + const hash = createHash("sha256"); + for (let offset = 0; offset < total; offset += MiB) { + hash.update(pattern(offset, Math.min(MiB, total - offset))); + } + return hash.digest("hex"); +} + +export async function pump( + writable: WritableStream, + total: number, + chunk = 64 * KiB, +): Promise { + const writer = writable.getWriter(); + for (let offset = 0; offset < total; offset += chunk) { + await writer.write(pattern(offset, Math.min(chunk, total - offset))); + } + await writer.close(); +} + +export async function drain( + readable: ReadableStream, +): Promise<{ length: number; hash: string }> { + const reader = readable.getReader(); + const hash = createHash("sha256"); + let length = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + hash.update(value); + length += value.length; + } + return { hash: hash.digest("hex"), length }; +} + +export async function readAll(readable: ReadableStream): Promise { + const reader = readable.getReader(); + const parts: Uint8Array[] = []; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + parts.push(value); + } + return Buffer.concat(parts); +} + +export async function writeAndClose(channel: LinkChannel, bytes: Uint8Array): Promise { + const writer = channel.writable.getWriter(); + await writer.write(bytes); + await writer.close(); +} + +export async function writeUntilBlocked( + writer: WritableStreamDefaultWriter, + chunk = 64 * KiB, + limit = 400, +): Promise { + let accepted = 0; + for (let i = 0; i < limit; i += 1) { + const ready = await Promise.race([ + writer.ready.then( + () => true, + () => false, + ), + settle().then(() => false), + ]); + if (!ready) break; + writer.write(pattern(accepted, chunk)).catch(() => undefined); + accepted += chunk; + } + return accepted; +} + +export async function endChannel(a: LinkChannel, b: LinkChannel): Promise { + await Promise.all([ + a.writable.getWriter().close(), + b.writable.getWriter().close(), + drain(a.readable), + drain(b.readable), + ]); +} + +export async function errorOfRead(readable: ReadableStream): Promise { + const reader = readable.getReader(); + try { + for (;;) { + const { done } = await reader.read(); + if (done) throw new Error("the readable ended cleanly instead of erroring"); + } + } catch (error: unknown) { + return error; + } +} + +export async function errorOfWritable(writable: WritableStream): Promise { + const writer = writable.getWriter(); + try { + await writer.closed; + } catch (error: unknown) { + return error; + } + throw new Error("the writable closed cleanly instead of erroring"); +} + +export function signal(): AbortSignal { + return new AbortController().signal; +} diff --git a/src/ports/index.ts b/src/ports/index.ts index 4eb210dec..8a220ed32 100644 --- a/src/ports/index.ts +++ b/src/ports/index.ts @@ -37,7 +37,9 @@ export { type UplinkConnector, type UplinkDialOptions, type UplinkListener, + type MemoryTransportConnection, type UplinkListenerFactory, + type UplinkTransportConnection, } from "./uplink.js"; // fallow-ignore-next-line unused-type -- public port contract for consumers that branch on why a dial failed. export type { UplinkErrorCode } from "./uplink.js"; diff --git a/src/ports/uplink-websocket.test.ts b/src/ports/uplink-websocket.test.ts index 3f4880fac..2f97b4c4e 100644 --- a/src/ports/uplink-websocket.test.ts +++ b/src/ports/uplink-websocket.test.ts @@ -16,14 +16,21 @@ import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; -import { afterEach, describe, expect, it } from "vitest"; - -import type { ClaimedUplinkIdentity, UplinkAuthOutcome } from "./uplink.js"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { WebSocket } from "ws"; + +import type { + ClaimedUplinkIdentity, + UplinkAuthOutcome, + UplinkTransportConnection, +} from "./uplink.js"; import { WebSocketUplinkConnector, WebSocketUplinkListenerFactory } from "./uplink-websocket.js"; let server: Server | undefined; +const openConnections: Array<{ close(): unknown }> = []; afterEach(async () => { + for (const connection of openConnections.splice(0)) await connection.close(); if (server === undefined) return; await new Promise((resolve) => server?.close(() => resolve())); server = undefined; @@ -105,3 +112,98 @@ describe("WebSocketUplinkListenerFactory / P3", () => { expect(claims[0]).toEqual({ label: "mac-mini-1", workerId: "wrk_1" }); }); }); + +async function startAcceptingGateway(): Promise<{ + url: string; + accepted: Promise; +}> { + let resolveAccepted: ((connection: UplinkTransportConnection) => void) | undefined; + const accepted = new Promise((resolve) => { + resolveAccepted = resolve; + }); + const factory = new WebSocketUplinkListenerFactory(); + await factory.listen({ + authenticate: () => Promise.resolve("accept"), + accept: (uplink) => { + openConnections.push(uplink.connection); + resolveAccepted?.(uplink.connection); + }, + }); + 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; + return { accepted, url: `ws://127.0.0.1:${port}` }; +} + +const dialOptions = (url: string) => ({ token: "join", url, workerId: "wrk_1" }); + +describe("WebSocketUplinkConnection binary messages", () => { + it("sends writeBinary bytes as one binary message and resolves on its send callback, and at once on a closed socket", async () => { + const { accepted, url } = await startAcceptingGateway(); + const client = new WebSocket(`${url}/v1/uplink`, { + headers: { authorization: "Bearer join", "x-simlock-worker-id": "wrk_1" }, + }); + openConnections.push(client); + const messages: Array<{ binary: boolean; length: number }> = []; + client.on("message", (data: Buffer, isBinary: boolean) => + messages.push({ binary: isBinary, length: data.length }), + ); + const gateway = await accepted; + + await gateway.writeBinary(new Uint8Array(100 * 1024)); + await vi.waitFor(() => expect(messages).toEqual([{ binary: true, length: 100 * 1024 }])); + await gateway.close(); + await gateway.writeBinary(new Uint8Array(4)); + + expect(messages).toHaveLength(1); + }); + + it("delivers a received binary message to onBinary", async () => { + const { accepted, url } = await startAcceptingGateway(); + const worker = await new WebSocketUplinkConnector().connect(dialOptions(url)); + const gateway = await accepted; + const received: number[][] = []; + gateway.onBinary((bytes) => received.push([...bytes])); + + await worker.writeBinary(new Uint8Array([4, 5, 6])); + + await vi.waitFor(() => expect(received).toEqual([[4, 5, 6]])); + }); + + it("drops a binary message that arrives with no listener", async () => { + const { accepted, url } = await startAcceptingGateway(); + const worker = await new WebSocketUplinkConnector().connect(dialOptions(url)); + const gateway = await accepted; + const text: string[] = []; + gateway.onData((chunk) => text.push(chunk)); + await worker.writeBinary(new Uint8Array([1])); + await worker.write("marker\n"); + await vi.waitFor(() => expect(text).toEqual(["marker\n"])); + const received: number[][] = []; + gateway.onBinary((bytes) => received.push([...bytes])); + + await worker.writeBinary(new Uint8Array([2])); + + await vi.waitFor(() => expect(received).toEqual([[2]])); + }); + + it("unsentBytes follows the socket's buffered amount with onSent firing when a send completes", async () => { + const { accepted, url } = await startAcceptingGateway(); + const worker = await new WebSocketUplinkConnector().connect(dialOptions(url)); + await accepted; + const onSent = vi.fn(); + worker.onSent(onSent); + expect(worker.unsentBytes).toBe(0); + + const write = worker.writeBinary(new Uint8Array(16 * 1024 * 1024)); + const buffered = worker.unsentBytes; + await write; + + expect(buffered).toBeGreaterThan(0); + expect(worker.unsentBytes).toBe(0); + expect(onSent).toHaveBeenCalled(); + }); +}); diff --git a/src/ports/uplink-websocket.ts b/src/ports/uplink-websocket.ts index 62b48cc6f..790b4ec0b 100644 --- a/src/ports/uplink-websocket.ts +++ b/src/ports/uplink-websocket.ts @@ -19,7 +19,7 @@ import type { Duplex } from "node:stream"; import { WebSocket, WebSocketServer, type RawData } from "ws"; -import { subscribeListener, type IpcConnection } from "./ipc.js"; +import { subscribeListener } from "./ipc.js"; import { resolveUplinkUrl, uplinkOutcome, @@ -33,6 +33,7 @@ import { type UplinkHandlers, type UplinkListener, type UplinkListenerFactory, + type UplinkTransportConnection, } from "./uplink.js"; /** @@ -41,7 +42,7 @@ import { * and every reader buffers by newline, so a message boundary that does not line up with a * frame boundary is harmless either way. */ -class WebSocketUplinkConnection implements IpcConnection { +class WebSocketUplinkConnection implements UplinkTransportConnection { readonly #socket: WebSocket; readonly #dataListeners = new Set<(chunk: string) => void>(); readonly #closeListeners = new Set<() => void>(); @@ -112,6 +113,18 @@ class WebSocketUplinkConnection implements IpcConnection { return subscribeListener(this.#errorListeners, listener); } + readonly unsentBytes = 0; + + async writeBinary(): Promise {} + + onBinary(): () => void { + return () => {}; + } + + onSent(): () => void { + return () => {}; + } + async write(contents: string): Promise { if (this.#closed || this.#socket.readyState !== WebSocket.OPEN) return; await new Promise((resolve) => { @@ -249,7 +262,7 @@ export class WebSocketUplinkListenerFactory implements UplinkListenerFactory { /** The worker's half: dials `gateway.url` with the join token and its instance id. */ export class WebSocketUplinkConnector implements UplinkConnector { - async connect(options: UplinkDialOptions): Promise { + async connect(options: UplinkDialOptions): Promise { // `options.url` is `gateway.url`, the gateway's base URL; the endpoint is this worker's to // derive (ADR 0005 §4), so an operator configures one URL and never an internal path. const socket = new WebSocket(resolveUplinkUrl(options.url), { diff --git a/src/ports/uplink.test.ts b/src/ports/uplink.test.ts index 22e01d0ff..70e8e680c 100644 --- a/src/ports/uplink.test.ts +++ b/src/ports/uplink.test.ts @@ -198,3 +198,56 @@ describe("resolveUplinkUrl", () => { expect(resolveUplinkUrl("wss://ci.example/simlock")).toBe("wss://ci.example/simlock/v1/uplink"); }); }); + +describe("createConnectionPair binary messages", () => { + it("carries a binary message from one end to the other's onBinary listeners", async () => { + const [left, right] = createConnectionPair(); + const received: number[][] = []; + right.onBinary((bytes) => received.push([...bytes])); + + await left.writeBinary(new Uint8Array([1, 2, 3])); + + expect(received).toEqual([[1, 2, 3]]); + }); + + it("drops a binary message that arrives with no onBinary listener", async () => { + const [left, right] = createConnectionPair(); + await left.writeBinary(new Uint8Array([9])); + const received: number[][] = []; + right.onBinary((bytes) => received.push([...bytes])); + + await left.writeBinary(new Uint8Array([1])); + + expect(received).toEqual([[1]]); + }); + + it("while held, unsentBytes counts what is written (text in UTF-8 bytes), nothing arrives and the write promises stay pending, until release delivers them in order and fires onSent", async () => { + const [left, right] = createConnectionPair(); + const arrived: string[] = []; + right.onData((chunk) => arrived.push(`text:${chunk}`)); + right.onBinary((bytes) => arrived.push(`binary:${String(bytes.length)}`)); + const onSent = vi.fn(); + left.onSent(onSent); + left.hold(); + const settled: string[] = []; + + const writes = [ + left.write("é").then(() => settled.push("first")), + left.writeBinary(new Uint8Array([1, 2, 3])).then(() => settled.push("second")), + left.write("x\n").then(() => settled.push("third")), + ]; + await new Promise((resolve) => setImmediate(resolve)); + + expect(left.unsentBytes).toBe(2 + 3 + 2); + expect(arrived).toEqual([]); + expect(settled).toEqual([]); + + left.release(); + await Promise.all(writes); + + expect(arrived).toEqual(["text:é", "binary:3", "text:x\n"]); + expect(settled).toEqual(["first", "second", "third"]); + expect(left.unsentBytes).toBe(0); + expect(onSent).toHaveBeenCalled(); + }); +}); diff --git a/src/ports/uplink.ts b/src/ports/uplink.ts index 985d0b36a..f5cfdfa18 100644 --- a/src/ports/uplink.ts +++ b/src/ports/uplink.ts @@ -55,13 +55,26 @@ export function resolveUplinkUrl(baseUrl: string): string { return new URL(UPLINK_PATH.slice(1), base).toString(); } +export interface UplinkTransportConnection extends IpcConnection { + writeBinary(bytes: Uint8Array): Promise; + onBinary(listener: (bytes: Uint8Array) => void): () => void; + readonly unsentBytes: number; + onSent(listener: () => void): () => void; +} + +export interface MemoryTransportConnection extends UplinkTransportConnection { + hold(): void; + release(): void; + fail(error: Error): void; +} + /** One accepted uplink: who opened it, and the frames it carries. */ export interface AcceptedUplink { /** The worker's instance id, from `WORKER_ID_HEADER`. */ readonly workerId: string; /** `gateway.label`, when the worker sent one. Display only. */ readonly label?: string; - readonly connection: IpcConnection; + readonly connection: UplinkTransportConnection; /** * The join token record's own id, when `authenticate` reported one alongside `accept` * (C-2, ADR 0005 §8: "revoking closes the uplink"). Recorded here so `GatewayService` can @@ -154,7 +167,7 @@ export interface UplinkDialOptions { } export interface UplinkConnector { - connect(options: UplinkDialOptions): Promise; + connect(options: UplinkDialOptions): Promise; } /** @@ -199,7 +212,7 @@ export class MemoryUplinkTransport implements UplinkListenerFactory, UplinkConne }; } - async connect(options: UplinkDialOptions): Promise { + async connect(options: UplinkDialOptions): Promise { const handlers = this.#handlers; if (handlers === undefined) { throw new UplinkError("unreachable", `No gateway is listening at ${options.url}`); @@ -230,7 +243,7 @@ export class MemoryUplinkTransport implements UplinkListenerFactory, UplinkConne * that needs a bare pair (a scripted worker on one end, a real `DaemonServer` on the other) * does not have to build one. */ -export function createConnectionPair(): [IpcConnection, IpcConnection] { +export function createConnectionPair(): [MemoryTransportConnection, MemoryTransportConnection] { const left = new PairedConnection(); const right = new PairedConnection(); left.pair(right); @@ -238,7 +251,7 @@ export function createConnectionPair(): [IpcConnection, IpcConnection] { return [left, right]; } -class PairedConnection implements IpcConnection { +class PairedConnection implements MemoryTransportConnection { readonly #closeListeners = new Set<() => void>(); readonly #dataListeners = new Set<(chunk: string) => void>(); /** Buffered until the first `onData`, exactly as the WebSocket adapter does and as a real @@ -280,6 +293,24 @@ class PairedConnection implements IpcConnection { return () => {}; } + readonly unsentBytes = 0; + + async writeBinary(): Promise {} + + onBinary(): () => void { + return () => {}; + } + + onSent(): () => void { + return () => {}; + } + + hold(): void {} + + release(): void {} + + fail(): void {} + async write(contents: string): Promise { const peer = this.#peer; if (this.#closed || peer === undefined || peer.#closed) return; From 8f3abab8eecef2d1b3952d87f9c9b41ee7bd6bfd Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 14:33:34 +0200 Subject: [PATCH 2/8] feat(ports): the uplink transport carries binary messages, unsent bytes and a held pair 7 failing port tests -> 0 failing --- src/ports/uplink-websocket.ts | 43 +++++++++++++----- src/ports/uplink.ts | 82 ++++++++++++++++++++++++++++------- 2 files changed, 99 insertions(+), 26 deletions(-) diff --git a/src/ports/uplink-websocket.ts b/src/ports/uplink-websocket.ts index 790b4ec0b..2bf9df608 100644 --- a/src/ports/uplink-websocket.ts +++ b/src/ports/uplink-websocket.ts @@ -60,14 +60,24 @@ class WebSocketUplinkConnection implements UplinkTransportConnection { * every other `IpcConnection` in the tree already does. */ readonly #pending: string[] = []; + readonly #binaryListeners = new Set<(bytes: Uint8Array) => void>(); + readonly #sentListeners = new Set<() => void>(); #closed = false; constructor(socket: WebSocket) { this.#socket = socket; socket.on("message", (data: RawData, isBinary: boolean) => { - // Binary frames are not part of this protocol. Ignoring one is the same treatment - // `SimlockWire` gives a malformed line: a peer's bad frame is not this side's crash. - if (isBinary) return; + if (isBinary) { + // why: with no listener the message is dropped, so nothing piles up before a link subscribes. + if (this.#binaryListeners.size === 0) return; + const bytes = Array.isArray(data) + ? Buffer.concat(data) + : Buffer.isBuffer(data) + ? data + : Buffer.from(data as ArrayBuffer); + for (const listener of this.#binaryListeners) listener(bytes); + return; + } const chunk = Array.isArray(data) ? Buffer.concat(data).toString("utf8") : Buffer.isBuffer(data) @@ -113,16 +123,26 @@ class WebSocketUplinkConnection implements UplinkTransportConnection { return subscribeListener(this.#errorListeners, listener); } - readonly unsentBytes = 0; + get unsentBytes(): number { + return this.#socket.bufferedAmount; + } - async writeBinary(): Promise {} + onBinary(listener: (bytes: Uint8Array) => void): () => void { + return subscribeListener(this.#binaryListeners, listener); + } - onBinary(): () => void { - return () => {}; + onSent(listener: () => void): () => void { + return subscribeListener(this.#sentListeners, listener); } - onSent(): () => void { - return () => {}; + async writeBinary(bytes: Uint8Array): Promise { + if (this.#closed || this.#socket.readyState !== WebSocket.OPEN) return; + await new Promise((resolve) => { + this.#socket.send(bytes, { binary: true }, () => { + for (const listener of this.#sentListeners) listener(); + resolve(); + }); + }); } async write(contents: string): Promise { @@ -133,7 +153,10 @@ class WebSocketUplinkConnection implements UplinkTransportConnection { // A send error is not rethrown -- the `error` event above already reports it to every // listener, and a rejected `write` would tear down a caller that has nothing to do // about it. - this.#socket.send(contents, () => resolve()); + this.#socket.send(contents, () => { + for (const listener of this.#sentListeners) listener(); + resolve(); + }); }); } diff --git a/src/ports/uplink.ts b/src/ports/uplink.ts index f5cfdfa18..ef936191b 100644 --- a/src/ports/uplink.ts +++ b/src/ports/uplink.ts @@ -251,12 +251,22 @@ export function createConnectionPair(): [MemoryTransportConnection, MemoryTransp return [left, right]; } +type PairedMessage = + | { readonly kind: "text"; readonly text: string } + | { readonly kind: "binary"; readonly bytes: Uint8Array }; + class PairedConnection implements MemoryTransportConnection { readonly #closeListeners = new Set<() => void>(); readonly #dataListeners = new Set<(chunk: string) => void>(); /** Buffered until the first `onData`, exactly as the WebSocket adapter does and as a real * socket does: the peer may write before this end has been handed to whoever reads it. */ readonly #pending: string[] = []; + readonly #errorListeners = new Set<(error: Error) => void>(); + readonly #binaryListeners = new Set<(bytes: Uint8Array) => void>(); + readonly #sentListeners = new Set<() => void>(); + readonly #queue: Array<{ message: PairedMessage; resolve: () => void; size: number }> = []; + #unsent = 0; + #held = false; #peer: PairedConnection | undefined; #closed = false; @@ -287,38 +297,76 @@ class PairedConnection implements MemoryTransportConnection { return subscribeListener(this.#closeListeners, listener); } - onError(): () => void { - // An in-memory pair has no transport to fail; nothing ever emits here. Returning an inert - // unsubscriber keeps the port's shape honest rather than pretending errors are possible. - return () => {}; + onError(listener: (error: Error) => void): () => void { + return subscribeListener(this.#errorListeners, listener); } - readonly unsentBytes = 0; - - async writeBinary(): Promise {} + get unsentBytes(): number { + return this.#unsent; + } - onBinary(): () => void { - return () => {}; + onBinary(listener: (bytes: Uint8Array) => void): () => void { + return subscribeListener(this.#binaryListeners, listener); } - onSent(): () => void { - return () => {}; + onSent(listener: () => void): () => void { + return subscribeListener(this.#sentListeners, listener); } - hold(): void {} + hold(): void { + this.#held = true; + } - release(): void {} + release(): void { + this.#held = false; + while (this.#queue.length > 0) { + const entry = this.#queue.shift(); + if (entry === undefined) break; + this.#unsent -= entry.size; + this.#deliver(entry.message); + entry.resolve(); + } + this.#unsent = 0; + for (const listener of this.#sentListeners) listener(); + } - fail(): void {} + fail(error: Error): void { + for (const listener of this.#errorListeners) listener(error); + void this.close(); + } async write(contents: string): Promise { + await this.#send({ kind: "text", text: contents }, Buffer.byteLength(contents)); + } + + async writeBinary(bytes: Uint8Array): Promise { + await this.#send({ kind: "binary", bytes }, bytes.length); + } + + async #send(message: PairedMessage, size: number): Promise { + if (this.#closed) return; + if (!this.#held) { + this.#deliver(message); + return; + } + this.#unsent += size; + await new Promise((resolve) => { + this.#queue.push({ message, resolve, size }); + }); + } + + #deliver(message: PairedMessage): void { const peer = this.#peer; if (this.#closed || peer === undefined || peer.#closed) return; + if (message.kind === "binary") { + for (const listener of peer.#binaryListeners) listener(message.bytes); + return; + } if (peer.#dataListeners.size === 0) { - peer.#pending.push(contents); + peer.#pending.push(message.text); return; } - for (const listener of peer.#dataListeners) listener(contents); + for (const listener of peer.#dataListeners) listener(message.text); } async close(): Promise { @@ -330,6 +378,8 @@ class PairedConnection implements MemoryTransportConnection { #close(): void { if (this.#closed) return; this.#closed = true; + this.#unsent = 0; + for (const entry of this.#queue.splice(0)) entry.resolve(); for (const listener of this.#closeListeners) listener(); } } From e5461827c350e4e067d661909b6baa7cc6055201 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 14:39:56 +0200 Subject: [PATCH 3/8] feat(link): the uplink carries byte channels beside its messages, and small messages go first (#556) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The link module wraps an uplink transport connection: text goes through unchanged and ahead of bulk bytes; byte channels carry credit, ending, stalls, numbers and the 64 channel limit (ADR 0028 §1-3). 57 failing -> 0 failing The test helper readAll returned a Buffer, which toEqual never matches against a Uint8Array; it returns a Uint8Array now. --- docs/internal/COMPONENTS.md | 1 + ...te-channels-and-small-messages-go-first.md | 2 +- docs/internal/adr/README.md | 2 +- src/link/channel.ts | 466 ++++++++++++++++++ src/link/envelope.ts | 69 +++ src/link/index.ts | 311 ++++++++++-- src/link/scheduler.ts | 132 +++++ src/link/test-support.ts | 2 +- 8 files changed, 935 insertions(+), 50 deletions(-) create mode 100644 src/link/channel.ts create mode 100644 src/link/envelope.ts create mode 100644 src/link/scheduler.ts diff --git a/docs/internal/COMPONENTS.md b/docs/internal/COMPONENTS.md index 11b06e453..5d2ba91ab 100644 --- a/docs/internal/COMPONENTS.md +++ b/docs/internal/COMPONENTS.md @@ -41,6 +41,7 @@ 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. | | `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. | 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 39cb5bc2d..55517d6f9 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 — not yet implemented +- **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 - **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/docs/internal/adr/README.md b/docs/internal/adr/README.md index 8df399bcf..2ea0e8c36 100644 --- a/docs/internal/adr/README.md +++ b/docs/internal/adr/README.md @@ -66,4 +66,4 @@ the status is stale. | [0025](0025-simlock-ships-android-profiles-and-a-model-pairs-only-with-images-that-fit.md) | Simlock ships Android device profiles, and a model pairs only with images that fit it | Accepted — not yet implemented | | [0026](0026-agent-device-through-a-gateway-relays-over-the-uplink.md) | agent-device through a gateway: workers advertise capabilities, and the host link relays over the uplink | Accepted — not yet implemented; §2 narrowed by 0028 for relayed bodies | | [0027](0027-dependency-cruiser-checks-every-component-boundary.md) | dependency-cruiser checks every component's boundary and the module graph | Accepted | -| [0028](0028-the-uplink-carries-byte-channels-and-small-messages-go-first.md) | The uplink carries byte channels beside its messages, and small messages go first | Accepted — not yet implemented | +| [0028](0028-the-uplink-carries-byte-channels-and-small-messages-go-first.md) | The uplink carries byte channels beside its messages, and small messages go first | Accepted — partly implemented (§1–3) | diff --git a/src/link/channel.ts b/src/link/channel.ts new file mode 100644 index 000000000..ef3d81443 --- /dev/null +++ b/src/link/channel.ts @@ -0,0 +1,466 @@ +import type { Clock, Logger, TimerHandle } from "../ports/index.js"; +import { + CHANNEL_WINDOW, + ENVELOPE, + KIB, + MAX_DATA_BYTES, + encodeCredit, + encodeEnvelope, + encodeReset, + type ResetReason, +} from "./envelope.js"; +import type { BulkMessage, BulkSource, Scheduler } from "./scheduler.js"; + +export type LinkChannelErrorReason = + | "aborted" + | "invalid" + | "not-accepted" + | "stalled" + | "closed" + | "stopped"; + +export class LinkChannelError extends Error { + constructor( + readonly reason: LinkChannelErrorReason, + message?: string, + ) { + super(message ?? reason); + this.name = "LinkChannelError"; + } +} + +export interface LinkChannel { + readonly id: string; + readonly readable: ReadableStream; + readonly writable: WritableStream; + abort(reason?: string): void; + readonly credit: number; + whenCredit(): Promise; +} + +export interface ChannelHost { + readonly clock: Clock; + readonly logger: Logger; + readonly scheduler: Scheduler; + unsentBytes(): number; + channelDone(channel: Channel): void; +} + +const ACCEPT_WAIT_MS = 30_000; +const STALL_WAIT_MS = 60_000; +const WRITER_BUFFER = 64 * KIB; + +interface Deferred { + resolve(): void; + reject(error: Error): void; +} + +type QueueItem = { readonly bytes: Uint8Array; readonly payload: number; readonly end: boolean }; + +export class Channel implements BulkSource { + readonly number: number; + readonly id: string; + readonly ownedByUs: boolean; + accepted: boolean; + readonly view: LinkChannel; + readonly #host: ChannelHost; + + #failure: LinkChannelError | undefined; + #done = false; + + #openHanded: boolean; + #queue: QueueItem[] = []; + #queuedBytes = 0; + #allowance = CHANNEL_WINDOW; + #handed = 0; + #inFlight = 0; + #endQueued = false; + #endHanded = false; + #stoppedByPeer = false; + #pendingWrite: Deferred | undefined; + #creditWaiters: Deferred[] = []; + #stallTimer: TimerHandle | undefined; + #acceptTimer: TimerHandle | undefined; + + #received = 0; + #granted = 0; + #readTotal = 0; + #inQueue: Uint8Array[] = []; + #inEnded = false; + #stopSent = false; + #wantRead = false; + #readableController: ReadableStreamDefaultController | undefined; + #writableController: WritableStreamDefaultController | undefined; + + #resetQueued = false; + #resetHanded = false; + #resetReceived = false; + + constructor(host: ChannelHost, number: number, id: string, ownedByUs: boolean) { + this.#host = host; + this.number = number; + this.id = id; + this.ownedByUs = ownedByUs; + this.accepted = ownedByUs; + this.#openHanded = !ownedByUs; + this.view = this.#buildView(); + if (ownedByUs) { + host.scheduler.binary( + encodeEnvelope(ENVELOPE.OPEN, number, new TextEncoder().encode(id)), + () => { + this.#openHanded = true; + if (this.hasNext) host.scheduler.addBulk(this); + }, + ); + } else { + this.#acceptTimer = host.clock.setTimer(ACCEPT_WAIT_MS, () => { + this.#acceptTimer = undefined; + this.#fail(new LinkChannelError("not-accepted"), "not-accepted"); + }); + } + } + + get failed(): boolean { + return this.#failure !== undefined; + } + + get hasNext(): boolean { + return this.#queue.length > 0; + } + + get credit(): number { + if (this.#failure !== undefined || this.#endQueued || this.#stoppedByPeer) return 0; + return Math.max(0, this.#allowance - this.#handed - this.#queuedBytes); + } + + markAccepted(): void { + this.accepted = true; + if (this.#acceptTimer !== undefined) { + this.#host.clock.cancel(this.#acceptTimer); + this.#acceptTimer = undefined; + } + } + + takeNext(): BulkMessage | undefined { + const item = this.#queue.shift(); + if (item === undefined) return undefined; + return { + bytes: item.bytes, + onHanded: () => { + if (item.end) { + this.#endHanded = true; + this.#checkDone(); + return; + } + this.#queuedBytes -= item.payload; + this.#handed += item.payload; + this.#inFlight += 1; + this.#updateStall(); + }, + onWritten: () => { + if (item.end) return; + this.#inFlight -= 1; + this.#updateStall(); + }, + }; + } + + transportMoved(): void { + this.#updateStall(); + } + + onData(payload: Uint8Array): void { + if (this.#failure !== undefined) return; + if (this.#inEnded) return this.#invalid("DATA after the direction ended"); + if (this.#stopSent) return; + if (payload.length > MAX_DATA_BYTES) return this.#invalid("DATA over 64 KiB"); + if (this.#received + payload.length > CHANNEL_WINDOW + this.#granted) { + return this.#invalid("DATA past the allowed bytes"); + } + if (payload.length === 0) return; + this.#received += payload.length; + this.#inQueue.push(payload); + this.#deliver(); + } + + onEnd(): void { + if (this.#failure !== undefined) return; + if (this.#inEnded) return this.#invalid("END after the direction ended"); + this.#inEnded = true; + this.#deliver(); + this.#checkDone(); + } + + onStop(): void { + if (this.#failure !== undefined) return; + if (this.#stoppedByPeer) return this.#invalid("a second STOP for one direction"); + this.#dropQueuedData(); + if (this.#endQueued) return; + this.#stoppedByPeer = true; + this.#queueEnd(); + this.#failOutgoing(new LinkChannelError("stopped")); + } + + onCredit(amount: number | undefined): void { + if (this.#failure !== undefined) return; + if (amount === undefined || amount < 1) return this.#invalid("a CREDIT of 0"); + const taken = this.#handed + this.#queuedBytes; + if (this.#allowance + amount > taken + CHANNEL_WINDOW) { + return this.#invalid("credit beyond 4 MiB outstanding"); + } + this.#allowance += amount; + this.#wakeWriters(); + } + + onReset(reason: ResetReason | undefined): void { + this.#resetReceived = true; + if (this.#failure === undefined) { + this.#fail( + new LinkChannelError(reason ?? "aborted"), + this.#resetQueued ? undefined : "aborted", + ); + } + this.#checkDone(); + } + + closeWith(error: LinkChannelError): void { + this.#resetQueued = true; + this.#done = true; + this.#fail(error, undefined); + } + + abort(reason?: string): void { + if (this.#failure !== undefined) return; + this.#fail(new LinkChannelError("aborted", reason), "aborted"); + } + + #invalid(rule: string): void { + this.#host.logger.warn(`link: channel ${this.id} broke a rule: ${rule}`); + this.#fail(new LinkChannelError("invalid", rule), "invalid"); + } + + #fail(error: LinkChannelError, send: ResetReason | undefined): void { + if (this.#failure !== undefined) return; + this.#failure = error; + this.#clearTimers(); + this.#host.scheduler.removeBulk(this); + this.#queue = []; + this.#queuedBytes = 0; + this.#inQueue = []; + this.#wantRead = false; + this.#failOutgoing(error); + try { + this.#readableController?.error(error); + } catch { + // why: the readable may already be closed or cancelled, and a stream cannot be errored twice. + } + if (send !== undefined && !this.#resetQueued) { + this.#resetQueued = true; + this.#host.scheduler.binary(encodeReset(this.number, send), () => { + this.#resetHanded = true; + this.#checkDone(); + }); + } + this.#checkDone(); + } + + #failOutgoing(error: LinkChannelError): void { + this.#clearStall(); + const pending = this.#pendingWrite; + this.#pendingWrite = undefined; + pending?.reject(error); + for (const waiter of this.#creditWaiters.splice(0)) waiter.reject(error); + try { + this.#writableController?.error(error); + } catch { + // why: the writable may already be closed or errored. + } + } + + #checkDone(): void { + if (this.#done) return; + const ours = this.#resetHanded || this.#endHanded; + const theirs = this.#resetReceived || this.#inEnded; + if (!ours || !theirs) return; + this.#done = true; + this.#clearTimers(); + this.#host.scheduler.removeBulk(this); + this.#host.channelDone(this); + } + + #clearTimers(): void { + this.#clearStall(); + if (this.#acceptTimer !== undefined) { + this.#host.clock.cancel(this.#acceptTimer); + this.#acceptTimer = undefined; + } + } + + #dropQueuedData(): void { + this.#queue = this.#queue.filter((item) => item.end); + this.#queuedBytes = 0; + if (this.#queue.length === 0) this.#host.scheduler.removeBulk(this); + } + + #queueEnd(): void { + this.#endQueued = true; + this.#queue.push({ bytes: encodeEnvelope(ENVELOPE.END, this.number), end: true, payload: 0 }); + if (this.#openHanded) this.#host.scheduler.addBulk(this); + } + + #take(chunk: Uint8Array): void { + for (let offset = 0; offset < chunk.length; offset += MAX_DATA_BYTES) { + const piece = chunk.subarray(offset, Math.min(chunk.length, offset + MAX_DATA_BYTES)); + this.#queue.push({ + bytes: encodeEnvelope(ENVELOPE.DATA, this.number, piece), + end: false, + payload: piece.length, + }); + this.#queuedBytes += piece.length; + } + if (this.#openHanded) this.#host.scheduler.addBulk(this); + } + + #wakeWriters(): void { + const pending = this.#pendingWrite; + this.#pendingWrite = undefined; + pending?.resolve(); + for (const waiter of this.#creditWaiters.splice(0)) waiter.resolve(); + this.#updateStall(); + } + + #updateStall(): void { + const waiting = this.#pendingWrite !== undefined || this.#creditWaiters.length > 0; + const peerHoldsEverything = + this.#queuedBytes === 0 && (this.#host.unsentBytes() === 0 || this.#inFlight === 0); + if (!waiting || !peerHoldsEverything || this.#failure !== undefined) { + this.#clearStall(); + return; + } + if (this.#stallTimer !== undefined) return; + this.#stallTimer = this.#host.clock.setTimer(STALL_WAIT_MS, () => { + this.#stallTimer = undefined; + this.#fail(new LinkChannelError("stalled"), "stalled"); + }); + } + + #clearStall(): void { + if (this.#stallTimer === undefined) return; + this.#host.clock.cancel(this.#stallTimer); + this.#stallTimer = undefined; + } + + #deliver(): void { + const controller = this.#readableController; + if (controller === undefined || !this.#wantRead || this.#stopSent) return; + const chunk = this.#inQueue.shift(); + if (chunk !== undefined) { + this.#wantRead = false; + this.#readTotal += chunk.length; + controller.enqueue(chunk); + this.#grant(); + return; + } + if (this.#inEnded) { + this.#wantRead = false; + controller.close(); + } + } + + #grant(): void { + const unread = this.#readTotal - this.#granted; + if (unread <= 0 || this.#inEnded) return; + if (unread < 64 * KIB && this.#inQueue.length > 0) return; + this.#granted += unread; + this.#host.scheduler.binary(encodeCredit(this.number, unread)); + } + + #cancelReadable(): void { + if (this.#stopSent || this.#failure !== undefined) return; + this.#inQueue = []; + this.#wantRead = false; + if (this.#inEnded) return; + this.#stopSent = true; + this.#host.scheduler.binary(encodeEnvelope(ENVELOPE.STOP, this.number)); + } + + #buildView(): LinkChannel { + const readable = new ReadableStream( + { + start: (controller) => { + this.#readableController = controller; + }, + pull: () => { + this.#wantRead = true; + this.#deliver(); + }, + cancel: () => this.#cancelReadable(), + }, + { highWaterMark: 0 }, + ); + const writable = new WritableStream( + { + start: (controller) => { + this.#writableController = controller; + }, + write: (chunk) => this.#write(chunk), + close: () => { + if (this.#failure !== undefined) throw this.#failure; + if (this.#endQueued) return; + this.#queueEnd(); + const error = new LinkChannelError("closed", "the channel's sending direction ended"); + for (const waiter of this.#creditWaiters.splice(0)) waiter.reject(error); + this.#updateStall(); + }, + abort: (reason) => { + this.abort(reason === undefined ? undefined : String(reason)); + }, + }, + new ByteLengthQueuingStrategy({ highWaterMark: WRITER_BUFFER }), + ); + const currentCredit = () => this.credit; + return { + abort: (reason) => this.abort(reason), + get credit() { + return currentCredit(); + }, + id: this.id, + readable, + whenCredit: () => this.#whenCredit(), + writable, + }; + } + + async #write(chunk: Uint8Array): Promise { + let offset = 0; + while (offset < chunk.length) { + if (this.#failure !== undefined) throw this.#failure; + if (this.#stoppedByPeer) throw new LinkChannelError("stopped"); + const n = Math.min(this.credit, chunk.length - offset); + if (n > 0) { + this.#take(chunk.subarray(offset, offset + n)); + offset += n; + continue; + } + await new Promise((resolve, reject) => { + this.#pendingWrite = { reject, resolve }; + this.#updateStall(); + }); + } + } + + #whenCredit(): Promise { + if (this.#failure !== undefined) return Promise.reject(this.#failure); + if (this.#stoppedByPeer) return Promise.reject(new LinkChannelError("stopped")); + if (this.#endQueued) { + return Promise.reject( + new LinkChannelError("closed", "the channel's sending direction ended"), + ); + } + if (this.credit > 0) return Promise.resolve(); + return new Promise((resolve, reject) => { + this.#creditWaiters.push({ reject, resolve }); + this.#updateStall(); + }); + } +} diff --git a/src/link/envelope.ts b/src/link/envelope.ts new file mode 100644 index 000000000..d21c46818 --- /dev/null +++ b/src/link/envelope.ts @@ -0,0 +1,69 @@ +export const KIB = 1024; +export const MAX_DATA_BYTES = 64 * KIB; +export const CHANNEL_WINDOW = 4 * KIB * KIB; +export const MAX_CHANNEL_NUMBER = 0xffffffff; + +export const ENVELOPE = { OPEN: 1, DATA: 2, END: 3, STOP: 4, CREDIT: 5, RESET: 6 } as const; +export type EnvelopeType = (typeof ENVELOPE)[keyof typeof ENVELOPE]; + +export const RESET_CODES = { aborted: 1, stalled: 2, "not-accepted": 3, invalid: 4 } as const; +export type ResetReason = keyof typeof RESET_CODES; + +const HEADER_BYTES = 5; +const CHANNEL_ID = /^[A-Za-z0-9-]{1,32}$/; + +export interface ParsedEnvelope { + readonly type: number; + readonly number: number; + readonly payload: Uint8Array; +} + +export function encodeEnvelope( + type: EnvelopeType, + number: number, + payload: Uint8Array = new Uint8Array(0), +): Uint8Array { + const bytes = new Uint8Array(HEADER_BYTES + payload.length); + bytes[0] = type; + new DataView(bytes.buffer).setUint32(1, number); + bytes.set(payload, HEADER_BYTES); + return bytes; +} + +export function encodeCredit(number: number, amount: number): Uint8Array { + const payload = new Uint8Array(4); + new DataView(payload.buffer).setUint32(0, amount); + return encodeEnvelope(ENVELOPE.CREDIT, number, payload); +} + +export function encodeReset(number: number, reason: ResetReason): Uint8Array { + return encodeEnvelope(ENVELOPE.RESET, number, new Uint8Array([RESET_CODES[reason]])); +} + +export function parseEnvelope(bytes: Uint8Array): ParsedEnvelope | undefined { + if (bytes.length < HEADER_BYTES) return undefined; + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + return { number: view.getUint32(1), payload: bytes.slice(HEADER_BYTES), type: bytes[0] ?? 0 }; +} + +export function isEnvelopeType(type: number): type is EnvelopeType { + return type >= ENVELOPE.OPEN && type <= ENVELOPE.RESET; +} + +export function parseCredit(payload: Uint8Array): number | undefined { + if (payload.length !== 4) return undefined; + return new DataView(payload.buffer, payload.byteOffset, payload.byteLength).getUint32(0); +} + +export function parseResetReason(payload: Uint8Array): ResetReason | undefined { + const code = payload[0]; + for (const [reason, value] of Object.entries(RESET_CODES)) { + if (value === code) return reason as ResetReason; + } + return undefined; +} + +export function parseChannelId(payload: Uint8Array): string | undefined { + const id = new TextDecoder().decode(payload); + return CHANNEL_ID.test(id) ? id : undefined; +} diff --git a/src/link/index.ts b/src/link/index.ts index 51cfd0778..13e5afd1b 100644 --- a/src/link/index.ts +++ b/src/link/index.ts @@ -1,31 +1,17 @@ import type { Clock, IpcConnection, Logger, UplinkTransportConnection } from "../ports/index.js"; +import { Channel, LinkChannelError, type ChannelHost, type LinkChannel } from "./channel.js"; +import { + ENVELOPE, + MAX_CHANNEL_NUMBER, + isEnvelopeType, + parseChannelId, + parseCredit, + parseEnvelope, + parseResetReason, +} from "./envelope.js"; +import { Scheduler } from "./scheduler.js"; -export type LinkChannelErrorReason = - | "aborted" - | "invalid" - | "not-accepted" - | "stalled" - | "closed" - | "stopped"; - -export class LinkChannelError extends Error { - constructor( - readonly reason: LinkChannelErrorReason, - message?: string, - ) { - super(message ?? reason); - this.name = "LinkChannelError"; - } -} - -export interface LinkChannel { - readonly id: string; - readonly readable: ReadableStream; - readonly writable: WritableStream; - abort(reason?: string): void; - readonly credit: number; - whenCredit(): Promise; -} +export { LinkChannelError, type LinkChannel, type LinkChannelErrorReason } from "./channel.js"; export interface LinkConnection extends IpcConnection { openChannel(options: { readonly signal: AbortSignal }): Promise; @@ -39,27 +25,258 @@ export interface LinkOptions { readonly firstChannelNumber?: number; } +const OPEN_LIMIT = 64; + +interface OpenWaiter { + readonly resolve: (channel: LinkChannel) => void; + readonly reject: (error: unknown) => void; + readonly signal: AbortSignal; + readonly onAbort: () => void; +} + +class Link implements LinkConnection, ChannelHost { + readonly clock: Clock; + readonly logger: Logger; + readonly scheduler: Scheduler; + readonly #transport: UplinkTransportConnection; + readonly #ownParity: number; + readonly #channels = new Map(); + readonly #unaccepted = new Map(); + readonly #waiters: OpenWaiter[] = []; + readonly #dataListeners = new Set<(chunk: string) => void>(); + readonly #closeListeners = new Set<() => void>(); + readonly #errorListeners = new Set<(error: Error) => void>(); + readonly #pendingText: string[] = []; + #nextOwn: number; + #highestPeer = 0; + #ownOpen = 0; + #peerOpen = 0; + #closed = false; + + constructor(transport: UplinkTransportConnection, options: LinkOptions) { + this.clock = options.clock; + this.logger = options.logger; + this.#transport = transport; + this.#ownParity = options.end === "worker" ? 1 : 0; + this.#nextOwn = options.firstChannelNumber ?? (options.end === "worker" ? 1 : 2); + this.scheduler = new Scheduler(transport); + transport.onData((chunk) => this.#onText(chunk)); + transport.onBinary((bytes) => this.#onBinary(bytes)); + transport.onError((error) => { + for (const listener of this.#errorListeners) listener(error); + }); + transport.onSent(() => { + for (const channel of this.#channels.values()) channel.transportMoved(); + }); + transport.onClose(() => this.#onTransportClosed()); + } + + get closed(): boolean { + return this.#closed || this.#transport.closed; + } + + unsentBytes(): number { + return this.#transport.unsentBytes; + } + + onData(listener: (chunk: string) => void): () => void { + this.#dataListeners.add(listener); + if (this.#pendingText.length > 0) { + for (const chunk of this.#pendingText.splice(0)) listener(chunk); + } + return () => { + this.#dataListeners.delete(listener); + }; + } + + onClose(listener: () => void): () => void { + if (this.#closed) { + listener(); + return () => {}; + } + this.#closeListeners.add(listener); + return () => { + this.#closeListeners.delete(listener); + }; + } + + onError(listener: (error: Error) => void): () => void { + this.#errorListeners.add(listener); + return () => { + this.#errorListeners.delete(listener); + }; + } + + write(contents: string): Promise { + return this.scheduler.text(contents); + } + + async close(): Promise { + await this.#transport.close(); + this.#onTransportClosed(); + } + + openChannel(options: { readonly signal: AbortSignal }): Promise { + const { signal } = options; + if (this.#closed) return Promise.reject(new LinkChannelError("closed")); + if (signal.aborted) return Promise.reject(signal.reason); + if (this.#ownOpen < OPEN_LIMIT && this.#waiters.length === 0) { + try { + return Promise.resolve(this.#open().view); + } catch (error: unknown) { + return Promise.reject(error); + } + } + return new Promise((resolve, reject) => { + const onAbort = () => { + const at = this.#waiters.findIndex((waiter) => waiter.onAbort === onAbort); + if (at >= 0) this.#waiters.splice(at, 1); + reject(signal.reason); + }; + signal.addEventListener("abort", onAbort, { once: true }); + this.#waiters.push({ onAbort, reject, resolve, signal }); + }); + } + + acceptChannel(id: string): LinkChannel { + const channel = this.#unaccepted.get(id); + if (channel === undefined) { + throw new Error(`channel ${id} was not opened by the peer, or was already accepted or ended`); + } + this.#unaccepted.delete(id); + channel.markAccepted(); + return channel.view; + } + + channelDone(channel: Channel): void { + if (this.#channels.get(channel.number) !== channel) return; + this.#forget(channel); + this.#drainWaiters(); + } + + #forget(channel: Channel): void { + this.#channels.delete(channel.number); + if (this.#unaccepted.get(channel.id) === channel) this.#unaccepted.delete(channel.id); + if (channel.ownedByUs) this.#ownOpen -= 1; + else this.#peerOpen -= 1; + } + + #open(): Channel { + if (this.#nextOwn > MAX_CHANNEL_NUMBER) { + this.logger.warn("link: this side has used every channel number on the connection"); + throw new Error("the link has no channel numbers left on this connection"); + } + const number = this.#nextOwn; + this.#nextOwn += 2; + let id = randomId(); + while (this.#channels.size > 0 && [...this.#channels.values()].some((c) => c.id === id)) { + id = randomId(); + } + const channel = new Channel(this, number, id, true); + this.#channels.set(number, channel); + this.#ownOpen += 1; + return channel; + } + + #drainWaiters(): void { + while (this.#waiters.length > 0 && this.#ownOpen < OPEN_LIMIT && !this.#closed) { + const waiter = this.#waiters.shift(); + if (waiter === undefined) break; + waiter.signal.removeEventListener("abort", waiter.onAbort); + try { + waiter.resolve(this.#open().view); + } catch (error: unknown) { + waiter.reject(error); + } + } + } + + #onText(chunk: string): void { + if (this.#dataListeners.size === 0) { + this.#pendingText.push(chunk); + return; + } + for (const listener of this.#dataListeners) listener(chunk); + } + + #onTransportClosed(): void { + if (this.#closed) return; + this.#closed = true; + this.scheduler.close(); + for (const waiter of this.#waiters.splice(0)) { + waiter.signal.removeEventListener("abort", waiter.onAbort); + waiter.reject(new LinkChannelError("closed")); + } + const error = new LinkChannelError("closed"); + for (const channel of this.#channels.values()) channel.closeWith(error); + this.#channels.clear(); + this.#unaccepted.clear(); + for (const listener of this.#closeListeners) listener(); + } + + #warn(rule: string): void { + this.logger.warn(`link: dropped a message from the peer: ${rule}`); + } + + #onBinary(bytes: Uint8Array): void { + const envelope = parseEnvelope(bytes); + if (envelope === undefined) return this.#warn("a message too short to read"); + if (!isEnvelopeType(envelope.type)) return this.#warn("an unknown envelope type"); + if (envelope.type === ENVELOPE.OPEN) return this.#onOpen(envelope.number, envelope.payload); + const channel = this.#channels.get(envelope.number); + if (channel === undefined) { + if (!this.#isLate(envelope.number)) this.#warn("a channel number the peer never opened"); + return; + } + switch (envelope.type) { + case ENVELOPE.DATA: + return channel.onData(envelope.payload); + case ENVELOPE.END: + return channel.onEnd(); + case ENVELOPE.STOP: + return channel.onStop(); + case ENVELOPE.CREDIT: + return channel.onCredit(parseCredit(envelope.payload)); + case ENVELOPE.RESET: + return channel.onReset(parseResetReason(envelope.payload)); + } + } + + #isLate(number: number): boolean { + if (number < 1) return false; + if (number % 2 === this.#ownParity) return number < this.#nextOwn; + return number <= this.#highestPeer; + } + + #onOpen(number: number, payload: Uint8Array): void { + if (number % 2 === this.#ownParity || number < 1) + return this.#warn("an OPEN with the wrong parity"); + if (number <= this.#highestPeer) { + return this.#warn( + this.#channels.has(number) + ? "an OPEN reusing a live number" + : "an OPEN reusing an ended number", + ); + } + if (this.#peerOpen >= OPEN_LIMIT) return this.#warn("a 65th OPEN from the peer"); + const id = parseChannelId(payload); + if (id === undefined) return this.#warn("an OPEN with an id outside [A-Za-z0-9-]{1,32}"); + if (this.#unaccepted.has(id)) return this.#warn("an OPEN reusing an id not yet accepted"); + this.#highestPeer = number; + const channel = new Channel(this, number, id, false); + this.#channels.set(number, channel); + this.#unaccepted.set(id, channel); + this.#peerOpen += 1; + } +} + +function randomId(): string { + return crypto.randomUUID().replaceAll("-", ""); +} + export function createLink( - _transport: UplinkTransportConnection, - _options: LinkOptions, + transport: UplinkTransportConnection, + options: LinkOptions, ): LinkConnection { - return { - closed: false, - onData: () => () => {}, - onClose: () => () => {}, - onError: () => () => {}, - write: async () => {}, - close: async () => {}, - openChannel: () => Promise.reject(new Error("the link module is not built yet")), - acceptChannel: (id) => ({ - abort: () => {}, - credit: 0, - id, - readable: new ReadableStream({ - start: (controller) => controller.error(new LinkChannelError("closed")), - }), - whenCredit: () => Promise.resolve(), - writable: new WritableStream(), - }), - }; + return new Link(transport, options); } diff --git a/src/link/scheduler.ts b/src/link/scheduler.ts new file mode 100644 index 000000000..12726ce36 --- /dev/null +++ b/src/link/scheduler.ts @@ -0,0 +1,132 @@ +import type { UplinkTransportConnection } from "../ports/index.js"; +import { KIB } from "./envelope.js"; + +const UNSENT_MARK = 256 * KIB; +const PRIORITY_SHARE = 64 * KIB; + +export interface BulkMessage { + readonly bytes: Uint8Array; + onHanded(): void; + onWritten(): void; +} + +export interface BulkSource { + takeNext(): BulkMessage | undefined; + readonly hasNext: boolean; +} + +type PriorityMessage = + | { readonly kind: "text"; readonly text: string; readonly resolve: () => void } + | { readonly kind: "binary"; readonly bytes: Uint8Array; readonly onHanded?: () => void }; + +export class Scheduler { + readonly #transport: UplinkTransportConnection; + readonly #priority: PriorityMessage[] = []; + readonly #ring: BulkSource[] = []; + readonly #inRing = new Set(); + #prioritySinceBulk = 0; + #pumping = false; + #scheduled = false; + #closed = false; + + constructor(transport: UplinkTransportConnection) { + this.#transport = transport; + transport.onSent(() => this.wake()); + } + + text(text: string): Promise { + if (this.#closed) return Promise.resolve(); + return new Promise((resolve) => { + this.#priority.push({ kind: "text", resolve, text }); + this.wake(); + }); + } + + binary(bytes: Uint8Array, onHanded?: () => void): void { + if (this.#closed) return; + this.#priority.push( + onHanded === undefined ? { bytes, kind: "binary" } : { bytes, kind: "binary", onHanded }, + ); + this.wake(); + } + + addBulk(source: BulkSource): void { + if (this.#inRing.has(source)) return; + this.#inRing.add(source); + this.#ring.push(source); + this.wake(); + } + + removeBulk(source: BulkSource): void { + if (!this.#inRing.delete(source)) return; + this.#ring.splice(this.#ring.indexOf(source), 1); + } + + wake(): void { + if (this.#scheduled || this.#closed) return; + this.#scheduled = true; + queueMicrotask(() => { + this.#scheduled = false; + this.#pump(); + }); + } + + close(): void { + this.#closed = true; + for (const message of this.#priority.splice(0)) { + if (message.kind === "text") message.resolve(); + } + this.#ring.length = 0; + this.#inRing.clear(); + } + + #pump(): void { + if (this.#pumping) return; + this.#pumping = true; + try { + while (!this.#closed) { + const canBulk = this.#ring.length > 0 && this.#transport.unsentBytes < UNSENT_MARK; + const bulkDue = canBulk && this.#prioritySinceBulk >= PRIORITY_SHARE; + if (this.#priority.length > 0 && !bulkDue) { + this.#sendPriority(); + } else if (canBulk) { + this.#sendBulk(); + } else { + break; + } + } + } finally { + this.#pumping = false; + } + } + + #sendPriority(): void { + const message = this.#priority.shift(); + if (message === undefined) return; + if (message.kind === "text") { + this.#prioritySinceBulk += Buffer.byteLength(message.text); + const done = () => message.resolve(); + this.#transport.write(message.text).then(done, done); + return; + } + this.#prioritySinceBulk += message.bytes.length; + message.onHanded?.(); + this.#transport.writeBinary(message.bytes).catch(() => undefined); + } + + #sendBulk(): void { + const source = this.#ring.shift(); + if (source === undefined) return; + const message = source.takeNext(); + if (source.hasNext) { + this.#ring.push(source); + } else { + this.#inRing.delete(source); + } + if (message === undefined) return; + this.#prioritySinceBulk = 0; + message.onHanded(); + const written = () => message.onWritten(); + this.#transport.writeBinary(message.bytes).then(written, written); + } +} diff --git a/src/link/test-support.ts b/src/link/test-support.ts index 1267a3396..024c364d9 100644 --- a/src/link/test-support.ts +++ b/src/link/test-support.ts @@ -318,7 +318,7 @@ export async function readAll(readable: ReadableStream): Promise { From 52addc34e74d3ce52182c8ec8e78bca3064e4495 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 14:40:50 +0200 Subject: [PATCH 4/8] chore(link): fallow findings, a smaller message handler 0 failing -> 0 failing --- src/link/channel.ts | 4 ---- src/link/envelope.ts | 2 +- src/link/index.ts | 10 +++++++++- src/link/test-support.ts | 2 +- src/ports/uplink-websocket.ts | 18 +++++++----------- 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/link/channel.ts b/src/link/channel.ts index ef3d81443..b49e79b35 100644 --- a/src/link/channel.ts +++ b/src/link/channel.ts @@ -120,10 +120,6 @@ export class Channel implements BulkSource { } } - get failed(): boolean { - return this.#failure !== undefined; - } - get hasNext(): boolean { return this.#queue.length > 0; } diff --git a/src/link/envelope.ts b/src/link/envelope.ts index d21c46818..9c7acb970 100644 --- a/src/link/envelope.ts +++ b/src/link/envelope.ts @@ -6,7 +6,7 @@ export const MAX_CHANNEL_NUMBER = 0xffffffff; export const ENVELOPE = { OPEN: 1, DATA: 2, END: 3, STOP: 4, CREDIT: 5, RESET: 6 } as const; export type EnvelopeType = (typeof ENVELOPE)[keyof typeof ENVELOPE]; -export const RESET_CODES = { aborted: 1, stalled: 2, "not-accepted": 3, invalid: 4 } as const; +const RESET_CODES = { aborted: 1, stalled: 2, "not-accepted": 3, invalid: 4 } as const; export type ResetReason = keyof typeof RESET_CODES; const HEADER_BYTES = 5; diff --git a/src/link/index.ts b/src/link/index.ts index 13e5afd1b..316f41a15 100644 --- a/src/link/index.ts +++ b/src/link/index.ts @@ -8,10 +8,14 @@ import { parseCredit, parseEnvelope, parseResetReason, + type ParsedEnvelope, } from "./envelope.js"; import { Scheduler } from "./scheduler.js"; -export { LinkChannelError, type LinkChannel, type LinkChannelErrorReason } from "./channel.js"; +// fallow-ignore-next-line unused-re-export -- the link's public surface; #558 is its first user. +export { LinkChannelError } from "./channel.js"; +// fallow-ignore-next-line unused-re-export-type -- the link's public surface; #558 is its first user. +export type { LinkChannel, LinkChannelErrorReason } from "./channel.js"; export interface LinkConnection extends IpcConnection { openChannel(options: { readonly signal: AbortSignal }): Promise; @@ -228,6 +232,10 @@ class Link implements LinkConnection, ChannelHost { if (!this.#isLate(envelope.number)) this.#warn("a channel number the peer never opened"); return; } + this.#dispatch(channel, envelope); + } + + #dispatch(channel: Channel, envelope: ParsedEnvelope): void { switch (envelope.type) { case ENVELOPE.DATA: return channel.onData(envelope.payload); diff --git a/src/link/test-support.ts b/src/link/test-support.ts index 024c364d9..9546947e9 100644 --- a/src/link/test-support.ts +++ b/src/link/test-support.ts @@ -35,7 +35,7 @@ export function envelope(type: number, number: number, payload = new Uint8Array( return bytes; } -export function parseEnvelope(bytes: Uint8Array): Envelope { +function parseEnvelope(bytes: Uint8Array): Envelope { return { type: bytes[0] ?? -1, number: new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(1), diff --git a/src/ports/uplink-websocket.ts b/src/ports/uplink-websocket.ts index 2bf9df608..848ae059d 100644 --- a/src/ports/uplink-websocket.ts +++ b/src/ports/uplink-websocket.ts @@ -42,6 +42,11 @@ import { * and every reader buffers by newline, so a message boundary that does not line up with a * frame boundary is harmless either way. */ +function rawBytes(data: RawData): Buffer { + if (Array.isArray(data)) return Buffer.concat(data); + return Buffer.isBuffer(data) ? data : Buffer.from(data as ArrayBuffer); +} + class WebSocketUplinkConnection implements UplinkTransportConnection { readonly #socket: WebSocket; readonly #dataListeners = new Set<(chunk: string) => void>(); @@ -67,22 +72,13 @@ class WebSocketUplinkConnection implements UplinkTransportConnection { constructor(socket: WebSocket) { this.#socket = socket; socket.on("message", (data: RawData, isBinary: boolean) => { + const bytes = rawBytes(data); if (isBinary) { // why: with no listener the message is dropped, so nothing piles up before a link subscribes. - if (this.#binaryListeners.size === 0) return; - const bytes = Array.isArray(data) - ? Buffer.concat(data) - : Buffer.isBuffer(data) - ? data - : Buffer.from(data as ArrayBuffer); for (const listener of this.#binaryListeners) listener(bytes); return; } - const chunk = Array.isArray(data) - ? Buffer.concat(data).toString("utf8") - : Buffer.isBuffer(data) - ? data.toString("utf8") - : Buffer.from(data as ArrayBuffer).toString("utf8"); + const chunk = bytes.toString("utf8"); if (this.#dataListeners.size === 0) { this.#pending.push(chunk); return; From 0e9d0f2ec9ee14cd93ecc58f600258c2c03ada93 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 14:41:10 +0200 Subject: [PATCH 5/8] chore(link): fallow suppression kinds 0 failing -> 0 failing --- src/link/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/link/index.ts b/src/link/index.ts index 316f41a15..ed110f2ab 100644 --- a/src/link/index.ts +++ b/src/link/index.ts @@ -12,9 +12,9 @@ import { } from "./envelope.js"; import { Scheduler } from "./scheduler.js"; -// fallow-ignore-next-line unused-re-export -- the link's public surface; #558 is its first user. +// 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-re-export-type -- the link's public surface; #558 is its first user. +// 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 { From 84b912396835b7767edfa32fd64f1bde7f267336 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 14:48:37 +0200 Subject: [PATCH 6/8] test(link): credit batching, cancel after END, a failed pair closes, text send fires onSent (#556) --- src/link/link-channels.test.ts | 24 ++++++++++++++++++++---- src/link/link-messages.test.ts | 3 ++- src/ports/uplink-websocket.test.ts | 12 ++++++++++++ 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/link/link-channels.test.ts b/src/link/link-channels.test.ts index eb61481d8..e6aacf3b0 100644 --- a/src/link/link-channels.test.ts +++ b/src/link/link-channels.test.ts @@ -472,15 +472,31 @@ describe("link byte channels: ending", () => { const pair = linkPair(); const { g, w } = await openPair(pair); await writeAndClose(g, pattern(0, 10)); - const reader = w.readable.getReader(); - await readAtLeast(reader, 10); - await reader.read(); await settle(); - await reader.cancel(); + await w.readable.cancel(); await settle(); expect(pair.workerTap.binaries(TYPE.STOP)).toEqual([]); + expect(pair.gatewayLog.problems()).toEqual([]); + }); + + it("grants credit once per 64 KiB read, or when the reader has read everything it holds", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + const writer = g.writable.getWriter(); + for (let i = 0; i < 100; i += 1) await writer.write(pattern(i * KiB, KiB)); + await settle(); + + const reader = w.readable.getReader(); + let read = 0; + while (read < 100 * KiB) read += (await reader.read()).value?.length ?? 0; + await settle(); + + const grants = pair.workerTap + .binaries(TYPE.CREDIT) + .map((e) => new DataView(e.payload.buffer, e.payload.byteOffset).getUint32(0)); + expect(grants).toEqual([64 * KiB, 36 * KiB]); }); it("abort(\"why\") on one side errors both streams on both sides with aborted; the aborting side's error message is why and the peer's carries no reason string", async () => { diff --git a/src/link/link-messages.test.ts b/src/link/link-messages.test.ts index 4da190add..a390267a2 100644 --- a/src/link/link-messages.test.ts +++ b/src/link/link-messages.test.ts @@ -77,7 +77,7 @@ describe("link text messages", () => { expect(closed).toHaveBeenCalledTimes(1); }); - it("a pair's fail(error) reaches onError", async () => { + it("a pair's fail(error) reaches onError and closes that end", async () => { const { gatewayEnd, gateway } = linkPair(); const errors: Error[] = []; gateway.onError((error) => errors.push(error)); @@ -86,6 +86,7 @@ describe("link text messages", () => { await settle(); expect(errors.map((error) => error.message)).toEqual(["socket reset"]); + expect(gatewayEnd.closed).toBe(true); }); it("closing the transport fails every open channel with closed", async () => { diff --git a/src/ports/uplink-websocket.test.ts b/src/ports/uplink-websocket.test.ts index 2f97b4c4e..b8d10976a 100644 --- a/src/ports/uplink-websocket.test.ts +++ b/src/ports/uplink-websocket.test.ts @@ -206,4 +206,16 @@ describe("WebSocketUplinkConnection binary messages", () => { expect(worker.unsentBytes).toBe(0); expect(onSent).toHaveBeenCalled(); }); + + it("onSent fires when a text send completes", async () => { + const { accepted, url } = await startAcceptingGateway(); + const worker = await new WebSocketUplinkConnector().connect(dialOptions(url)); + await accepted; + const onSent = vi.fn(); + worker.onSent(onSent); + + await worker.write("hello"); + + expect(onSent).toHaveBeenCalledTimes(1); + }); }); From cdf8ed0160da2d5fd2a8653f4390520fde443284 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 15:07:43 +0200 Subject: [PATCH 7/8] fix(link): a failed channel still counts the peer's END, tests fail on named assertions, claims on the WebSocket wrapper (#556) --- src/link/channel.ts | 7 ++- src/link/link-channels.test.ts | 100 ++++++++++++++++++++++++++------- src/link/link-rules.test.ts | 6 +- src/link/test-support.ts | 23 ++++++++ src/ports/uplink-websocket.ts | 6 -- 5 files changed, 115 insertions(+), 27 deletions(-) diff --git a/src/link/channel.ts b/src/link/channel.ts index b49e79b35..24208fade 100644 --- a/src/link/channel.ts +++ b/src/link/channel.ts @@ -180,7 +180,12 @@ export class Channel implements BulkSource { } onEnd(): void { - if (this.#failure !== undefined) return; + if (this.#failure !== undefined) { + // why: the peer's END still ends its direction after this side failed; the slot frees once both are done. + this.#inEnded = true; + this.#checkDone(); + return; + } if (this.#inEnded) return this.#invalid("END after the direction ended"); this.#inEnded = true; this.#deliver(); diff --git a/src/link/link-channels.test.ts b/src/link/link-channels.test.ts index e6aacf3b0..cf38724b2 100644 --- a/src/link/link-channels.test.ts +++ b/src/link/link-channels.test.ts @@ -9,6 +9,7 @@ import { KiB, linkPair, MiB, + outcome, pattern, patternHash, pump, @@ -211,10 +212,14 @@ describe("link byte channels: transfer", () => { await settle(); expect(resolved).toBe(false); const received = drain(w.readable); - await write; + expect((await outcome(write)).state).toBe("resolved"); await writer.close(); - expect(await received).toEqual({ hash: patternHash(20 * MiB), length: 20 * MiB }); + const arrived = await outcome(received); + expect(arrived).toEqual({ + state: "resolved", + value: { hash: patternHash(20 * MiB), length: 20 * MiB }, + }); }); it("one channel's stalled reader does not slow another channel on the same link", async () => { @@ -246,10 +251,14 @@ describe("link byte channels: credit and stalls", () => { pair.clock.advance(60_000); await settle(); - await expect(writer.closed).rejects.toMatchObject({ reason: "stalled" }); - await expect(errorOfRead(g.readable)).resolves.toMatchObject({ reason: "stalled" }); - await expect(errorOfRead(w.readable)).resolves.toMatchObject({ reason: "stalled" }); - await expect(errorOfWritable(w.writable)).resolves.toMatchObject({ reason: "stalled" }); + const stalled = { state: "resolved", value: { reason: "stalled" } }; + expect(await outcome(writer.closed)).toMatchObject({ + state: "rejected", + error: { reason: "stalled" }, + }); + expect(await outcome(errorOfRead(g.readable))).toMatchObject(stalled); + expect(await outcome(errorOfRead(w.readable))).toMatchObject(stalled); + expect(await outcome(errorOfWritable(w.writable))).toMatchObject(stalled); }); it("a reader that reads 64 KiB every 50 s keeps a 10 MiB transfer going without a reset", async () => { @@ -302,8 +311,10 @@ describe("link byte channels: credit and stalls", () => { expect(resolved).toBe(false); await readAtLeast(w.readable.getReader(), 64 * KiB); - await waiting; + await settle(); + expect(resolved).toBe(true); + await waiting; expect(g.credit).toBeGreaterThan(0); }); @@ -311,45 +322,50 @@ describe("link byte channels: credit and stalls", () => { const pair = linkPair(); const { g, w } = await openPair(pair); await fillWindow(g.writable); - const failed = expect(g.whenCredit()).rejects.toMatchObject({ reason: "aborted" }); + const waiting = outcome(g.whenCredit()); w.abort(); - await failed; + expect(await waiting).toMatchObject({ state: "rejected", error: { reason: "aborted" } }); }); it("whenCredit() rejects when the peer stops that direction", async () => { const pair = linkPair(); const { g, w } = await openPair(pair); await fillWindow(g.writable); - const stopped = expect(g.whenCredit()).rejects.toMatchObject({ reason: "stopped" }); + const waiting = outcome(g.whenCredit()); await w.readable.cancel(); - await stopped; + expect(await waiting).toMatchObject({ state: "rejected", error: { reason: "stopped" } }); }); it("whenCredit() rejects when this side closes its own writable", async () => { const pair = linkPair(); const { g } = await openPair(pair); const writer = await fillWindow(g.writable); - const ended = expect(g.whenCredit()).rejects.toBeInstanceOf(Error); + const waiting = outcome(g.whenCredit()); await writer.close(); - await ended; + const ended = await waiting; + expect(ended.state).toBe("rejected"); + expect((ended as { error: unknown }).error).toBeInstanceOf(Error); }); it("a whenCredit() pending 60 s, with the peer holding every byte and granting nothing, errors the channel stalled", async () => { const pair = linkPair(); const { g, w } = await openPair(pair); await fillWindow(g.writable); - const waiting = expect(g.whenCredit()).rejects.toMatchObject({ reason: "stalled" }); + const waiting = outcome(g.whenCredit()); pair.clock.advance(60_000); - await waiting; - await expect(errorOfRead(w.readable)).resolves.toMatchObject({ reason: "stalled" }); + expect(await waiting).toMatchObject({ state: "rejected", error: { reason: "stalled" } }); + expect(await outcome(errorOfRead(w.readable))).toMatchObject({ + state: "resolved", + value: { reason: "stalled" }, + }); }); it("with the transport held for 90 s and a write waiting behind it, the channel is not reset", async () => { @@ -364,10 +380,13 @@ describe("link byte channels: credit and stalls", () => { await settle(); pair.gatewayEnd.release(); const received = drain(w.readable); - await write; + expect((await outcome(write)).state).toBe("resolved"); await writer.close(); - expect(await received).toEqual({ hash: patternHash(8 * MiB), length: 8 * MiB }); + expect(await outcome(received)).toEqual({ + state: "resolved", + value: { hash: patternHash(8 * MiB), length: 8 * MiB }, + }); expect(pair.gatewayLog.problems()).toEqual([]); }); @@ -408,6 +427,20 @@ describe("link byte channels: ending", () => { await expect(readAll(w.readable)).resolves.toEqual(pattern(0, 1000)); }); + it("after one side closes its writable, the other side's bytes still travel back to the side that closed", async () => { + const pair = linkPair(); + const { g, w } = await openPair(pair); + + await g.writable.getWriter().close(); + await settle(); + await writeAndClose(w, pattern(0, 700)); + + expect(await outcome(readAll(g.readable))).toEqual({ + state: "resolved", + value: pattern(0, 700), + }); + }); + it("cancelling a readable errors the peer's writable with stopped, and the other direction still carries bytes to its end", async () => { const pair = linkPair(); const { g, w } = await openPair(pair); @@ -656,6 +689,23 @@ describe("link byte channels: the 64 channel limit", () => { expect(state).toBe("opened"); }); + it("an abort after this side's END was written, with the peer's END still in flight, frees the slot once that END arrives", async () => { + const pair = linkPair(); + const open = await open64(pair); + const { g, w } = open[0]!; + pair.workerEnd.hold(); + await g.writable.getWriter().close(); + await w.writable.getWriter().close(); + await settle(); + + g.abort(); + await settle(); + pair.workerEnd.release(); + const next = pair.gateway.openChannel({ signal: signal() }); + + expect((await outcome(next)).state).toBe("resolved"); + }); + it("the 65th openChannel rejects with the signal's reason when its signal aborts first", async () => { const pair = linkPair(); await open64(pair); @@ -708,10 +758,22 @@ describe("link byte channels: the 64 channel limit", () => { const pair = linkPair(); const open = await open64(pair); pair.gatewayEnd.hold(); + // why: a held transport only refuses bulk messages once 256 KiB sit unsent, so fill it + // from another channel; this channel's END then waits behind it and is not yet written. + void open[1]!.g.writable + .getWriter() + .write(pattern(0, MiB)) + .catch(() => undefined); + await settle(); - const next = pair.gateway.openChannel({ signal: signal() }); + let state = "pending"; + const next = pair.gateway.openChannel({ signal: signal() }).then((opened) => { + state = "opened"; + return opened; + }); const ending = endChannel(open[0]!.g, open[0]!.w); await settle(); + expect(state).toBe("pending"); pair.gatewayEnd.release(); await ending; const channel = await next; diff --git a/src/link/link-rules.test.ts b/src/link/link-rules.test.ts index ad4b3461f..7ec68ee32 100644 --- a/src/link/link-rules.test.ts +++ b/src/link/link-rules.test.ts @@ -172,7 +172,11 @@ const dropped: Dropped[] = [ { name: "an unknown envelope type", run: async (peer) => { - await peer.raw.writeBinary(envelope(99, 4)); + await acceptRaw(peer); + await peer.raw.writeBinary(envelope(99, 2)); + await settle(); + expect(peer.log.problems().join("\n")).toContain("an unknown envelope type"); + expect(resets(peer, 2)).toEqual([]); }, }, { diff --git a/src/link/test-support.ts b/src/link/test-support.ts index 9546947e9..e0ae310b7 100644 --- a/src/link/test-support.ts +++ b/src/link/test-support.ts @@ -160,6 +160,29 @@ export class RecordingLogger implements Logger { } } +export type Outcome = + | { readonly state: "resolved"; readonly value: T } + | { readonly state: "rejected"; readonly error: unknown } + | { readonly state: "pending" }; + +export async function outcome(promise: Promise, ms = 2000): Promise> { + let timer: NodeJS.Timeout | undefined; + const pending = new Promise>((resolve) => { + timer = setTimeout(() => resolve({ state: "pending" }), ms); + }); + try { + return await Promise.race([ + promise.then( + (value): Outcome => ({ state: "resolved", value }), + (error: unknown): Outcome => ({ state: "rejected", error }), + ), + pending, + ]); + } finally { + clearTimeout(timer); + } +} + export async function settle(): Promise { for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setImmediate(resolve)); } diff --git a/src/ports/uplink-websocket.ts b/src/ports/uplink-websocket.ts index 848ae059d..32bb9274c 100644 --- a/src/ports/uplink-websocket.ts +++ b/src/ports/uplink-websocket.ts @@ -36,12 +36,6 @@ import { type UplinkTransportConnection, } from "./uplink.js"; -/** - * Wraps one WebSocket as the `IpcConnection` the daemon protocol expects. Each protocol frame - * is sent as its own text message; frames are already newline-terminated by `serializeFrame` - * and every reader buffers by newline, so a message boundary that does not line up with a - * frame boundary is harmless either way. - */ function rawBytes(data: RawData): Buffer { if (Array.isArray(data)) return Buffer.concat(data); return Buffer.isBuffer(data) ? data : Buffer.from(data as ArrayBuffer); From 9098f451bd8d3f9da91638982c2fbba34d6c542f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 14 Oct 2026 17:07:49 +0200 Subject: [PATCH 8/8] fix(link): test support reaches the WebSocket adapters through the ports testing entry (#556) --- src/link/test-support.ts | 5 +---- src/ports/testing.ts | 2 ++ 2 files changed, 3 insertions(+), 4 deletions(-) create mode 100644 src/ports/testing.ts diff --git a/src/link/test-support.ts b/src/link/test-support.ts index e0ae310b7..84ea2532b 100644 --- a/src/link/test-support.ts +++ b/src/link/test-support.ts @@ -9,10 +9,7 @@ import { type MemoryTransportConnection, type UplinkTransportConnection, } from "../ports/index.js"; -import { - WebSocketUplinkConnector, - WebSocketUplinkListenerFactory, -} from "../ports/uplink-websocket.js"; +import { WebSocketUplinkConnector, WebSocketUplinkListenerFactory } from "../ports/testing.js"; import { createLink, type LinkChannel, type LinkConnection } from "./index.js"; export const KiB = 1024; diff --git a/src/ports/testing.ts b/src/ports/testing.ts new file mode 100644 index 000000000..57af6ad66 --- /dev/null +++ b/src/ports/testing.ts @@ -0,0 +1,2 @@ +// why: the real WebSocket adapters stay out of the ports barrel so the CLI never loads `ws`; tests that need them import them from here. +export { WebSocketUplinkConnector, WebSocketUplinkListenerFactory } from "./uplink-websocket.js";