Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions scripts/test-layout/layout-clients.json
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@
"link-supervisor.test.ts": "clients",
"link-status-projection.test.ts": "clients",
"link-traffic.test.ts": "clients",
"held-socket-writes.test.ts": "clients",
"link-traffic-child-status.test.ts": "clients",
"link-request-zstd.test.ts": "clients",
"link-admission-wait.test.ts": "clients",
Expand Down
74 changes: 74 additions & 0 deletions tests/clients/held-socket-writes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { afterEach, expect, test } from "bun:test";
import { EventEmitter } from "node:events";
import { Socket } from "node:net";
import { heldSocketWriteCountForTests, holdLargeSocketWrites, releaseHeldSocketWrites, restoreSocketWrites } from "../helpers/held-socket-writes";

// The shared helper behind the link traffic, request-zstd and relay cases (#8627, #8670). These cases
// drive it with a base write whose native completion the test decides, on an EventEmitter standing in
// for the socket, so every ordering is deterministic on every platform.
type Done = (error?: Error | null) => void;
afterEach(() => { restoreSocketWrites(); });

function controlledBase() {
const pending: Done[] = [];
const base = function (this: Socket, _chunk: unknown, _encoding: BufferEncoding, done: Done) { pending.push(done); };
return { base, pending };
}
const write = (target: EventEmitter, calls: Array<Error | null | undefined>) =>
(Socket.prototype._write as unknown as (this: EventEmitter, chunk: Uint8Array, encoding: string, done: Done) => void)
.call(target, new Uint8Array(8), "buffer", error => { calls.push(error); });

test("a success is held until released, and settles once", () => {
const { base, pending } = controlledBase();
holdLargeSocketWrites(1, base);
const calls: Array<Error | null | undefined> = [];
write(new EventEmitter(), calls);
pending[0]!();
expect(calls).toHaveLength(0);
expect(heldSocketWriteCountForTests()).toBe(1);
releaseHeldSocketWrites();
releaseHeldSocketWrites();
expect(calls).toHaveLength(1);
expect(calls[0]).toBeUndefined();
expect(heldSocketWriteCountForTests()).toBe(0);
});

test("a write error and a closing socket settle at once", () => {
const { base, pending } = controlledBase();
holdLargeSocketWrites(1, base);
const failed: Array<Error | null | undefined> = [], closed: Array<Error | null | undefined> = [];
write(new EventEmitter(), failed);
const socket = new EventEmitter();
write(socket, closed);
pending[0]!(new Error("EPIPE"));
socket.emit("close");
expect(failed.map(error => error?.message)).toEqual(["EPIPE"]);
expect(closed.map(error => (error as { code?: string } | undefined)?.code)).toEqual(["ERR_SOCKET_CLOSED"]);
});

test("a native success after the socket closed is ignored and nothing is kept", () => {
const { base, pending } = controlledBase();
holdLargeSocketWrites(1, base);
const calls: Array<Error | null | undefined> = [];
const socket = new EventEmitter();
write(socket, calls);
socket.emit("close");
pending[0]!();
expect(heldSocketWriteCountForTests()).toBe(0);
releaseHeldSocketWrites();
expect(calls).toHaveLength(1);
});

test("a completion arriving after restore settles at once, even after a new hold began", () => {
const first = controlledBase();
holdLargeSocketWrites(1, first.base);
const calls: Array<Error | null | undefined> = [];
write(new EventEmitter(), calls);
restoreSocketWrites();
const second = controlledBase();
holdLargeSocketWrites(1, second.base);
first.pending[0]!();
expect(calls).toHaveLength(1);
expect(calls[0]).toBeUndefined();
expect(heldSocketWriteCountForTests()).toBe(0);
});
19 changes: 12 additions & 7 deletions tests/clients/link-ws-relay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { CodexSocket, manualTimers, RawCodex, rawUpgrade, startChild } from "../
import { connect, createServer, type Socket } from "node:net";
import { HomeLeg } from "../../src/client/link-websocket";
import { LINK_CHILD_WS_LIMITS } from "../../src/client/link-websocket-limits";
import { holdLargeSocketWrites, releaseHeldSocketWrites, restoreSocketWrites } from "../helpers/held-socket-writes";

