feat(ws)!: bound inbound WebSocket message size and queue
Inbound WebSocket traffic was unbounded per connection: Node used ws's 100 MiB default payload, the other runtimes had no cap of their own, and the queue behind `inbound` was an unbounded channel on every runtime, so one client could exhaust memory with large messages or a slow consumer. Add `limits.maxWsMessageBytes` (default 1 MiB, close 1009) and `limits.maxWsQueue` (default 16 unread messages, close 1013), as recorded in D1. Both are server-wide and validated by createApp, which throws a TypeError for anything but a positive integer. Enforcement is shared in `boundInbound`, which subscribes immediately and replaces the subscribe-before-boot trick in app.upgrade. Node and Bun also get the native pre-buffer cap; Bun drops the connection without a close frame, so its peer sees 1006, which is documented and tested. Deno and workerd expose no such option and check the size after receipt. BREAKING CHANGE: messages over 1 MiB now close the connection with 1009, and a connection with 16 unread inbound messages is closed with 1013 on the next one, including a handler that never reads `inbound`. Closes #107 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
13 files changed
+762
-34
No files matched your search
+25
-11
@@ -8,7 +8,17 @@ import { runPipeline, runSteps, PipelineStep } from '../pipeline';
|
||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
||||
import type { HttpOptions } from '../http';
|
||||
import { buildFetch } from '../http/web';
|
||||
import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocket } from '../http/ws-core';
|
||||
import {
|
||||
boundInbound,
|
||||
validateWsLimits,
|
||||
WS_MAX_MESSAGE_BYTES,
|
||||
wsMessageBytes,
|
||||
matchWsRoute,
|
||||
runWsConnection,
|
||||
trackUntil,
|
||||
type WsRequest,
|
||||
type WsSocket,
|
||||
} from '../http/ws-core';
|
||||
import { isAsyncIterable } from '../channel';
|
||||
import { JsonTransformer, type ErrorRenderer } from '../transformers';
|
||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
|
||||
@@ -195,6 +205,8 @@ export function createApp(opts: {
|
||||
);
|
||||
}
|
||||
|
||||
validateWsLimits(opts.limits);
|
||||
|
||||
const bus = new Bus();
|
||||
const logger = opts.logger ?? createDefaultLogger();
|
||||
if (opts.logRequests) logRequests(bus, logger);
|
||||
@@ -318,7 +330,7 @@ export function createApp(opts: {
|
||||
devRoutes,
|
||||
() => remoteRoutes,
|
||||
);
|
||||
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl);
|
||||
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits);
|
||||
|
||||
const listen = async (port: number): Promise<http.Server> => {
|
||||
const deps = pipelineDeps;
|
||||
@@ -387,7 +399,7 @@ export function createApp(opts: {
|
||||
return wrapped;
|
||||
};
|
||||
|
||||
return {
|
||||
const app: App = {
|
||||
listen,
|
||||
close,
|
||||
handleSignals,
|
||||
@@ -405,6 +417,10 @@ export function createApp(opts: {
|
||||
bus,
|
||||
logger,
|
||||
};
|
||||
|
||||
return Object.assign(app, {
|
||||
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
|
||||
});
|
||||
}
|
||||
|
||||
/** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */
|
||||
@@ -1275,18 +1291,16 @@ function buildAppUpgrade(
|
||||
streams: Set<() => void>,
|
||||
ensureBooted: () => Promise<void>,
|
||||
getMeshControl: () => MeshControl | undefined,
|
||||
limits?: RequestLimits,
|
||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||
let wsRoutes: WsRouteDef[] | undefined;
|
||||
|
||||
return async (request: WsRequest, socket: WsSocket): Promise<void> => {
|
||||
// Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no
|
||||
// subscriber is dropped, so anything the peer sends while providers are still booting would be
|
||||
// lost. For the mesh control channel that is the `hello` itself — the handshake would hang
|
||||
// until timeout against a teapot whose providers happened to boot slowly.
|
||||
const frames = socket.inbound[Symbol.asyncIterator]();
|
||||
const ready: WsSocket = Object.create(socket, {
|
||||
inbound: { value: { [Symbol.asyncIterator]: () => frames } },
|
||||
}) as WsSocket;
|
||||
// Bound and subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed
|
||||
// with no subscriber is dropped, so anything the peer sends while providers are still booting
|
||||
// would be lost. For the mesh control channel that is the `hello` itself — the handshake would
|
||||
// hang until timeout against a teapot whose providers happened to boot slowly.
|
||||
const ready = boundInbound(socket, limits);
|
||||
|
||||
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
||||
|
||||
|
||||
+8
-1
@@ -1,7 +1,7 @@
|
||||
import { channel } from './channel';
|
||||
import type { Channel } from './channel';
|
||||
import type { App } from './app/types';
|
||||
import type { WsSocket, WsRequest } from './http/ws-core';
|
||||
import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core';
|
||||
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
||||
import { closeWithDeadline } from './http/shutdown';
|
||||
|
||||
@@ -15,6 +15,7 @@ interface BunServerWebSocket {
|
||||
terminate?(): void;
|
||||
}
|
||||
interface BunWebSocketHandler {
|
||||
maxPayloadLength?: number;
|
||||
open?(ws: BunServerWebSocket): void;
|
||||
message(ws: BunServerWebSocket, message: string | Uint8Array): void;
|
||||
close?(ws: BunServerWebSocket, code: number, reason: string): void;
|
||||
@@ -103,6 +104,12 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
||||
return app.fetch(request);
|
||||
},
|
||||
websocket: {
|
||||
// The pre-buffer half of `limits.maxWsMessageBytes`: Bun refuses an oversized frame before
|
||||
// assembling it. It drops the connection without a close frame, so the peer sees 1006 rather
|
||||
// than 1009 — verified on Bun 1.3, and the price of not buffering the message at all.
|
||||
// `app.upgrade` checks the same bound again on the decoded text.
|
||||
maxPayloadLength:
|
||||
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
|
||||
open(ws) {
|
||||
const { wsReq } = ws.data as BunConnData;
|
||||
|
||||
|
||||
+1
-1
@@ -79,7 +79,7 @@ export function createHttpServer(
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
attachWs(server, wsRoutes, bus, meshControl, opts?.streams);
|
||||
attachWs(server, wsRoutes, bus, meshControl, opts?.streams, opts?.limits);
|
||||
return server;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,31 @@ export interface RequestLimits {
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
maxParts?: number; // default 1000
|
||||
/**
|
||||
* Largest inbound WebSocket message, in bytes (UTF-8 bytes for text), per connection. Default
|
||||
* `1_048_576` (1 MiB). A larger message closes the connection with `1009` (`message too large`);
|
||||
* a fragmented message counts as a whole. Must be a positive integer, or `createApp` throws.
|
||||
*
|
||||
* Node and Bun refuse an oversized frame before buffering it (`ws`'s `maxPayload`, Bun's
|
||||
* `maxPayloadLength`). Bun then drops the connection without a close frame, so on Bun the peer
|
||||
* sees `1006` instead of `1009`. Deno and the edge offer no such option: there the runtime
|
||||
* receives the whole message first, so its memory is bounded by the platform's own cap, and this
|
||||
* limit is checked after receipt — the connection still closes `1009`.
|
||||
*
|
||||
* Server-level only; there is no per-route override.
|
||||
*/
|
||||
maxWsMessageBytes?: number;
|
||||
/**
|
||||
* Inbound WebSocket messages a connection may hold that the handler has not read yet. Default
|
||||
* `16`. One more closes the connection with `1013` (`inbound queue full`) rather than dropping
|
||||
* anything, so a handler that never reads `inbound` is closed once its peer sends 17 messages.
|
||||
* Must be a positive integer, or `createApp` throws. Applies on every runtime.
|
||||
*
|
||||
* Worst-case buffered inbound memory is about `maxConnections × maxWsQueue × maxWsMessageBytes`:
|
||||
* ≈ 15.6 GiB at the defaults on Node. Deno and Bun have no connection cap, so cap connections at
|
||||
* the platform or proxy there. Server-level only; there is no per-route override.
|
||||
*/
|
||||
maxWsQueue?: number;
|
||||
}
|
||||
|
||||
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
|
||||
|
||||
+143
-1
@@ -2,7 +2,7 @@ import { isHttpError } from '../signals';
|
||||
import type { Bus } from '../bus';
|
||||
import { correlateRequest } from './core';
|
||||
import { matchPattern } from './router';
|
||||
import type { WsRouteDef } from './types';
|
||||
import type { WsRouteDef, RequestLimits } from './types';
|
||||
|
||||
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
|
||||
export interface WsRequest {
|
||||
@@ -22,6 +22,148 @@ export interface WsSocket {
|
||||
terminate(): void;
|
||||
}
|
||||
|
||||
/** 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). */
|
||||
export const DEFAULT_MAX_WS_QUEUE = 16;
|
||||
|
||||
/**
|
||||
* Where `createApp` leaves the resolved `maxWsMessageBytes` for `serveBun`, which needs it as
|
||||
* Bun's native `maxPayloadLength` and has no other path to the app's options. Internal, not part
|
||||
* of the public `App` type; `Symbol.for` because each tsup entry carries its own copy of this
|
||||
* module, and only the global registry resolves to one symbol across them.
|
||||
*/
|
||||
export const WS_MAX_MESSAGE_BYTES: unique symbol = Symbol.for('green-tea.ws-max-message-bytes');
|
||||
|
||||
/** The effective `limits.maxWsMessageBytes`. */
|
||||
export function wsMessageBytes(limits: Pick<RequestLimits, 'maxWsMessageBytes'> | undefined): number {
|
||||
return limits?.maxWsMessageBytes ?? DEFAULT_MAX_WS_MESSAGE_BYTES;
|
||||
}
|
||||
|
||||
/** Throws when a WebSocket limit is present but not a positive safe integer (#107). */
|
||||
export function validateWsLimits(limits: RequestLimits | undefined): void {
|
||||
for (const key of ['maxWsMessageBytes', 'maxWsQueue'] as const) {
|
||||
const value: unknown = limits?.[key];
|
||||
if (value === undefined || (Number.isSafeInteger(value) && (value as number) > 0)) continue;
|
||||
const shown = typeof value === 'string' ? `'${value}'` : String(value);
|
||||
throw new TypeError(`limits.${key} must be a positive integer, got ${shown}`);
|
||||
}
|
||||
}
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
/** True when `msg`'s UTF-8 encoding is longer than `max` bytes. */
|
||||
function exceedsBytes(msg: unknown, max: number): boolean {
|
||||
if (typeof msg !== 'string') return false; // every adapter delivers strings; nothing else to measure
|
||||
// A UTF-16 unit encodes to 1–3 UTF-8 bytes, so both bounds below are exact. Only a string in
|
||||
// between pays for the encode — which is never one of the short messages that dominate.
|
||||
if (msg.length * 3 <= max) return false;
|
||||
if (msg.length > max) return true;
|
||||
return encoder.encode(msg).byteLength > max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounds a socket's inbound side (#107): a frame over `maxWsMessageBytes` closes `1009`, and a
|
||||
* frame that arrives while `maxWsQueue` frames are still undelivered closes `1013`. Nothing is
|
||||
* dropped silently — the peer learns which bound it hit from the close code.
|
||||
*
|
||||
* Subscribes to `socket.inbound` immediately. `channel` is fan-out, so a frame pushed with no
|
||||
* subscriber is lost; subscribing here, before any boot or step runs, is what keeps the first
|
||||
* frames — for the mesh control channel, the `hello` itself. The returned socket's `inbound` is a
|
||||
* single-consumer FIFO over those frames, and every other capability is the original socket's.
|
||||
*/
|
||||
export function boundInbound(
|
||||
socket: WsSocket,
|
||||
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
|
||||
): WsSocket {
|
||||
const fifo = new InboundFifo(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
|
||||
|
||||
void fifo.pump();
|
||||
|
||||
return Object.create(socket, {
|
||||
inbound: { value: { [Symbol.asyncIterator]: () => fifo } },
|
||||
}) as WsSocket;
|
||||
}
|
||||
|
||||
/** The single-consumer queue behind {@link boundInbound}; it is its own async iterator. */
|
||||
class InboundFifo implements AsyncIterator<unknown> {
|
||||
private readonly queue: unknown[] = [];
|
||||
private waiter: { resolve: (r: IteratorResult<unknown>) => void; reject: (e: unknown) => void } | null = null;
|
||||
private ended = false;
|
||||
private failure: { err: unknown } | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly socket: WsSocket,
|
||||
private readonly maxBytes: number,
|
||||
private readonly maxQueue: number,
|
||||
) {}
|
||||
|
||||
async pump(): Promise<void> {
|
||||
try {
|
||||
for await (const msg of this.socket.inbound) {
|
||||
if (this.ended || !this.accept(msg)) break;
|
||||
}
|
||||
|
||||
this.settle();
|
||||
} catch (err) {
|
||||
this.settle({ err });
|
||||
}
|
||||
}
|
||||
|
||||
next(): Promise<IteratorResult<unknown>> {
|
||||
if (this.queue.length) return Promise.resolve({ value: this.queue.shift(), done: false });
|
||||
if (this.failure) return Promise.reject(this.failure.err);
|
||||
if (this.ended) return Promise.resolve({ value: undefined, done: true });
|
||||
return new Promise((resolve, reject) => {
|
||||
this.waiter = { resolve, reject };
|
||||
});
|
||||
}
|
||||
|
||||
// A consumer that stops reading has said it wants no more; queueing for it would only close
|
||||
// the connection for a bound it no longer cares about.
|
||||
return(): Promise<IteratorResult<unknown>> {
|
||||
this.queue.length = 0;
|
||||
this.settle();
|
||||
return Promise.resolve({ value: undefined, done: true });
|
||||
}
|
||||
|
||||
/** Delivers or queues one frame; returns false once the frame has closed the socket. */
|
||||
private accept(msg: unknown): boolean {
|
||||
if (exceedsBytes(msg, this.maxBytes)) {
|
||||
this.socket.close(1009, 'message too large');
|
||||
return false;
|
||||
}
|
||||
|
||||
const waiter = this.waiter;
|
||||
|
||||
if (waiter) {
|
||||
this.waiter = null;
|
||||
waiter.resolve({ value: msg, done: false });
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.queue.length >= this.maxQueue) {
|
||||
this.socket.close(1013, 'inbound queue full');
|
||||
return false;
|
||||
}
|
||||
|
||||
this.queue.push(msg);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Ends the queue once, cleanly or with a failure; whatever is still queued is delivered first. */
|
||||
private settle(failure?: { err: unknown }): void {
|
||||
if (this.ended) return;
|
||||
this.ended = true;
|
||||
this.failure = failure ?? null;
|
||||
const waiter = this.waiter;
|
||||
this.waiter = null;
|
||||
if (!waiter) return;
|
||||
if (failure) waiter.reject(failure.err);
|
||||
else waiter.resolve({ value: undefined, done: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Finds the first ws route whose pattern matches `path`, capturing its params. */
|
||||
export function matchWsRoute(
|
||||
wsRoutes: WsRouteDef[],
|
||||
|
||||
+32
-17
@@ -1,8 +1,16 @@
|
||||
import type http from 'http';
|
||||
import { channel } from '../channel';
|
||||
import type { Bus } from '../bus';
|
||||
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
|
||||
import type { WsRouteDef, MeshControl } from './types';
|
||||
import {
|
||||
runWsConnection,
|
||||
matchWsRoute,
|
||||
trackUntil,
|
||||
boundInbound,
|
||||
wsMessageBytes,
|
||||
type WsSocket,
|
||||
type WsRequest,
|
||||
} from './ws-core';
|
||||
import type { WsRouteDef, MeshControl, RequestLimits } from './types';
|
||||
import { normalizeRequestPath } from './router';
|
||||
import { nodeRequire } from '../node-require';
|
||||
|
||||
@@ -32,6 +40,7 @@ function handleMeshUpgrade(
|
||||
socket: any,
|
||||
head: Buffer,
|
||||
streams?: Set<() => void>,
|
||||
limits?: RequestLimits,
|
||||
): boolean {
|
||||
if (path !== meshControl.path) return false;
|
||||
|
||||
@@ -46,7 +55,7 @@ function handleMeshUpgrade(
|
||||
// an untracked control channel leaves the teapot's server.close() waiting on it forever.
|
||||
// serveFrames swallows its own failures, so the floating promise cannot reject.
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
const neutral = nodeSocket(ws);
|
||||
const neutral = boundInbound(nodeSocket(ws), limits);
|
||||
|
||||
void trackUntil(neutral, meshControl.handle(neutral), streams);
|
||||
});
|
||||
@@ -98,10 +107,14 @@ export function attachWs(
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
streams?: Set<() => void>,
|
||||
limits?: RequestLimits,
|
||||
): void {
|
||||
if (wsRoutes.length === 0 && !meshControl) return;
|
||||
const WebSocketServer = loadWss();
|
||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null;
|
||||
// `maxPayload` is the pre-buffer half of `maxWsMessageBytes`: `ws` refuses an oversized frame,
|
||||
// fragmented or not, before it is assembled, and closes 1009 itself. `boundInbound` repeats the
|
||||
// check on the decoded text, which is the only half Deno and the edge have.
|
||||
const wss = WebSocketServer ? new WebSocketServer({ noServer: true, maxPayload: wsMessageBytes(limits) }) : null;
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
// A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody
|
||||
// else is listening to yet: that is as fatal as a throw.
|
||||
@@ -110,7 +123,7 @@ export function attachWs(
|
||||
// Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an
|
||||
// uncaught exception that takes the whole process down, not a 500 for one client.
|
||||
try {
|
||||
routeUpgrade(wss, wsRoutes, req, socket, head, bus, meshControl, streams);
|
||||
routeUpgrade({ wss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
|
||||
} catch {
|
||||
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
|
||||
else socket.destroy();
|
||||
@@ -118,17 +131,19 @@ export function attachWs(
|
||||
});
|
||||
}
|
||||
|
||||
/** What every upgrade on one server shares. */
|
||||
interface UpgradeEnv {
|
||||
wss: any;
|
||||
wsRoutes: WsRouteDef[];
|
||||
bus?: Bus;
|
||||
meshControl?: MeshControl;
|
||||
streams?: Set<() => void>;
|
||||
limits?: RequestLimits;
|
||||
}
|
||||
|
||||
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
|
||||
function routeUpgrade(
|
||||
wss: any,
|
||||
wsRoutes: WsRouteDef[],
|
||||
req: http.IncomingMessage,
|
||||
socket: any,
|
||||
head: Buffer,
|
||||
bus?: Bus,
|
||||
meshControl?: MeshControl,
|
||||
streams?: Set<() => void>,
|
||||
): void {
|
||||
function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void {
|
||||
const { wss, wsRoutes, bus, meshControl, streams, limits } = env;
|
||||
let path: string;
|
||||
|
||||
// The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed
|
||||
@@ -140,7 +155,7 @@ function routeUpgrade(
|
||||
return;
|
||||
}
|
||||
|
||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return;
|
||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams, limits)) return;
|
||||
|
||||
const route = matchWsRoute(wsRoutes, path);
|
||||
|
||||
@@ -155,6 +170,6 @@ function routeUpgrade(
|
||||
}
|
||||
|
||||
wss.handleUpgrade(req, socket, head, (ws: any) => {
|
||||
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
|
||||
void runWsConnection(boundInbound(nodeSocket(ws), limits), nodeWsRequest(req), route, bus, streams);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user