fix(ws): bound inbound frames synchronously and all-or-nothing
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s

Two gaps in boundInbound, both from review of #117.

The bound ran in an async pump reading the adapter's channel. `ws` emits a
whole TCP read's worth of frames synchronously, so the unbounded channel
took the burst before the pump saw the first frame: with maxWsQueue 2, a
2,000-frame burst reached the channel in full before close(1013). boundInbound now taps
the channel through an internal, non-exported hook that runs inside push(),
so each frame is bounded before it is queued. Measured on the Node
listen() path, the same burst now closes on the 3rd frame.

accept() also offered a frame to consumers in order and closed 1013 when a
later queue was full, so the rejected frame had already reached earlier
consumers. Capacity is now checked for every consumer before any delivery.

Refs #107

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-10 11:42:38 -05:00
1 parent 7fa02d16be
commit 26bacdb304
4 files changed
+96 -11

No files matched your search

+31 -2
View File
@@ -14,6 +14,26 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'; return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
} }
/**
* Internal: reads a channel synchronously, inside `push`, rather than through an async iterator
* that only drains once the event loop yields. `boundInbound` needs it to bound a WebSocket burst
* frame by frame, before anything is queued (#107). Not exported from the package; `Symbol.for`
* because each tsup entry carries its own copy of this module.
*/
export const CHANNEL_TAP: unique symbol = Symbol.for('green-tea.channel-tap');
/** What {@link CHANNEL_TAP} calls, synchronously, for every push, close and fail. */
export interface ChannelSink<T> {
push(value: T): void;
end(): void;
fail(err: unknown): void;
}
/** A channel that can be tapped; every channel built by {@link channel} is one. */
export interface TappableChannel<T> extends Channel<T> {
[CHANNEL_TAP](sink: ChannelSink<T>): () => void;
}
interface Sub<T> { interface Sub<T> {
iterator: AsyncIterator<T>; iterator: AsyncIterator<T>;
push(value: T, cap: number): void; push(value: T, cap: number): void;
@@ -84,9 +104,9 @@ function newSub<T>(onReturn: () => void): Sub<T> {
* Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber. * Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber.
* @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded). * @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded).
*/ */
export function channel<T>(opts: { buffer?: number } = {}): Channel<T> { export function channel<T>(opts: { buffer?: number } = {}): TappableChannel<T> {
const cap = opts.buffer ?? Infinity; const cap = opts.buffer ?? Infinity;
const subs = new Set<Sub<T>>(); const subs = new Set<Omit<Sub<T>, 'iterator'>>();
let done = false; let done = false;
let closedFlag = false; let closedFlag = false;
@@ -117,5 +137,14 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
subs.add(sub); subs.add(sub);
return sub.iterator; return sub.iterator;
}, },
[CHANNEL_TAP](sink) {
if (done) {
sink.end();
return () => {};
}
subs.add(sink);
return () => subs.delete(sink);
},
}; };
} }
+2 -2
View File
@@ -1,4 +1,4 @@
import { channel } from '../channel'; import { channel, type Channel } from '../channel';
import type { App } from '../app/types'; import type { App } from '../app/types';
import type { WsRequest, WsSocket } from './ws-core'; import type { WsRequest, WsSocket } from './ws-core';
import { nodeRequire } from '../node-require'; import { nodeRequire } from '../node-require';
@@ -91,7 +91,7 @@ export function eventSocket(host: EventfulSocket): WsSocket {
*/ */
export function neutralSocket( export function neutralSocket(
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void }, host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
inbound: ReturnType<typeof channel<unknown>>, inbound: Channel<unknown>,
ac: AbortController, ac: AbortController,
): WsSocket { ): WsSocket {
return { return {
+34 -7
View File
@@ -1,4 +1,5 @@
import { isHttpError } from '../signals'; import { isHttpError } from '../signals';
import { CHANNEL_TAP, type TappableChannel } from '../channel';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { correlateRequest } from './core'; import { correlateRequest } from './core';
import { matchPattern } from './router'; import { matchPattern } from './router';
@@ -80,7 +81,9 @@ export function boundInbound(
): WsSocket { ): WsSocket {
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE); const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
void fanout.pump(); const tap = (socket.inbound as Partial<TappableChannel<unknown>>)[CHANNEL_TAP];
if (tap) fanout.tap(tap);
else void fanout.pump();
return Object.create(socket, { return Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } }, inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
@@ -103,6 +106,24 @@ class InboundFanout {
this.first = this.add(); this.first = this.add();
} }
/**
* 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
* unbounded queue has already taken the burst. Here each frame is bounded before it is queued.
*/
tap(tap: TappableChannel<unknown>[typeof CHANNEL_TAP]): void {
const untap = tap({
push: (msg) => {
if (this.ended || this.accept(msg)) return;
untap();
this.settle();
},
end: () => this.settle(),
fail: (err) => this.settle({ err }),
});
}
// ponytail: only for an inbound that is not a channel (no adapter builds one); bounds late.
async pump(): Promise<void> { async pump(): Promise<void> {
try { try {
for await (const msg of this.socket.inbound) { for await (const msg of this.socket.inbound) {
@@ -135,13 +156,16 @@ class InboundFanout {
return false; return false;
} }
// Capacity first, for every consumer: a frame that overflows one queue reaches none, so a
// rejected frame cannot run some handlers' side effects and not others'.
for (const sub of this.subs) { for (const sub of this.subs) {
if (!sub.offer(msg, this.maxQueue)) { if (sub.full(this.maxQueue)) {
this.socket.close(1013, 'inbound queue full'); this.socket.close(1013, 'inbound queue full');
return false; return false;
} }
} }
for (const sub of this.subs) sub.offer(msg);
return true; return true;
} }
@@ -164,19 +188,22 @@ class InboundSub implements AsyncIterator<unknown> {
constructor(private readonly onReturn: () => void) {} constructor(private readonly onReturn: () => void) {}
/** Hands `msg` to a waiting `next()` or queues it; false when `max` frames are already waiting. */ /** True when `max` frames are already waiting and no `next()` is there to take another. */
offer(msg: unknown, max: number): boolean { full(max: number): boolean {
return !this.waiter && this.queue.length >= max;
}
/** Hands `msg` to a waiting `next()` or queues it; callers check {@link full} first. */
offer(msg: unknown): void {
const waiter = this.waiter; const waiter = this.waiter;
if (waiter) { if (waiter) {
this.waiter = null; this.waiter = null;
waiter.resolve({ value: msg, done: false }); waiter.resolve({ value: msg, done: false });
return true; return;
} }
if (this.queue.length >= max) return false;
this.queue.push(msg); this.queue.push(msg);
return true;
} }
next(): Promise<IteratorResult<unknown>> { next(): Promise<IteratorResult<unknown>> {
+29
View File
@@ -340,6 +340,35 @@ describe('boundInbound (#107)', () => {
expect(closes).toEqual([[1013, 'inbound queue full']]); expect(closes).toEqual([[1013, 'inbound queue full']]);
}); });
it('fans out: a frame that overflows any queue reaches no consumer', async () => {
const { socket, inbound, closes } = fakeSocket();
const bounded = boundInbound(socket, { maxWsQueue: 1 });
const fast = bounded.inbound[Symbol.asyncIterator]();
bounded.inbound[Symbol.asyncIterator](); // stalled
const first = fast.next();
inbound.push('a'); // fast takes it, stalled queues it: 1/1
expect(await first).toEqual({ value: 'a', done: false });
const second = fast.next();
inbound.push('b'); // stalled is full: rejected for everyone
expect(closes).toEqual([[1013, 'inbound queue full']]);
expect(await second).toEqual({ value: undefined, done: true });
});
it('enforces the queue bound inside a synchronous burst, before the event loop yields', () => {
const { socket, inbound, closes } = fakeSocket();
const bounded = boundInbound(socket, { maxWsQueue: 2 });
bounded.inbound[Symbol.asyncIterator](); // stalled
for (let i = 0; i < 100_000; i++) inbound.push(String(i)); // what `ws` does with one TCP read
expect(closes).toEqual([[1013, 'inbound queue full']]);
});
it('enforces the size bound synchronously too', () => {
const { socket, inbound, closes } = fakeSocket();
boundInbound(socket, { maxWsMessageBytes: 3 });
inbound.push('abcd');
expect(closes).toEqual([[1009, 'message too large']]);
});
it('T15: keeps the socket capabilities other than inbound', () => { it('T15: keeps the socket capabilities other than inbound', () => {
const { socket } = fakeSocket(); const { socket } = fakeSocket();
const bounded = boundInbound(socket); const bounded = boundInbound(socket);