// Lane T6, design T4 3.2 and 3.3: a Child carries Codex's Responses WebSocket over its link when the
// Home advertises it, and answers today's 426 otherwise. The Home is a raw-TCP stand-in, so every byte
Expand Down Expand Up @@ -222,13 +223,17 @@ describe("link WebSocket on the Child: an advertising Home", () => {
const { port, home } = await setup();
const codex = await CodexSocket.open(port);
const leg = home.sockets.at(-1)!;
leg.socket.pause(); // the Home stops reading: the first message cannot flush
codex.ws.send("a".repeat(8 * 1024 * 1024 - 64));
codex.ws.send("second");
expect((await codex.closed()).code).toBe(1013);
leg.socket.resume();
expect(await leg.until(frame => frame.type === "close")).toMatchObject({ code: 1001 });
expect(leg.frames.filter(frame => frame.type === "text").map(frame => frame.type === "text" ? frame.data.length : 0)).toEqual([8 * 1024 * 1024 - 64]);
// Windows can take the whole 8 MiB into its socket buffer at once, so pausing the Home alone does
// not keep the first message unflushed there; hold the write's completion until the overload close.
holdLargeSocketWrites(1024 * 1024);
try {
codex.ws.send("a".repeat(8 * 1024 * 1024 - 64));
codex.ws.send("second");
expect((await codex.closed()).code).toBe(1013);
releaseHeldSocketWrites(); // Let the queued close follow the first message to the Home.
expect(await leg.until(frame => frame.type === "close")).toMatchObject({ code: 1001 });
expect(leg.frames.filter(frame => frame.type === "text").map(frame => frame.type === "text" ? frame.data.length : 0)).toEqual([8 * 1024 * 1024 - 64]);
} finally { restoreSocketWrites(); }
});

