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 <diego.resendez@zero-oneit.com>
This commit is contained in:
4 files changed
+100
-9
No files matched your search
@@ -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). */
|
||||
|
||||
Reference in new issue
Block a user