3 Commits
Author SHA1 Message Date
chrnx 1c9f387b91 fix(ws): wait for the send buffer before pulling the next outbound value (CARD-26, #41)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 27s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 30s
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>
2026-10-23 00:52:32 -05:00
chrnx bd85bf67bc fix(mesh): hold the control channel to hello size until the peer authenticates
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 14s
boundInbound(socket, meshBounds) runs before ensureBooted() and before
the hello is checked, and meshBounds allowed 4,096 queued frames of up
to 7 MB each. During a slow boot nothing reads that queue, so an
unauthenticated peer could make the process buffer tens of GB.

The control channel's bounds are now phased (controlBounds() replaces
controlLimits()):
- until the hello is accepted: frames of at most HELLO_FRAME_BYTES
  (64 KiB) and the default 16-frame queue, so about 1 MiB per
  connection;
- after: the frame bound from #120 and the queue bound from #148.

boundInbound takes the second set as an optional `widened` argument and
keeps the switch on the bounded socket under a Symbol.for key. The
teapot calls widenInbound() when the handshake succeeds. The teapot's
own parse check follows the same phases, so a standalone
createMeshControl also refuses a pre-auth frame over hello size.

This is an auth-phased bound rather than a total-bytes cap: the only
unauthenticated frame with a purpose is the hello, and phasing keeps
the trusted path free of a second accounting rule. No new option.

On Node the control path's native maxPayload stays at the authed bound,
because ws cannot change it per phase. A pre-auth peer can still make
ws assemble one frame of up to that size before boundInbound closes
the connection with 1009. That frame is transient and never queued.

