fix(mesh): queue RPC sends per socket so one drain releases one frame (#41)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / runtimes (deno) (pull_request) Successful in 33s

#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 <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-24 14:26:49 -05:00
1 parent 8333a46497
commit 1ae4c6f865
4 files changed
+100 -9

No files matched your search

+27
View File
@@ -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<WsSocket, Promise<void>>();
/**
* 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<void> {
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). */
+4 -4
View File
@@ -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,
);
});
}
+3 -4
View File
@@ -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<void> {
if (socket.drained) await socket.drained();
if (!socket.abort.aborted) socket.send(encode(frame));
function reply(socket: WsSocket, frame: Frame): Promise<void> {
return sendWhenDrained(socket, () => encode(frame));
}
/** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */