fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41)
The outbound pump pulled a @Ws handler's iterator as fast as it yielded, whatever the peer read. With a slow client, 10,000 frames of 64 KiB were all pulled at once and sat in the send buffer: 640 MiB. WsSocket gains one optional member, drained(): it resolves once the socket's send buffer is at or below the adapter's high-water mark (WS_HIGH_WATER_MARK, 1 MiB, internal), or the socket has closed. The pump awaits it before each pull, so the buffer peaks at the mark plus one frame. A close ends the wait and the abort path runs the iterator's return(), as before. A socket without drained() is never waited on. Per runtime: - Node: ws.bufferedAmount, released by each send's write callback; - Bun: getBufferedAmount(), released by the server's drain callback; - Deno: polls bufferedAmount every 10 ms, only while over the mark; - workerd reports no buffered amount, so the edge never waits. The Deno poll also waits while the socket is CONNECTING. Deno hands the socket over before it opens, and a handler that yielded at once had its first value pulled into a socket that was not open yet. The pump then gave up, so the client saw no frame and a 1005 close. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
10 files changed
+616
-8
No files matched your search
+35
-2
@@ -1,6 +1,6 @@
|
||||
import { channel, type Channel } from '../channel';
|
||||
import type { App } from '../app/types';
|
||||
import type { WsRequest, WsSocket } from './ws-core';
|
||||
import { WS_HIGH_WATER_MARK, type WsRequest, type WsSocket } from './ws-core';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
/**
|
||||
@@ -40,6 +40,8 @@ export function toWsRequest(request: Request, ip: string): WsRequest {
|
||||
/** The subset of a host WebSocket that {@link eventSocket} drives (Deno's WebSocket and workerd's both satisfy it). */
|
||||
export interface EventfulSocket {
|
||||
readonly readyState: number;
|
||||
/** Bytes queued by `send` and not yet written. Deno reports it; a host without it is never waited on. */
|
||||
readonly bufferedAmount?: number;
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
addEventListener(
|
||||
@@ -90,7 +92,7 @@ export function eventSocket(host: EventfulSocket): WsSocket {
|
||||
* callers never have to guard an already-closed socket.
|
||||
*/
|
||||
export function neutralSocket(
|
||||
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
|
||||
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close' | 'bufferedAmount'> & { terminate?(): void },
|
||||
inbound: Channel<unknown>,
|
||||
ac: AbortController,
|
||||
): WsSocket {
|
||||
@@ -103,6 +105,7 @@ export function neutralSocket(
|
||||
send: (data) => {
|
||||
host.send(data);
|
||||
},
|
||||
drained: () => pollDrained(host, ac.signal),
|
||||
close: (code, reason) => {
|
||||
try {
|
||||
host.close(code, reason);
|
||||
@@ -120,6 +123,36 @@ export function neutralSocket(
|
||||
};
|
||||
}
|
||||
|
||||
/** How often {@link pollDrained} rereads `bufferedAmount` while a socket is backed up. */
|
||||
const DRAIN_POLL_MS = 10;
|
||||
|
||||
/**
|
||||
* {@link WsSocket.drained} for a host that reports `bufferedAmount` but fires no drain event —
|
||||
* the Web `WebSocket` API has none. Polls only while the socket is over the mark, so a socket that
|
||||
* keeps up never starts a timer; the close (`signal`) ends the wait at once.
|
||||
*
|
||||
* A socket still CONNECTING is not writable either, and waits too. Deno hands its socket over in
|
||||
* that state, and a route that yielded at once had its first frame pulled, found the socket not
|
||||
* open, and the pump gave up on the connection.
|
||||
*/
|
||||
async function pollDrained(host: Pick<EventfulSocket, 'readyState' | 'bufferedAmount'>, signal: AbortSignal) {
|
||||
const backedUp = () =>
|
||||
host.readyState === CONNECTING || (host.readyState === OPEN && (host.bufferedAmount ?? 0) > WS_HIGH_WATER_MARK);
|
||||
|
||||
while (!signal.aborted && backedUp()) {
|
||||
await new Promise<void>((resolve) => {
|
||||
const done = () => {
|
||||
clearTimeout(timer);
|
||||
signal.removeEventListener('abort', done);
|
||||
resolve();
|
||||
};
|
||||
|
||||
const timer = setTimeout(done, DRAIN_POLL_MS);
|
||||
signal.addEventListener('abort', done, { once: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Constructs a host WebSocket *client*. Both the platform global and the `ws` package satisfy it. */
|
||||
export type SocketCtor = new (url: string) => EventfulSocket;
|
||||
|
||||
|
||||
+26
-1
@@ -21,8 +21,24 @@ export interface WsSocket {
|
||||
send(data: string): void;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate(): void;
|
||||
/**
|
||||
* Resolves once the socket's send buffer is at or below the adapter's high-water mark, or the
|
||||
* socket has closed — at once when it already is (#41). The outbound pump awaits it before
|
||||
* pulling the next value, so a fast producer cannot grow the buffer without limit.
|
||||
*
|
||||
* Optional: a socket without it is never waited on, which is how every socket behaved before.
|
||||
* The mark is the adapter's; {@link WS_HIGH_WATER_MARK} is what the built-in adapters use.
|
||||
*/
|
||||
drained?(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send-buffer level, in bytes, above which the built-in adapters report a socket as backed up
|
||||
* (#41). Internal, not an option: it bounds what one slow peer can make the process hold, and
|
||||
* a frame is sent whole, so the buffer peaks at this plus one frame.
|
||||
*/
|
||||
export const WS_HIGH_WATER_MARK = 1_048_576;
|
||||
|
||||
/** 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). */
|
||||
@@ -345,9 +361,18 @@ function trackConnection(socket: WsSocket, streams?: Set<() => void>): { closer:
|
||||
return { closer };
|
||||
}
|
||||
|
||||
/** Drives the outbound async iterator, sending each yielded value until done or the socket closes. */
|
||||
/**
|
||||
* Drives the outbound async iterator, sending each yielded value until done or the socket closes.
|
||||
* Waits for {@link WsSocket.drained} before each pull (#41): a value pulled while the peer is
|
||||
* backed up has nowhere to go but the send buffer, so it is not pulled until there is room.
|
||||
*/
|
||||
async function pumpOutbound(socket: WsSocket, iterator: AsyncIterator<unknown>): Promise<void> {
|
||||
while (true) {
|
||||
if (socket.drained) await socket.drained();
|
||||
// Closed while waiting: stop before pulling a value nobody can receive. The abort listener in
|
||||
// `runWsConnection` has already called the iterator's `return()`. `abort`, not `isOpen`: Deno
|
||||
// hands a socket over still CONNECTING, which is not open yet and not closed either.
|
||||
if (socket.abort.aborted) break;
|
||||
const { value, done } = await iterator.next();
|
||||
if (done) break;
|
||||
if (!socket.isOpen) break;
|
||||
|
||||
+14
-1
@@ -8,6 +8,7 @@ import {
|
||||
boundInbound,
|
||||
controlBounds,
|
||||
wsMessageBytes,
|
||||
WS_HIGH_WATER_MARK,
|
||||
type WsSocket,
|
||||
type WsRequest,
|
||||
} from './ws-core';
|
||||
@@ -95,10 +96,21 @@ function nodeWsRequest(req: http.IncomingMessage): WsRequest {
|
||||
function nodeSocket(ws: any): WsSocket {
|
||||
const inbound = channel<unknown>();
|
||||
const ac = new AbortController();
|
||||
// `drained` callers waiting for the send buffer to fall to the mark (#41). Released by a send
|
||||
// callback, which `ws` runs once that frame is written to the TCP socket, or by the close.
|
||||
const waiters: Array<() => void> = [];
|
||||
const release = () => waiters.splice(0).forEach((resolve) => resolve());
|
||||
const backedUp = () => ws.readyState === 1 && ws.bufferedAmount > WS_HIGH_WATER_MARK;
|
||||
|
||||
const written = () => {
|
||||
if (!backedUp()) release();
|
||||
};
|
||||
|
||||
ws.on('message', (data: Buffer) => inbound.push(data.toString()));
|
||||
ws.on('close', () => {
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
release();
|
||||
});
|
||||
ws.on('error', (err: unknown) => inbound.fail(err));
|
||||
return {
|
||||
@@ -107,7 +119,8 @@ function nodeSocket(ws: any): WsSocket {
|
||||
get isOpen() {
|
||||
return ws.readyState === 1; // 1 = OPEN
|
||||
},
|
||||
send: (data) => ws.send(data),
|
||||
send: (data) => ws.send(data, written),
|
||||
drained: () => (backedUp() ? new Promise<void>((resolve) => waiters.push(resolve)) : Promise.resolve()),
|
||||
close: (code, reason) => {
|
||||
try {
|
||||
ws.close(code, reason);
|
||||
|
||||
Reference in new issue
Block a user