Tests: during a delayed boot, a 1 MB pre-auth frame closes 1009 at once
and a flood closes 1013 within 17 frames; after the hello, large frames
and a 64-ping burst are accepted. On Node, Deno and Bun, an
unauthenticated 1 MB frame over a real socket closes 1009. The #148
64-RPC test stays green.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:52:20 -05:00
chrnx de798771e4 fix(mesh): size control frames for the worst escaping a body can get (#120)
A 999,000-byte text/plain body of U+0001, within maxBodyBytes, still
failed 503: the envelope carries a text body as a JSON string, each
control character escapes to six characters, and the ~6 MB frame was
over the 4,000,000 the channel was sized to.

controlFrameLimit() is now 6 x maxBodyBytes plus 1 MiB for headers,
params, query and the envelope: 7,048,576 at the 1 MB default. Six is
the worst growth of any body byte; quotes and backslashes double, JSON
numbers like 1e20 grow about fivefold, multipart Buffers at most
fourfold, and non-ASCII text is not escaped. The fixed MAX_FRAME_CHARS
goes away with it.

Test (T1c) on Node, Deno and Bun: the control-character body now
answers 200 and the channel stays open.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:49:34 -05:00
17 changed files with 912 additions and 73 deletions

No files matched your search

+35 -7
View File
@@ -69,6 +69,11 @@ npm treats versions as semver and semver forbids leading zeros.
about `maxConnections × maxWsQueue × maxWsMessageBytes`, ≈ 15.6 GiB at the Node defaults; Deno and
Bun have no connection cap, so set one at the platform or proxy there.
- **`WsSocket.drained()`** (#41): an optional method an adapter's socket provides so the outbound
pump can wait for its send buffer. It resolves once the buffer is at or below the adapter's
high-water mark, or the socket has closed, and at once when it already is. The built-in adapters
all provide it. A socket built without it is never waited on, as before.
### Changed
- **HTTP route lookup uses a radix index** (#109). The router used to scan a specificity-sorted
@@ -83,6 +88,22 @@ npm treats versions as semver and semver forbids leading zeros.
### Fixed
- **WebSocket outbound respects backpressure** (#41). A `@Ws` handler's async iterator was pulled
as fast as it could yield, whatever the peer read, so a fast producer and a slow client grew the
send buffer without limit: 10,000 frames of 64 KiB put 640 MiB in memory at once. The pump now
waits before each pull while the socket's buffer is over 1 MiB, an internal mark rather than an
option, so a slow peer holds at most about that plus one frame. A peer that keeps up never makes
it wait. If the peer goes away while the pump waits, the wait ends and the iterator's `return()`
runs, as on any other close. Each runtime signals in its own way: Node uses `ws`'s
`bufferedAmount` and send callback, Bun uses `getBufferedAmount()` and its `drain` callback, and
Deno polls `bufferedAmount`, since its `WebSocket` has no drain event. **workerd reports no
buffered amount**, so on the edge the pump never waits and buffering is left to the platform.
- **On Deno, a `@Ws` handler that yields at once no longer loses the connection.** Deno hands the
socket over before it is open. A value yielded in that window was pulled, the pump found the
socket not open, and it gave up: the client got no frame and a close without a code (`1005`).
The pump now waits for the socket to open, as part of the same backpressure wait.
- **A mesh RPC whose body is within `maxBodyBytes` reaches the teapot again** (#120). The 1 MiB
WebSocket cap from #107 also bounded the mesh control channel, so a request body that fit the
HTTP limit could still exceed it once the teacup wrapped it in an RPC frame. A text body near
@@ -90,13 +111,14 @@ npm treats versions as semver and semver forbids leading zeros.
above 1 MiB was capped at 1 MiB on the channel. Either way the teapot closed the whole channel
with `1009`, and every request through that link failed with `503` until it reconnected.
The control channel is now bounded by the teapot's `limits.maxBodyBytes`: 4,000,000 bytes at the
1 MB default, the figure its frame parser already used, and four times the body limit when that
is raised. `limits.maxWsMessageBytes` still governs every user `@Ws` route, unchanged. On Bun,
which takes one native payload limit for all sockets, a teapot raises that limit to the control
channel's bound, so an oversized frame on a user route is refused by the framework instead: still
`1009`, on every Bun version, where Bun before 1.4 refused natively by dropping the connection
(`1006`).
The control channel is now bounded by the teapot's `limits.maxBodyBytes`: six times the body
limit, the most JSON escaping can grow a body (a control character becomes `\u0001`), plus 1 MiB
for headers and the rest of the envelope. That is 7,048,576 bytes at the 1 MB default, up from
the frame parser's former fixed 4,000,000. `limits.maxWsMessageBytes` still governs every user
`@Ws` route, unchanged. On Bun, which takes one native payload limit for all sockets, a teapot
raises that limit to the control channel's bound, so an oversized frame on a user route is
refused by the framework instead: still `1009`, on every Bun version, where Bun before 1.4
refused natively by dropping the connection (`1006`).
- **More than 16 mesh RPCs in flight on one link no longer drop the control channel** (#148). The
16-frame inbound queue from #107 (`limits.maxWsQueue`) also applied to the control channel. On
@@ -106,6 +128,12 @@ npm treats versions as semver and semver forbids leading zeros.
more than one socket read can carry. User `@Ws` routes keep closing `1013` at `maxWsQueue`. Deno
and Bun deliver frames one at a time and did not hit this, but they now share the same bound.
Both larger bounds, this one and the frame size from #120, **apply only once the peer's `hello`
is accepted**. Until then the control channel takes frames of at most 64 KiB and queues at most
16, and closes with `1009` or `1013` past that. An unauthenticated peer can therefore make a
teapot hold about 1 MiB per connection, including while `app.upgrade` waits for a slow boot,
instead of thousands of multi-megabyte frames.
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
was served. Containment now compares real paths: the requested file, and a directory's
+11 -7
View File
@@ -10,7 +10,7 @@ import type { HttpOptions } from '../http';
import { buildFetch } from '../http/web';
import {
boundInbound,
controlLimits,
controlBounds,
validateWsLimits,
WS_MAX_MESSAGE_BYTES,
wsMessageBytes,
@@ -335,7 +335,7 @@ export function createApp(opts: {
);
// Known at construction, unlike the control channel itself, because `app.upgrade` must bound a
// socket before it awaits the boot (#120).
const meshBounds = controlLimits(opts.limits, controlFrameLimit(opts.limits?.maxBodyBytes));
const meshBounds = controlBounds(opts.limits, controlFrameLimit(opts.limits?.maxBodyBytes));
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
limits: opts.limits,
meshBounds,
@@ -1242,10 +1242,10 @@ function nativeWsBytes(
mesh: MeshConfig | undefined,
registry: Registry,
limits: RequestLimits | undefined,
meshBounds: { maxWsMessageBytes: number },
meshBounds: ReturnType<typeof controlBounds>,
): number {
const servesControl = mesh?.secret && (registry.exportedSteps.length || registry.exportedRoutes.length);
return servesControl ? meshBounds.maxWsMessageBytes : wsMessageBytes(limits);
return servesControl ? meshBounds.authed.maxWsMessageBytes : wsMessageBytes(limits);
}
/**
@@ -1431,7 +1431,7 @@ function buildAppUpgrade(
streams: Set<() => void>,
ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined,
bounds: { limits?: RequestLimits; meshBounds: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'> },
bounds: { limits?: RequestLimits; meshBounds: ReturnType<typeof controlBounds> },
): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined;
@@ -1441,7 +1441,8 @@ function buildAppUpgrade(
// 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.
// The path comes first, though, because it decides the bound: the mesh control channel carries
// whole request bodies and is bounded by the body limit, not `maxWsMessageBytes` (#120).
// whole request bodies and is bounded by the body limit, not `maxWsMessageBytes` (#120) — once
// its peer authenticates. Until then, and so throughout the boot, it takes hello-sized frames.
let path: string;
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
@@ -1453,7 +1454,10 @@ function buildAppUpgrade(
return;
}
const ready = boundInbound(socket, path === MESH_CONTROL_PATH ? bounds.meshBounds : bounds.limits);
const ready =
path === MESH_CONTROL_PATH
? boundInbound(socket, bounds.meshBounds.preAuth, bounds.meshBounds.authed)
: boundInbound(socket, bounds.limits);
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
+33 -4
View File
@@ -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 { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown';
import { setPeer } from './http/peer';
@@ -14,12 +20,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 {
@@ -57,6 +66,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());
}
/**
@@ -65,9 +81,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 });
}
/**
@@ -97,7 +121,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 });
}
@@ -125,15 +149,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
View File
@@ -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;
+82 -17
View File
@@ -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). */
@@ -42,31 +58,60 @@ export function wsMessageBytes(limits: Pick<RequestLimits, 'maxWsMessageBytes'>
}
/**
* Undelivered inbound frames the mesh control channel may hold (#148), in place of
* `limits.maxWsQueue` when larger. Its consumer, the teapot's frame loop, never awaits between
* frames, so its queue only ever holds one delivery burst: `ws` emits every frame of one socket
* read synchronously, and a read is at most 64 KiB, under 4,096 of the smallest control frame
* (`{"type":"ping"}`). A teacup with many RPCs in flight sends exactly such bursts, which the
* 16-frame user default closed with 1013. Still finite, so a peer flooding the channel while
* nothing reads it — before the boot finishes, say — is still cut off.
* Undelivered inbound frames the mesh control channel may hold once its peer is authenticated
* (#148), in place of `limits.maxWsQueue` when larger. Its consumer, the teapot's frame loop, never
* awaits between frames, so its queue only ever holds one delivery burst: `ws` emits every frame of
* one socket read synchronously, and a read is at most 64 KiB, under 4,096 of the smallest control
* frame (`{"type":"ping"}`). A teacup with many RPCs in flight sends exactly such bursts, which the
* 16-frame user default closed with 1013.
*/
const CONTROL_QUEUE = 4096;
/**
* The limits the mesh control channel's socket is bounded by: `limits` with `maxWsMessageBytes`
* raised to the channel's own frame bound (#120) and `maxWsQueue` to {@link CONTROL_QUEUE} (#148),
* each only when larger. A user route never goes through this, so it keeps both as configured.
* Largest frame the mesh control channel accepts before its peer's `hello` is accepted. A hello
* is a version and a secret; nothing larger has a reason to arrive first.
*/
export function controlLimits(
export const HELLO_FRAME_BYTES = 65_536;
/** Inbound bounds for one socket, as {@link boundInbound} takes them. */
type InboundLimits = { maxWsMessageBytes: number; maxWsQueue: number };
/**
* The bounds of the mesh control channel's socket, in two phases.
*
* - `preAuth`, until the peer's `hello` is accepted: hello-sized frames and the default 16-frame
* queue, so an unauthenticated peer can make the process hold about 1 MiB at most — including
* while `app.upgrade` waits for a slow boot, before anything reads the queue.
* - `authed`, after: `maxWsMessageBytes` raised to the channel's frame bound (#120) and `maxWsQueue`
* to {@link CONTROL_QUEUE} (#148), each only when larger. The peer holds the mesh secret by then.
*
* A user route never goes through this, so it keeps both limits as configured.
*/
export function controlBounds(
limits: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'> | undefined,
maxFrameBytes: number | undefined,
): { maxWsMessageBytes: number; maxWsQueue: number } {
): { preAuth: InboundLimits; authed: InboundLimits } {
return {
maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0),
maxWsQueue: Math.max(limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE, CONTROL_QUEUE),
preAuth: { maxWsMessageBytes: HELLO_FRAME_BYTES, maxWsQueue: DEFAULT_MAX_WS_QUEUE },
authed: {
maxWsMessageBytes: Math.max(wsMessageBytes(limits), maxFrameBytes ?? 0),
maxWsQueue: Math.max(limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE, CONTROL_QUEUE),
},
};
}
/** Where a socket bounded with a second phase keeps the switch to it; `Symbol.for`, as above. */
const WIDEN_INBOUND: unique symbol = Symbol.for('green-tea.widen-inbound');
/**
* Switches a socket from {@link boundInbound}'s first bounds to the `widened` ones it was given —
* for the mesh control channel, once the peer has authenticated. A no-op on any other socket.
* Frames already queued stay; the new bounds apply to the frames that arrive next.
*/
export function widenInbound(socket: WsSocket): void {
(socket as { [WIDEN_INBOUND]?: () => void })[WIDEN_INBOUND]?.();
}
/** 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) {
@@ -100,10 +145,14 @@ function exceedsBytes(msg: unknown, max: number): boolean {
* consumer. After that the returned `inbound` fans out like `channel`: each iterator gets every
* frame from the moment it subscribes, through its own queue, and the bound applies to each queue.
* Every other capability is the original socket's.
*
* `widened`, when given, is a second set of bounds that {@link widenInbound} switches to later: the
* mesh control channel starts at hello size and widens once its peer authenticates.
*/
export function boundInbound(
socket: WsSocket,
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
widened?: InboundLimits,
): WsSocket {
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
@@ -113,6 +162,7 @@ export function boundInbound(
return Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
...(widened && { [WIDEN_INBOUND]: { value: () => fanout.widen(widened) } }),
}) as WsSocket;
}
@@ -126,12 +176,18 @@ class InboundFanout {
constructor(
private readonly socket: WsSocket,
private readonly maxBytes: number,
private readonly maxQueue: number,
private maxBytes: number,
private maxQueue: number,
) {
this.first = this.add();
}
/** Applies the second phase's bounds; see {@link widenInbound}. */
widen(limits: InboundLimits): void {
this.maxBytes = limits.maxWsMessageBytes;
this.maxQueue = limits.maxWsQueue;
}
/**
* Reads the adapter's channel inside its `push`. Runtimes emit a whole read's worth of frames
* synchronously — `ws` does — so a bound checked after the event loop yields is checked after an
@@ -305,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;
+21 -8
View File
@@ -6,8 +6,9 @@ import {
matchWsRoute,
trackUntil,
boundInbound,
controlLimits,
controlBounds,
wsMessageBytes,
WS_HIGH_WATER_MARK,
type WsSocket,
type WsRequest,
} from './ws-core';
@@ -50,10 +51,10 @@ function handleMeshUpgrade(
return true;
}
// An RPC carries a whole request body, so the channel is bounded by the teapot's body limit
// rather than `maxWsMessageBytes` (#120). `wss` is built with that bound as `maxPayload`, and
// `boundInbound` repeats it on the decoded text, as it does for every route.
const bounds = controlLimits(limits, meshControl.maxFrameBytes);
// An RPC carries a whole request body, so once the peer authenticates the channel is bounded by
// the teapot's body limit rather than `maxWsMessageBytes` (#120). `wss` is built with that bound
// as `maxPayload`; until the hello is accepted, `boundInbound` holds the peer to hello size.
const bounds = controlBounds(limits, meshControl.maxFrameBytes);
// nodeSocket, not the raw ws: the control channel is the last consumer that spoke the
// `ws` EventEmitter API directly. It now takes the same neutral socket every route does.
@@ -61,7 +62,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 = boundInbound(nodeSocket(ws), bounds);
const neutral = boundInbound(nodeSocket(ws), bounds.preAuth, bounds.authed);
void trackUntil(neutral, meshControl.handle(neutral), streams);
});
@@ -82,10 +83,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 {
@@ -94,7 +106,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);
@@ -126,7 +139,7 @@ export function attachWs(
WebSocketServer && meshControl
? new WebSocketServer({
noServer: true,
maxPayload: controlLimits(limits, meshControl.maxFrameBytes).maxWsMessageBytes,
maxPayload: controlBounds(limits, meshControl.maxFrameBytes).authed.maxWsMessageBytes,
})
: null;
server.on('upgrade', (req, socket, head) => {
+29 -26
View File
@@ -3,7 +3,7 @@
// under node-compat on both; edge/workerd is out of scope (see the cross-runtime spec).
import crypto from 'node:crypto';
import type { Bus } from '../bus';
import type { WsSocket } from '../http/ws-core';
import { HELLO_FRAME_BYTES, widenInbound, type WsSocket } from '../http/ws-core';
import type { ResponseShape } from '../pipeline';
import { isHttpError } from '../signals';
import {
@@ -29,34 +29,33 @@ export const MESH_CONTROL_PATH = '/__mesh__/control';
*/
const HANDSHAKE_TIMEOUT_MS = 10_000;
/**
* Largest control frame the teapot will parse, in characters.
*
* `decode` runs `JSON.parse` on peer-controlled input, and until the handshake succeeds that peer
* is *unauthenticated* — so without a cap, anyone who can reach the port can make the process parse
* as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no
* documented ceiling on the platform sockets Deno and Bun provide).
*
* Sized for the 1 MB default body limit an RPC can legitimately carry, with room for the JSON
* overhead of the envelope around it. That overhead is not a constant: a JSON body re-encodes to
* about its own size, but a text body doubles wherever it holds a `"` or a backslash, since the
* envelope escapes it as a JSON string. {@link controlFrameLimit} scales this figure with a raised
* limit.
*/
const MAX_FRAME_CHARS = 4_000_000;
/** The body limit {@link MAX_FRAME_CHARS} is sized for: `limits.maxBodyBytes`'s default. */
/** `limits.maxBodyBytes`'s default, which a teapot without one is sized for. */
const DEFAULT_MAX_BODY_BYTES = 1_000_000;
/**
* Largest control frame a teapot accepts when the largest body it may be sent is `maxBodyBytes`
* (#120): {@link MAX_FRAME_CHARS}, scaled by the same ratio for a body limit raised above the
* default. Never below it, because the frame also carries headers, params and query, which do not
* shrink with a lowered body limit. Applies to the control channel only: user WebSocket routes keep
* `limits.maxWsMessageBytes`.
* The most a body byte can grow inside an `rpc-req` envelope. The envelope is JSON, and a text
* body travels as a JSON string, so a control character (`\u0001`) becomes the six characters of its
* escape. Nothing a body can hold grows more: a `"` or backslash doubles, a JSON number such as
* `1e20` re-encodes to about five times its length, a multipart `Buffer` to at most four, and
* non-ASCII text is not escaped at all.
*/
const WORST_ESCAPE = 6;
/** Room in a frame for everything but the body: headers, params, query, url and the envelope. */
const ENVELOPE_HEADROOM = 1_048_576;
/**
* Largest control frame a teapot accepts, in characters, when the largest body it may be sent is
* `maxBodyBytes` (#120): the body at its worst escaping plus {@link ENVELOPE_HEADROOM}, so any body
* within the limit fits. 7,048,576 at the 1 MB default.
*
* `decode` runs `JSON.parse` on peer-controlled input, so the parse is capped by this figure — and
* an unauthenticated peer never gets near it: until its `hello` is accepted, the channel takes only
* hello-sized frames (`HELLO_FRAME_BYTES`, `controlBounds` in `ws-core`). Applies to the control
* channel only: user WebSocket routes keep `limits.maxWsMessageBytes`.
*/
export function controlFrameLimit(maxBodyBytes = DEFAULT_MAX_BODY_BYTES): number {
return Math.max(MAX_FRAME_CHARS, Math.ceil((MAX_FRAME_CHARS / DEFAULT_MAX_BODY_BYTES) * maxBodyBytes));
return WORST_ESCAPE * maxBodyBytes + ENVELOPE_HEADROOM;
}
/** Assemble a {@link Manifest} from exported step tokens and buffered routes. */
@@ -123,6 +122,9 @@ function handleHandshake(socket: WsSocket, frame: Frame, deps: MeshControlDeps):
return false;
}
// The peer holds the secret now: lift the hello-sized bounds its socket was given to the ones
// that carry RPC bodies (#120, #148). A socket bounded without a second phase is left as it is.
widenInbound(socket);
socket.send(
encode({
type: 'manifest',
@@ -211,8 +213,9 @@ async function serveFrames(
for await (const data of socket.inbound) {
const raw = String(data);
// Checked before `decode`, because decoding is the expensive part being defended.
if (raw.length > maxFrameChars) {
// Checked before `decode`, because decoding is the expensive part being defended. Until the
// handshake, nothing larger than a hello is parsed, whatever the socket in front allowed.
if (raw.length > (authed ? maxFrameChars : HELLO_FRAME_BYTES)) {
socket.close(1009, 'mesh frame too large');
break;
}
+26
View File
@@ -98,6 +98,18 @@ test('mesh on Bun: a text body that JSON escaping doubles still reaches the teap
}
});
test('mesh on Bun: a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => {
const { post, close } = await pair();
try {
const res = await post('\u0001'.repeat(999_000), 'text/plain');
expect(res.status).toEqual(200);
expect(await res.json()).toEqual({ length: 999_000 });
expect((await post('ok', 'text/plain')).status).toEqual(200);
} finally {
await close();
}
});
test('mesh on Bun: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => {
const { post, close, teacup } = await pair();
try {
@@ -180,3 +192,17 @@ test('mesh on Bun: a user ws route on the same teapot still closes 1013 at maxWs
await close();
}
});
test('mesh on Bun: an unauthenticated peer sending a frame over hello size is closed 1009', async () => {
const { close, tPort } = await pair();
try {
const code = await new Promise<number>((resolve) => {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`);
ws.onopen = () => ws.send('x'.repeat(1_000_000));
ws.onclose = (e) => resolve(e.code);
});
expect(code).toEqual(1009);
} finally {
await close();
}
});
+78
View File
@@ -0,0 +1,78 @@
// #41 (CARD-26, D23) on Bun: the outbound pump waits while the socket is backed up. Bun has no
// `bufferedAmount` property; the adapter reads `getBufferedAmount()` and waits on `drain`.
// Node twin: test/ws-backpressure.test.ts, which explains the cases.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Route, Ws, Module } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { rawWs } from '../helpers/raw-ws.ts';
const FRAMES = 10_000;
const FRAME = 64 * 1024;
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const state = { pulled: 0, returned: false };
@Route('/bp')
class Flood {
@Ws('/flood')
flood() {
return (async function* () {
try {
for (let i = 0; i < FRAMES; i++) {
state.pulled++;
yield frame(i);
}
} finally {
state.returned = true;
}
})();
}
}
@Module({ mountpoint: '/', controllers: [Flood] })
class M {}
async function serve() {
state.pulled = 0;
state.returned = false;
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
return { server, port: server.port };
}
test('serveBun: ws outbound stops pulling while the client is not reading, then delivers in order (T1)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
const stalled = state.pulled;
await sleep(200);
expect(state.pulled).toBe(stalled);
expect(stalled).toBeLessThan(FRAMES / 10);
expect(await client.readAll(FRAMES)).toEqual({ received: FRAMES, inOrder: true });
expect(state.pulled).toBe(FRAMES);
client.destroy();
} finally {
server.stop(true);
}
}, 60_000);
test('serveBun: ws outbound ends the wait and calls return() when the client goes away (T2)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
expect(state.pulled).toBeLessThan(FRAMES / 10);
client.destroy();
await sleep(300);
expect(state.returned).toBe(true);
expect(state.pulled).toBeLessThan(FRAMES / 10);
} finally {
server.stop(true);
}
}, 60_000);
+26
View File
@@ -105,6 +105,18 @@ Deno.test('mesh on Deno: a text body that JSON escaping doubles still reaches th
}
});
Deno.test('mesh on Deno: a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => {
const { post, close } = await pair();
try {
const res = await post('\u0001'.repeat(999_000), 'text/plain');
assertEquals(res.status, 200);
assertEquals(await res.json(), { length: 999_000 });
assertEquals((await post('ok', 'text/plain')).status, 200);
} finally {
await close();
}
});
Deno.test('mesh on Deno: a body over maxBodyBytes is 413, and the channel stays open (T2)', async () => {
const { post, close } = await pair();
try {
@@ -176,3 +188,17 @@ Deno.test('mesh on Deno: a user ws route on the same teapot still closes 1013 at
await close();
}
});
Deno.test('mesh on Deno: an unauthenticated peer sending a frame over hello size is closed 1009', async () => {
const { close, tPort } = await pair();
try {
const code = await new Promise<number>((resolve) => {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`);
ws.onopen = () => ws.send('x'.repeat(1_000_000));
ws.onclose = (e) => resolve(e.code);
});
assertEquals(code, 1009);
} finally {
await close();
}
});
+114
View File
@@ -0,0 +1,114 @@
// #41 (CARD-26, D23) on Deno: the outbound pump waits while the socket is backed up. Deno's
// WebSocket fires no drain event, so the adapter polls `bufferedAmount` while over the mark.
// Node twin: test/ws-backpressure.test.ts, which explains the cases.
//
// Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assert, assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Ws, Module } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { rawWs } from '../helpers/raw-ws.ts';
const FRAMES = 10_000;
const FRAME = 64 * 1024;
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const state = { pulled: 0, returned: false };
@Route('/bp')
class Flood {
@Ws('/flood')
flood() {
return (async function* () {
try {
for (let i = 0; i < FRAMES; i++) {
state.pulled++;
yield frame(i);
}
} finally {
state.returned = true;
}
})();
}
}
@Route('/early')
class Early {
// Yields before Deno's socket has left CONNECTING. The pump used to pull 'hi', find the socket
// not open, and give up: the client got no frame and a close without a code (1005).
@Ws('/hi')
hi() {
return (async function* () {
yield 'hi';
await new Promise<never>(() => {});
})();
}
}
@Module({ mountpoint: '/', controllers: [Flood, Early] })
class M {}
async function serve() {
state.pulled = 0;
state.returned = false;
let port = 0;
const server = await serveDeno(createApp({ modules: [M] }), {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await sleep(50);
return { server, port };
}
Deno.test('serveDeno: ws outbound stops pulling while the client is not reading, then delivers in order (T1)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
const stalled = state.pulled;
await sleep(200);
assertEquals(state.pulled, stalled);
assert(stalled < FRAMES / 10, `pulled ${stalled} of ${FRAMES} with nobody reading`);
assertEquals(await client.readAll(FRAMES), { received: FRAMES, inOrder: true });
assertEquals(state.pulled, FRAMES);
client.destroy();
} finally {
await server.shutdown();
}
});
Deno.test('serveDeno: ws outbound ends the wait and calls return() when the client goes away (T2)', async () => {
const { server, port } = await serve();
try {
const client = await rawWs(port, '/bp/flood', FRAME);
client.pause();
await sleep(300);
assert(state.pulled < FRAMES / 10);
client.destroy();
await sleep(300);
assertEquals(state.returned, true);
assert(state.pulled < FRAMES / 10);
} finally {
await server.shutdown();
}
});
Deno.test('serveDeno: a ws route that yields at once still delivers its first frame', async () => {
const { server, port } = await serve();
try {
const first = await new Promise<string>((resolve, reject) => {
const ws = new WebSocket(`ws://127.0.0.1:${port}/early/hi`);
ws.onmessage = (e) => {
resolve(String(e.data));
ws.close();
};
ws.onclose = (e) => reject(new Error(`closed ${e.code} before any frame`));
});
assertEquals(first, 'hi');
} finally {
await server.shutdown();
}
});
+83
View File
@@ -0,0 +1,83 @@
// A WebSocket client over a bare `node:net` socket, for the backpressure tests (#41) on Deno and
// Bun. The platform `WebSocket` reads as fast as it can and cannot be told to stop; a TCP socket
// can be paused, which is the "client reads slowly" those tests need. Server frames are unmasked,
// and every frame these tests send is the same size, so frames are found by offset alone.
import net from 'node:net';
export interface RawWs {
/** Stop reading: the server's send buffer is all that can grow. */
pause(): void;
/** Resume reading; resolves once `count` frames have arrived, reporting whether they were in order. */
readAll(count: number): Promise<{ received: number; inOrder: boolean }>;
destroy(): void;
}
/**
* Opens `ws://127.0.0.1:<port><path>` and resolves once the 101 is in. Each server frame must be
* a text frame of exactly `payload` bytes (> 65535, so a 10-byte header) whose first 8 bytes are
* its zero-padded index.
*/
export function rawWs(port: number, path: string, payload: number): Promise<RawWs> {
const total = payload + 10;
const socket = net.connect(port, '127.0.0.1');
let head = '';
let upgraded = false;
let pos = 0;
let digits = '';
let received = 0;
let inOrder = true;
let onFrame = () => {};
const consume = (chunk: Uint8Array) => {
let i = 0;
while (i < chunk.length) {
if (pos < 18) {
if (pos === 0 && chunk[i] !== 0x81) inOrder = false;
if (pos >= 10) digits += String.fromCharCode(chunk[i]);
if (pos === 17) {
if (Number(digits) !== received) inOrder = false;
digits = '';
}
pos++;
i++;
} else {
const skip = Math.min(total - pos, chunk.length - i);
pos += skip;
i += skip;
}
if (pos === total) {
pos = 0;
received++;
onFrame();
}
}
};
return new Promise((resolve, reject) => {
socket.once('error', reject);
socket.on('data', (chunk: Uint8Array) => {
if (upgraded) return consume(chunk);
head += new TextDecoder('latin1').decode(chunk);
const end = head.indexOf('\r\n\r\n');
if (end < 0) return;
upgraded = true;
const rest = chunk.subarray(chunk.length - (head.length - end - 4));
resolve({
pause: () => socket.pause(),
readAll: (count) =>
new Promise((done) => {
onFrame = () => {
if (received === count) done({ received, inOrder });
};
socket.resume();
}),
destroy: () => socket.destroy(),
});
consume(rest);
});
socket.write(
`GET ${path} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n',
);
});
}
+100
View File
@@ -0,0 +1,100 @@
// Before a peer's `hello` is accepted, the mesh control channel takes only hello-sized frames and
// a small queue. The large bounds that carry RPC bodies (#120, #148) apply after authentication
// only, so an unauthenticated peer cannot make the process buffer `queue × frame` bytes — which
// at 4,096 × 7 MB was tens of GB, reachable while `app.upgrade` waits for a slow boot.
import { describe, it, expect } from 'vitest';
import { createApp, Module, Provider, Step } from '../../src/index';
import { channel } from '../../src/channel';
import { MESH_CONTROL_PATH } from '../../src/mesh/teapot';
import { encode, MESH_PROTOCOL_VERSION } from '../../src/mesh/protocol';
import type { WsSocket, WsRequest } from '../../src/http/ws-core';
@Provider({ provides: 'slow' })
class Slow {
async provide() {
await new Promise((resolve) => setTimeout(resolve, 300));
return { slow: true };
}
}
@Step({ provides: 'cfg', needs: [], export: true })
class Cfg {
run() {
return { cfg: 1 };
}
}
@Module({ mountpoint: '/api', providers: [Slow], steps: [Cfg] })
class SlowTeapot {}
function fakeSocket() {
const inbound = channel<unknown>();
const ac = new AbortController();
const sent: string[] = [];
const closes: number[] = [];
const socket: WsSocket = {
inbound,
abort: ac.signal,
get isOpen() {
return !ac.signal.aborted;
},
send: (d) => sent.push(d),
close: (code) => {
if (ac.signal.aborted) return;
closes.push(code ?? 1005);
ac.abort();
inbound.close();
},
terminate: () => ac.abort(),
};
return { socket, inbound, sent, closes };
}
const req: WsRequest = { url: MESH_CONTROL_PATH, headers: {}, protocol: 'http', ip: '' };
const teapot = () => createApp({ modules: [SlowTeapot], experimental: true, mesh: { secret: 's3cr3t' } });
describe('mesh control channel before authentication', () => {
it('closes 1009 on a frame over hello size while the boot is still running', async () => {
const app = teapot();
const { socket, inbound, closes } = fakeSocket();
const run = app.upgrade(req, socket);
inbound.push('x'.repeat(1_000_000));
expect(closes).toEqual([1009]); // at once: the boot has not finished, nothing was buffered
await run;
await app.close();
});
it('closes 1013 when an unauthenticated peer floods frames during the boot', async () => {
const app = teapot();
const { socket, inbound, closes } = fakeSocket();
const run = app.upgrade(req, socket);
let accepted = 0;
for (let i = 0; i < 64 && !closes.length; i++, accepted++) inbound.push('x'.repeat(1024));
expect(closes).toEqual([1013]);
expect(accepted).toBeLessThanOrEqual(17); // the user default, not the authenticated 4,096
await run;
await app.close();
});
it('lifts the bounds once the hello is accepted', async () => {
const app = teapot();
const { socket, inbound, sent, closes } = fakeSocket();
const run = app.upgrade(req, socket);
inbound.push(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: 's3cr3t' }));
await new Promise((resolve) => setTimeout(resolve, 400)); // boot, then the handshake
expect(JSON.parse(sent[0]).type).toBe('manifest');
// A frame far over hello size is accepted now (undecodable, so ignored), and a burst of 64
// fits the authenticated queue.
inbound.push('x'.repeat(1_000_000));
for (let i = 0; i < 64; i++) inbound.push(encode({ type: 'ping' }));
await new Promise((resolve) => setTimeout(resolve, 20));
expect(closes).toEqual([]);
expect(sent.filter((s) => s.includes('pong'))).toHaveLength(64);
socket.close(1000);
await run;
await app.close();
});
});
+2 -2
View File
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';
import { WebSocketServer } from 'ws';
import { connectLink } from '../../src/mesh/link';
import { envelopeFrom } from '../../src/mesh/teacup';
import { createMeshControl } from '../../src/mesh/teapot';
import { controlFrameLimit, createMeshControl } from '../../src/mesh/teapot';
import { encode, decode, MESH_PROTOCOL_VERSION, type RequestEnvelope } from '../../src/mesh/protocol';
import { Bus } from '../../src/bus';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
@@ -139,7 +139,7 @@ describe('teapot hardening', () => {
const fake = fakeSocket();
const running = control().handle(fake.socket as never);
fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(4_000_001)}"}`);
fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(controlFrameLimit() + 1)}"}`);
await running;
expect(fake.closes[0]?.code).toBe(1009);
+25
View File
@@ -91,6 +91,19 @@ describe('mesh RPC body near maxBodyBytes (#120)', () => {
}
});
it('a text body of control characters, escaped 6x, still reaches the teapot (T1c)', async () => {
const { post, close } = await pair();
try {
// `\u0001` re-encodes as the six characters `\u0001`: the worst escaping a body can get.
const res = await post('\u0001'.repeat(999_000), 'text/plain');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ length: 999_000 });
expect((await post('ok', 'text/plain')).status).toBe(200);
} finally {
await close();
}
});
it('a body over maxBodyBytes is refused 413 by the teacup, and the channel stays open (T2)', async () => {
const { post, close } = await pair();
try {
@@ -157,4 +170,16 @@ describe('mesh RPC body near maxBodyBytes (#120)', () => {
await close();
}
});
it('an unauthenticated peer sending a frame over hello size is closed 1009', async () => {
const { close, tPort } = await pair();
try {
const ws = new WebSocket(`ws://127.0.0.1:${tPort}/__mesh__/control`);
await new Promise((resolve) => ws.once('open', resolve));
const closed = new Promise<number>((resolve) => ws.once('close', (code) => resolve(code)));
ws.send('x'.repeat(1_000_000)); // within the authenticated bound, far over a hello
expect(await closed).toBe(1009);
} finally {
await close();
}
});
});
+109
View File
@@ -0,0 +1,109 @@
// #41 (CARD-26, D23): the outbound pump waits while the socket is backed up.
//
// Over a real `ws` server on Node: a route that can produce 10,000 frames of 64 KiB (640 MiB)
// for a client that has stopped reading. Without backpressure the pump pulls all of them into
// the send buffer at once; with it, it stops pulling after about the high-water mark plus what
// the kernel's socket buffers absorb. The Deno and Bun twins live in test/deno and test/bun; the
// exact "mark plus one frame" bound is pinned with a fake socket in ws-core.test.ts.
import { describe, it, expect } from 'vitest';
import WebSocket from 'ws';
import { createHttpServer, type WsRouteDef } from '../src/http';
const FRAMES = 10_000;
const FRAME = 64 * 1024;
/** Frame `i`: its index, zero-padded, then filler up to 64 KiB. */
const frame = (i: number) => String(i).padStart(8, '0') + 'x'.repeat(FRAME - 8);
const url = (server: import('http').Server, path: string) => {
const a = server.address();
if (a && typeof a === 'object') return `ws://127.0.0.1:${a.port}${path}`;
throw new Error('no address');
};
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
describe('ws outbound backpressure (#41)', () => {
it('stops pulling while the client is not reading, then delivers every frame in order (T1)', async () => {
let pulled = 0;
const wsRoutes: WsRouteDef[] = [
{
pattern: '/flood',
open: async () =>
(async function* () {
for (let i = 0; i < FRAMES; i++) {
pulled++;
yield frame(i);
}
})(),
},
];
const server = createHttpServer([], wsRoutes);
await new Promise<void>((resolve) => server.listen(0, resolve));
const client = new WebSocket(url(server, '/flood'));
await new Promise((resolve) => client.once('upgrade', resolve));
// The client stops reading from TCP: the server's send buffer is all that can grow.
(client as any)._socket.pause();
await sleep(300);
const stalled = pulled;
await sleep(200);
// Pulling has stopped, far short of the 10,000 frames on offer: about the 1 MiB mark plus the
// kernel's socket buffers. Before #41 every frame was pulled at once, 640 MiB in memory.
expect(pulled).toBe(stalled);
expect(stalled).toBeLessThan(FRAMES / 10);
let next = 0;
let inOrder = true;
const done = new Promise<void>((resolve) => {
client.on('message', (data) => {
if (data.toString('latin1', 0, 8) !== String(next).padStart(8, '0')) inOrder = false;
if (++next === FRAMES) resolve();
});
});
(client as any)._socket.resume();
await done;
expect(inOrder).toBe(true);
expect(pulled).toBe(FRAMES);
client.close();
server.close();
}, 60_000);
it('calls the iterator return() when the client goes away while the pump waits (T2)', async () => {
let pulled = 0;
let returned = false;
const wsRoutes: WsRouteDef[] = [
{
pattern: '/flood',
open: async () =>
(async function* () {
try {
for (let i = 0; i < FRAMES; i++) {
pulled++;
yield frame(i);
}
} finally {
returned = true;
}
})(),
},
];
const server = createHttpServer([], wsRoutes);
await new Promise<void>((resolve) => server.listen(0, resolve));
const client = new WebSocket(url(server, '/flood'));
await new Promise((resolve) => client.once('upgrade', resolve));
(client as any)._socket.pause();
await sleep(300);
expect(pulled).toBeLessThan(FRAMES / 10); // waiting, not finished
client.terminate();
await sleep(200);
expect(returned).toBe(true);
expect(pulled).toBeLessThan(FRAMES / 10);
server.close();
}, 30_000);
});
+103
View File
@@ -152,3 +152,106 @@ describe('runWsConnection correlation', () => {
expect(open.transport).toBe('ws');
});
});
describe('runWsConnection outbound backpressure (#41)', () => {
/** A fake socket with a send buffer that only empties when the test says so. */
function bufferedSocket(mark: number) {
const fake = fakeSocket();
let buffered = 0;
let wake: (() => void) | null = null;
const socket: WsSocket = Object.assign(Object.create(fake.socket), {
send: (d: string) => {
fake.sent.push(d);
buffered += d.length;
},
drained: () =>
buffered <= mark || fake.ac.signal.aborted
? Promise.resolve()
: new Promise<void>((resolve) => {
wake = resolve;
fake.ac.signal.addEventListener('abort', () => resolve(), { once: true });
}),
});
const flush = () => {
buffered = 0;
wake?.();
wake = null;
};
return { ...fake, socket, flush, buffered: () => buffered };
}
const flood = (count: number, size: number, onPull: () => void, onReturn = () => {}) => ({
pattern: '/ws',
open: async () =>
(async function* () {
try {
for (let i = 0; i < count; i++) {
onPull();
yield String(i).padStart(size, '0');
}
} finally {
onReturn();
}
})(),
});
it('pulls nothing more once the buffer is over the mark: it peaks at the mark plus one frame (T1)', async () => {
let pulled = 0;
const { socket, flush, buffered, sent } = bufferedSocket(10);
const run = runWsConnection(socket, req, { def: flood(100, 4, () => pulled++), params: {} });
await new Promise((resolve) => setTimeout(resolve, 10));
expect(pulled).toBe(3); // 4 + 4 + 4 = 12 > 10: waits after the third frame
expect(buffered()).toBeLessThanOrEqual(10 + 4);
while (pulled < 100) {
flush();
await new Promise((resolve) => setTimeout(resolve, 0));
}
flush();
await run;
expect(sent.map(Number)).toEqual([...Array(100).keys()]);
});
it('ends the wait on close and calls the iterator return(), without an unhandled rejection (T2)', async () => {
let pulled = 0;
let returned = false;
const unhandled: unknown[] = [];
const onUnhandled = (err: unknown) => unhandled.push(err);
process.on('unhandledRejection', onUnhandled);
try {
const { socket, ac } = bufferedSocket(0);
const run = runWsConnection(socket, req, {
def: flood(100, 4, () => pulled++, () => (returned = true)),
params: {},
});
await new Promise((resolve) => setTimeout(resolve, 10));
expect(pulled).toBe(1);
ac.abort(); // the peer went away
await run;
await new Promise((resolve) => setTimeout(resolve, 10));
expect(returned).toBe(true);
expect(pulled).toBe(1);
expect(unhandled).toEqual([]);
} finally {
process.off('unhandledRejection', onUnhandled);
}
});
it('never waits below the mark: drained() answers at once and every frame goes out (T3)', async () => {
let waits = 0;
const { socket, sent } = fakeSocket();
const counted: WsSocket = Object.assign(Object.create(socket), {
drained: () => {
waits++;
return Promise.resolve();
},
});
await runWsConnection(counted, req, { def: flood(50, 4, () => {}), params: {} });
expect(sent).toHaveLength(50);
expect(waits).toBe(51); // once before each pull, the last one being the pull that ends it
});
});