test("toward a stalled Codex the Child stops reading the Home above 1 MiB and resumes on drain, dropping nothing", async () => {
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/test-layout-expected.json
Original file line number Diff line number Diff line change
Expand Up @@ -1620,7 +1620,7 @@
"client-link-tunnel.test.ts": "clients", "link-ports.test.ts": "clients",
"injection-link-websocket.test.ts": "codex-integration", "link-supervisor.test.ts": "clients",
"link-status-projection.test.ts": "clients", "link-admission-wait.test.ts": "clients",
"link-traffic.test.ts": "clients", "link-traffic-child-status.test.ts": "clients", "link-traffic-status.test.ts": "server", "request-body-log.test.ts": "usage",
"link-traffic.test.ts": "clients", "held-socket-writes.test.ts": "clients", "link-traffic-child-status.test.ts": "clients", "link-traffic-status.test.ts": "server", "request-body-log.test.ts": "usage",
"link-request-zstd.test.ts": "clients", "request-decompress-ratio.test.ts": "usage", "inbound-encoded-body-budget.test.ts": "server",
"link-fingerprint.test.ts": "clients", "cli-link.test.ts": "cli", "cli-link-enrollment.test.ts": "cli", "cli-link-routes.test.ts": "cli", "link-explicit-route.test.ts": "clients", "link-explicit-route-paths.test.ts": "clients", "link-route-edit-exclusive.test.ts": "server", "link-enrollment-explicit-route.test.ts": "server", "cli-link-explicit-route.test.ts": "cli", "link-alias-lock.test.ts": "clients", "link-enrollment-operation.test.ts": "server", "link-full-install-census.test.ts": "clients", "link-revoke-operation.test.ts": "server", "link-operations-routes.test.ts": "server", "cli-link-operation.test.ts": "cli", "link-operations-journal.test.ts": "clients", "link-revoke-suspend.test.ts": "clients",
"link-management-routes.test.ts": "server", "link-enrollment.test.ts": "server", "link-compensation.test.ts": "clients",
Expand Down
45 changes: 39 additions & 6 deletions tests/helpers/held-socket-writes.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { Socket } from "node:net";

type WriteCallback = (error?: Error | null) => void;
type SocketWrite = (this: Socket, chunk: unknown, encoding: BufferEncoding, callback: WriteCallback) => unknown;

const originalWrite = Socket.prototype._write;
const originalWrite: SocketWrite = Socket.prototype._write;

/** One hold, from holdLargeSocketWrites to restoreSocketWrites; its writes keep it after a later hold. */
interface HoldCycle { releasing: boolean; held: Set<() => void> }
let cycle: HoldCycle | null = null;

/**
* Holds the completion of every `node:net` socket write of at least `minBytes`, the way a send
Expand All @@ -13,25 +18,53 @@ const originalWrite = Socket.prototype._write;
* Size alone cannot give a test that state. Bun completes a plain TCP write once the operating system
* accepts it, and Windows can take a whole large nonblocking send into its socket buffer (on the
* Windows runners a 48 MiB write to a Home that never reads it completed immediately). Smaller writes
* (the relay-auth challenge, headers) complete as usual. Undo with {@link restoreSocketWrites}.
* (the relay-auth challenge, headers) complete as usual. A write error and the socket ending or
* closing settle a held write at once; each write settles once. {@link releaseHeldSocketWrites} lets
* successful completions through, and {@link restoreSocketWrites} releases whatever this hold still
* holds before undoing it, so a completion arriving after the restore is never kept by a later hold.
* `base` is the write being wrapped; only the helper's own tests pass one.
*/
export function holdLargeSocketWrites(minBytes: number): void {
export function holdLargeSocketWrites(minBytes: number, base: SocketWrite = originalWrite): void {
const current: HoldCycle = { releasing: false, held: new Set() };
cycle = current;
Socket.prototype._write = function (this: Socket, chunk: unknown, encoding: BufferEncoding, callback: WriteCallback) {
const size = typeof chunk === "string" ? Buffer.byteLength(chunk, encoding) : (chunk as Uint8Array).byteLength;
if (size < minBytes) return originalWrite.call(this, chunk, encoding, callback);
if (size < minBytes) return base.call(this, chunk, encoding, callback);
let settled = false;
const settle = (error: Error) => {
const settle = (error?: Error) => {
if (settled) return;
settled = true;
current.held.delete(complete);
this.removeListener("end", closed).removeListener("close", closed);
callback(error);
};
const complete = () => settle();
const closed = () => settle(Object.assign(new Error("write failed: the socket closed before it completed"), { code: "ERR_SOCKET_CLOSED" }));
this.prependOnceListener("end", closed).prependOnceListener("close", closed);
return originalWrite.call(this, chunk, encoding, (error?: Error | null) => { if (error) settle(error); });
return base.call(this, chunk, encoding, (error?: Error | null) => {
if (settled) return; // Already failed by the socket ending or closing; nothing to hold.
if (error) settle(error);
else if (current.releasing) complete();
else current.held.add(complete);
});
};
}

/** Let this hold's held and later successful completions through, as a drained buffer would. Idempotent. */
export function releaseHeldSocketWrites(): void {
if (!cycle) return;
cycle.releasing = true;
for (const complete of [...cycle.held]) complete();
}

/** Release what the current hold still holds and put the real write back. */
export function restoreSocketWrites(): void {
releaseHeldSocketWrites();
cycle = null;
Socket.prototype._write = originalWrite;
}

/** Test seam for the helper's own tests: how many completions the current hold is keeping. */
export function heldSocketWriteCountForTests(): number {
return cycle?.held.size ?? 0;
}
Loading