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>
210 lines
8.0 KiB
TypeScript
210 lines
8.0 KiB
TypeScript
import { channel, type Channel } from '../channel';
|
|
import type { App } from '../app/types';
|
|
import { WS_HIGH_WATER_MARK, type WsRequest, type WsSocket } from './ws-core';
|
|
import { nodeRequire } from '../node-require';
|
|
|
|
/**
|
|
* Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket
|
|
* to the neutral {@link WsSocket} the core talks to. Separate from `ws-core` on purpose:
|
|
* that module *runs* a connection, this one *builds* one from a host runtime's socket.
|
|
*/
|
|
|
|
const decoder = new TextDecoder();
|
|
const CONNECTING = 0; // WebSocket.CONNECTING
|
|
const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient
|
|
|
|
/** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */
|
|
export function decodeMessage(data: string | ArrayBuffer | Uint8Array): string {
|
|
return typeof data === 'string' ? data : decoder.decode(data);
|
|
}
|
|
|
|
/**
|
|
* Builds a neutral {@link WsRequest} from a Web-standard `Request`. Every adapter derives
|
|
* url/headers/protocol identically; only the client IP is runtime-specific, so it's passed in.
|
|
*/
|
|
export function toWsRequest(request: Request, ip: string): WsRequest {
|
|
const url = new URL(request.url);
|
|
const headers: Record<string, string> = {};
|
|
request.headers.forEach((value, key) => {
|
|
headers[key] = value;
|
|
});
|
|
|
|
return {
|
|
url: url.pathname + url.search,
|
|
headers,
|
|
protocol: url.protocol === 'https:' ? 'https' : 'http',
|
|
ip,
|
|
};
|
|
}
|
|
|
|
/** 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(
|
|
type: 'open' | 'message' | 'close' | 'error',
|
|
listener: (event: { data?: string | ArrayBuffer; error?: unknown }) => void,
|
|
): void;
|
|
}
|
|
|
|
/**
|
|
* Wraps an `addEventListener`-style host socket (Deno, workerd) as a neutral {@link WsSocket}:
|
|
* creates the inbound channel and abort controller and wires message/close/error into them.
|
|
* Bun does not use this — its socket events are delivered to a server-level handler rather
|
|
* than the socket, so it builds its own {@link WsSocket} over state stashed on `ws.data`.
|
|
*/
|
|
export function eventSocket(host: EventfulSocket): WsSocket {
|
|
const inbound = channel<unknown>();
|
|
const ac = new AbortController();
|
|
|
|
host.addEventListener('message', (event) => {
|
|
inbound.push(decodeMessage(event.data as string | ArrayBuffer));
|
|
});
|
|
host.addEventListener('close', () => {
|
|
inbound.close();
|
|
ac.abort();
|
|
});
|
|
host.addEventListener('error', () => {
|
|
inbound.fail(new Error('websocket error'));
|
|
ac.abort();
|
|
});
|
|
|
|
const socket = neutralSocket(host, inbound, ac);
|
|
const closeNow = socket.close;
|
|
|
|
// Deno hands the socket over still CONNECTING: its 101 has not gone out yet, and a close in
|
|
// that state is a no-op, so a route that refuses straight away (1008) left the peer hanging.
|
|
// Deferring to 'open' is what lets that close reach the client at all.
|
|
return Object.assign(socket, {
|
|
close: (code?: number, reason?: string) => {
|
|
if (host.readyState === CONNECTING) host.addEventListener('open', () => closeNow(code, reason));
|
|
else closeNow(code, reason);
|
|
},
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Wraps a host socket's send/close/readyState as a neutral {@link WsSocket} over an
|
|
* already-wired channel and abort controller. `close`/`terminate` swallow throws so
|
|
* callers never have to guard an already-closed socket.
|
|
*/
|
|
export function neutralSocket(
|
|
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close' | 'bufferedAmount'> & { terminate?(): void },
|
|
inbound: Channel<unknown>,
|
|
ac: AbortController,
|
|
): WsSocket {
|
|
return {
|
|
inbound,
|
|
abort: ac.signal,
|
|
get isOpen() {
|
|
return host.readyState === OPEN;
|
|
},
|
|
send: (data) => {
|
|
host.send(data);
|
|
},
|
|
drained: () => pollDrained(host, ac.signal),
|
|
close: (code, reason) => {
|
|
try {
|
|
host.close(code, reason);
|
|
} catch {
|
|
/* already closed */
|
|
}
|
|
},
|
|
terminate: () => {
|
|
try {
|
|
(host.terminate ?? host.close).call(host);
|
|
} catch {
|
|
/* already closed */
|
|
}
|
|
},
|
|
};
|
|
}
|
|
|
|
/** 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;
|
|
|
|
/**
|
|
* The WebSocket client implementation: the platform global where it exists, else the `ws`
|
|
* optional peer. Every supported runtime has the global — Deno, Bun, and Node from 22, the
|
|
* declared floor — so the fallback is reached only when Node runs with the global switched off
|
|
* (`--no-experimental-websocket`). `ws` is installed anyway for the server side.
|
|
*
|
|
* Both expose the same `addEventListener` API and deliver text frames as `event.data` strings,
|
|
* so one bridge covers both. That is verified rather than assumed: `ws` implements the
|
|
* browser-compatible event API alongside its EventEmitter one.
|
|
*/
|
|
export function loadWebSocketCtor(): SocketCtor {
|
|
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
|
|
|
|
if (platform) return platform;
|
|
|
|
return nodeRequire<SocketCtor>('ws');
|
|
}
|
|
|
|
/**
|
|
* Opens a client connection and wraps it as a neutral {@link WsSocket}. `opened` resolves once
|
|
* the socket is live (the caller's cue to send its first frame) and rejects if it never opens.
|
|
*
|
|
* `Ctor` is injectable so both implementations can be exercised on one runtime — otherwise CI
|
|
* on a single Node version would silently cover only one of the two paths.
|
|
*/
|
|
export function connectSocket(
|
|
url: string,
|
|
Ctor: SocketCtor = loadWebSocketCtor(),
|
|
): { socket: WsSocket; opened: Promise<void> } {
|
|
const host = new Ctor(url);
|
|
// registered before eventSocket's own error listener, so a connect failure rejects `opened`
|
|
// with the host's real error rather than eventSocket's generic one
|
|
const opened = new Promise<void>((resolve, reject) => {
|
|
host.addEventListener('open', () => resolve());
|
|
host.addEventListener('error', (event) => reject(event?.error ?? new Error(`websocket error: ${url}`)));
|
|
});
|
|
|
|
return { socket: eventSocket(host), opened };
|
|
}
|
|
|
|
/**
|
|
* Runs the ws lifecycle, closing with 1011 if it rejects. `app.upgrade` can reject *before*
|
|
* `runWsConnection`'s own try/catch (mesh-before-listen, provider boot failure); unguarded,
|
|
* that surfaces as an uncaught rejection and is fatal on Bun/Deno. Returns the promise so
|
|
* edge can hand it to `ctx.waitUntil`.
|
|
*/
|
|
export function upgradeSafely(app: App, request: WsRequest, socket: WsSocket): Promise<void> {
|
|
return app.upgrade(request, socket).catch(() => {
|
|
socket.close(1011, 'internal error'); // neutral close already swallows throws
|
|
});
|
|
}
|