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
+33
-4
@@ -1,7 +1,13 @@
|
||||
import { channel } from './channel';
|
||||
import type { Channel } from './channel';
|
||||
import type { App } from './app/types';
|
||||
import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core';
|
||||
import {
|
||||
WS_MAX_MESSAGE_BYTES,
|
||||
DEFAULT_MAX_WS_MESSAGE_BYTES,
|
||||
WS_HIGH_WATER_MARK,
|
||||
type WsSocket,
|
||||
type WsRequest,
|
||||
} from './http/ws-core';
|
||||
import { beginDrain } from './http/health';
|
||||
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
||||
import { closeWithDeadline } from './http/shutdown';
|
||||
@@ -15,12 +21,15 @@ interface BunServerWebSocket {
|
||||
send(data: string): number;
|
||||
close(code?: number, reason?: string): void;
|
||||
terminate?(): void;
|
||||
/** Bytes queued and not yet written; Bun's counterpart to `WebSocket.bufferedAmount`. */
|
||||
getBufferedAmount?(): number;
|
||||
}
|
||||
interface BunWebSocketHandler {
|
||||
maxPayloadLength?: number;
|
||||
open?(ws: BunServerWebSocket): void;
|
||||
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
||||
close?(ws: BunServerWebSocket, code: number, reason: string): void;
|
||||
drain?(ws: BunServerWebSocket): void;
|
||||
error?(ws: BunServerWebSocket, error?: unknown): void;
|
||||
}
|
||||
interface BunServer {
|
||||
@@ -58,6 +67,13 @@ interface BunConnData {
|
||||
wsReq: WsRequest;
|
||||
inbound: Channel<unknown>;
|
||||
ac: AbortController;
|
||||
/** `drained` callers waiting for Bun's `drain` callback or the close (#41). */
|
||||
drainWaiters: Array<() => void>;
|
||||
}
|
||||
|
||||
/** Wakes every `drained` caller; each rechecks the buffer and waits again if it is still over. */
|
||||
function releaseDrain(ws: BunServerWebSocket): void {
|
||||
(ws.data as BunConnData).drainWaiters.splice(0).forEach((resolve) => resolve());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -66,9 +82,17 @@ interface BunConnData {
|
||||
* created during the upgrade and stashed on ws.data — there is nothing here to wire up.
|
||||
*/
|
||||
function bunSocket(ws: BunServerWebSocket): WsSocket {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
const { inbound, ac, drainWaiters } = ws.data as BunConnData;
|
||||
|
||||
return neutralSocket(ws, inbound, ac);
|
||||
// Bun has no `bufferedAmount` property, so the generic poll would never wait. It has better: a
|
||||
// `getBufferedAmount()` to read and a server-level `drain` callback to wait on, no timer needed.
|
||||
const drained = async (): Promise<void> => {
|
||||
while (!ac.signal.aborted && (ws.getBufferedAmount?.() ?? 0) > WS_HIGH_WATER_MARK) {
|
||||
await new Promise<void>((resolve) => drainWaiters.push(resolve));
|
||||
}
|
||||
};
|
||||
|
||||
return Object.assign(neutralSocket(ws, inbound, ac), { drained });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,7 +122,7 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
||||
const inbound = channel();
|
||||
const ac = new AbortController();
|
||||
const wsReq = toWsRequest(request, server.requestIP(request)?.address ?? '');
|
||||
const data: BunConnData = { wsReq, inbound, ac };
|
||||
const data: BunConnData = { wsReq, inbound, ac, drainWaiters: [] };
|
||||
if (server.upgrade(request, { data })) return undefined;
|
||||
return new Response('WebSocket upgrade failed', { status: 400 });
|
||||
}
|
||||
@@ -126,15 +150,20 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
||||
|
||||
inbound.push(decodeMessage(message));
|
||||
},
|
||||
drain(ws) {
|
||||
releaseDrain(ws);
|
||||
},
|
||||
close(ws) {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
inbound.close();
|
||||
ac.abort();
|
||||
releaseDrain(ws);
|
||||
},
|
||||
error(ws) {
|
||||
const { inbound, ac } = ws.data as BunConnData;
|
||||
inbound.fail(new Error('websocket error'));
|
||||
ac.abort();
|
||||
releaseDrain(ws);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
+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