fix(mesh): queue RPC sends per socket so one drain releases one frame (#41) #156

Merged
chrnx merged 1 commits from fix/mesh-rpc-send-order into develop 2026-10-24 19:32:23 +00:00
4 changed files with 100 additions and 9 deletions

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. */
+66 -1
View File
@@ -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<void>((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);
});
});