From 1ae4c6f8657ddfef1cac0dc35d1408c810dffd18 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Sat, 24 Oct 2026 14:26:49 -0500 Subject: [PATCH] fix(mesh): queue RPC sends per socket so one drain releases one frame (#41) #152 made each mesh RPC send wait for `drained()`, but each one waited on its own. A drain on a backed-up socket releases every waiter at once (`nodeSocket` keeps them in one list), so they all sent and the buffer overshot the 1 MiB mark by one frame per concurrent RPC: bounded, but not what #152 claims. Found in the second pre-freeze review. `sendWhenDrained` (ws-core, internal) chains sends per socket, and each one waits for `drained()` when its turn comes. The buffer then peaks at the mark plus one frame, however many RPCs wait, and frames go out in call order. The teapot's `reply` and the link's `sendRpc` both use it. The frame is built at send time, so a call that timed out while queued sends nothing, and nothing is sent after the close. Tests: a burst of five 100-byte frames behind a backed-up socket sends one frame per drain, in order, with the buffer at most one frame. It fails when each sender waits on its own. Also: a withdrawn frame is skipped, and a frame queued at close is dropped. Signed-off-by: Diego Resendez --- src/http/ws-core.ts | 27 ++++++++++++++++++ src/mesh/link.ts | 8 +++--- src/mesh/teapot.ts | 7 ++--- test/ws-core.test.ts | 67 +++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 100 insertions(+), 9 deletions(-) diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts index e304e0e..49c8498 100644 --- a/src/http/ws-core.ts +++ b/src/http/ws-core.ts @@ -39,6 +39,33 @@ export interface WsSocket { */ export const WS_HIGH_WATER_MARK = 1_048_576; +/** The tail of each socket's {@link sendWhenDrained} queue. */ +const sendQueues = new WeakMap>(); + +/** + * Sends on `socket` in call order, each frame only once {@link WsSocket.drained} lets it (#41). + * For senders outside the outbound pump, such as concurrent mesh RPCs. Waiting one at a time is + * the point: callers that each waited on their own would all be released by the same drain and + * all send, putting one frame per caller over the mark. Queued, the buffer peaks at the mark plus + * one frame, however many callers wait. + * + * `frame` runs at send time, so a caller that settled while queued (a timeout) returns + * `undefined` and sends nothing. Nothing is sent once the socket has closed. + */ +export function sendWhenDrained(socket: WsSocket, frame: () => string | undefined): Promise { + const sent = (sendQueues.get(socket) ?? Promise.resolve()).then(async () => { + if (socket.drained) await socket.drained(); + if (socket.abort.aborted) return; + const data = frame(); + if (data !== undefined) socket.send(data); + }); + sendQueues.set( + socket, + sent.catch(() => {}), + ); + return sent; +} + /** Default for `limits.maxWsMessageBytes`: 1 MiB. */ export const DEFAULT_MAX_WS_MESSAGE_BYTES = 1_048_576; /** Default for `limits.maxWsQueue`, in undelivered inbound messages per connection (D1). */ diff --git a/src/mesh/link.ts b/src/mesh/link.ts index 1e0e66b..7375c62 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -2,7 +2,7 @@ import type { Bus } from '../bus'; import type { Logger } from '../logger'; import { HttpError } from '../signals'; import { connectSocket, type SocketCtor } from '../http/ws-adapter'; -import type { WsSocket } from '../http/ws-core'; +import { sendWhenDrained, type WsSocket } from '../http/ws-core'; import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol'; /** Client handle to a remote mesh server: its manifest, an RPC caller, and a close(). */ @@ -121,9 +121,9 @@ function sendRpc( pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer }); // Not before the socket has room (#41); the timeout already runs, so a teapot that stops // reading still answers 504. Settled while waiting (timeout, close): nothing left to send. - void (socket.drained?.() ?? Promise.resolve()).then(() => { - if (pending.has(id) && !socket.abort.aborted) socket.send(encode({ type: 'rpc-req', id, kind, name, ctx })); - }); + void sendWhenDrained(socket, () => + pending.has(id) ? encode({ type: 'rpc-req', id, kind, name, ctx }) : undefined, + ); }); } diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 17a9166..9715bc7 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -3,7 +3,7 @@ // under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec). import crypto from 'node:crypto'; import type { Bus } from '../bus'; -import { HELLO_FRAME_BYTES, widenInbound, type WsSocket } from '../http/ws-core'; +import { HELLO_FRAME_BYTES, sendWhenDrained, widenInbound, type WsSocket } from '../http/ws-core'; import type { ResponseShape } from '../pipeline'; import { isHttpError } from '../signals'; import { @@ -174,9 +174,8 @@ function resolveRpc( * Sends one frame once the socket has room (#41): RPCs are served concurrently, so without the wait * a peer that stops reading grows the send buffer by one response per request it keeps sending. */ -async function reply(socket: WsSocket, frame: Frame): Promise { - if (socket.drained) await socket.drained(); - if (!socket.abort.aborted) socket.send(encode(frame)); +function reply(socket: WsSocket, frame: Frame): Promise { + return sendWhenDrained(socket, () => encode(frame)); } /** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */ diff --git a/test/ws-core.test.ts b/test/ws-core.test.ts index 9e6ddaf..657a7f3 100644 --- a/test/ws-core.test.ts +++ b/test/ws-core.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { runWsConnection, matchWsRoute, type WsSocket, type WsRequest } from '../src/http/ws-core'; +import { runWsConnection, matchWsRoute, sendWhenDrained, type WsSocket, type WsRequest } from '../src/http/ws-core'; import { channel } from '../src/channel'; import { HttpError } from '../src/signals'; import { Bus } from '../src/bus'; @@ -255,3 +255,68 @@ describe('runWsConnection outbound backpressure (#41)', () => { expect(waits).toBe(51); // once before each pull, the last one being the pull that ends it }); }); + +describe('sendWhenDrained (#41)', () => { + /** Like `nodeSocket`: every `drained()` caller waits on one list, and a drain releases them all. */ + function drainingSocket(mark: number) { + const fake = fakeSocket(); + let buffered = 0; + let waiters: Array<() => void> = []; + const socket: WsSocket = Object.assign(Object.create(fake.socket), { + send: (d: string) => { + fake.sent.push(d); + buffered += d.length; + }, + drained: () => + buffered <= mark || fake.ac.signal.aborted + ? Promise.resolve() + : new Promise((resolve) => waiters.push(resolve)), + }); + const flush = () => { + buffered = 0; + const woken = waiters; + waiters = []; + woken.forEach((resolve) => resolve()); + }; + const close = () => { + fake.ac.abort(); + flush(); + }; + return { ...fake, socket, flush, close, buffered: () => buffered }; + } + + const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + + it('a burst of callers sends one frame per drain, in call order, never more than one over the mark', async () => { + const { socket, sent, flush, buffered } = drainingSocket(10); + socket.send('x'.repeat(11)); // backed up before anyone queues + const frames = ['a', 'b', 'c', 'd', 'e'].map((c) => c.repeat(100)); + const all = Promise.all(frames.map((f) => sendWhenDrained(socket, () => f))); + await tick(); + expect(sent).toHaveLength(1); + for (let i = 0; i < frames.length; i++) { + flush(); + await tick(); + expect(sent).toHaveLength(i + 2); // one more, not the whole burst + expect(buffered()).toBe(100); // the mark plus one frame at most + } + await all; + expect(sent.slice(1)).toEqual(frames); + }); + + it('skips a frame its caller withdrew while queued, and sends nothing after the close', async () => { + const { socket, sent, flush, close } = drainingSocket(10); + socket.send('x'.repeat(11)); + const withdrawn = sendWhenDrained(socket, () => undefined); + flush(); + await withdrawn; + expect(sent).toHaveLength(1); + + socket.send('y'.repeat(11)); // backed up again + const late = sendWhenDrained(socket, () => 'late'); + await tick(); + close(); // releases the wait, as a real close does + await late; + expect(sent).toHaveLength(2); + }); +});