fix(mesh): RPC frames wait for the send buffer too (CARD-26, #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

CARD-26 made the WebSocket route pump await `drained()` before each pull,
but mesh RPC traffic sends outside that pump, so it never waited:

- teapot: `handleRpc` runs concurrently per rpc-req, so a teacup that
  keeps sending requests and stops reading grows the teapot's buffer by
  one response each.
- link: `sendRpc` sent each rpc-req at once, whatever the buffer held.

Both now wait for `drained()` before sending. The teapot drops a response
whose socket closed while waiting. The link starts its timeout before
waiting, so a teapot that stops reading still answers 504, and a call
that settles while waiting (timeout or close) is never sent late.

Found in the pre-freeze integrated review.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-24 13:57:35 -05:00
1 parent cdef95ffcb
commit 77d4f32eff
4 files changed
+88 -4

No files matched your search

+5 -1
View File
@@ -119,7 +119,11 @@ function sendRpc(
}, timeoutMs);
pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer });
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
// 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 }));
});
});
}
+11 -2
View File
@@ -170,6 +170,15 @@ function resolveRpc(
return deps.resolveRoute(name, ctx);
}
/**
* 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));
}
/** Serve one authenticated rpc-req: resolve it and frame the ok/error response back to the peer. */
async function handleRpc(
socket: WsSocket,
@@ -196,12 +205,12 @@ async function handleRpc(
throw error;
}
socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
await reply(socket, { type: 'rpc-res', id, ok: true, result });
} catch (err) {
const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500);
deps.bus?.emit('mesh:rpc:error', { name, error: err });
socket.send(encode({ type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }));
await reply(socket, { type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } });
}
}