diff --git a/src/channel.ts b/src/channel.ts index 7f71793..8cd394c 100644 --- a/src/channel.ts +++ b/src/channel.ts @@ -14,6 +14,26 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable { 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 { + 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 extends Channel { + [CHANNEL_TAP](sink: ChannelSink): () => void; +} + interface Sub { iterator: AsyncIterator; push(value: T, cap: number): void; @@ -84,9 +104,9 @@ function newSub(onReturn: () => void): Sub { * 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). */ -export function channel(opts: { buffer?: number } = {}): Channel { +export function channel(opts: { buffer?: number } = {}): TappableChannel { const cap = opts.buffer ?? Infinity; - const subs = new Set>(); + const subs = new Set, 'iterator'>>(); let done = false; let closedFlag = false; @@ -117,5 +137,14 @@ export function channel(opts: { buffer?: number } = {}): Channel { subs.add(sub); return sub.iterator; }, + [CHANNEL_TAP](sink) { + if (done) { + sink.end(); + return () => {}; + } + + subs.add(sink); + return () => subs.delete(sink); + }, }; } diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts index 2400c60..a91d7cb 100644 --- a/src/http/ws-adapter.ts +++ b/src/http/ws-adapter.ts @@ -1,4 +1,4 @@ -import { channel } from '../channel'; +import { channel, type Channel } from '../channel'; import type { App } from '../app/types'; import type { WsRequest, WsSocket } from './ws-core'; import { nodeRequire } from '../node-require'; @@ -91,7 +91,7 @@ export function eventSocket(host: EventfulSocket): WsSocket { */ export function neutralSocket( host: Pick & { terminate?(): void }, - inbound: ReturnType>, + inbound: Channel, ac: AbortController, ): WsSocket { return { diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts index 8c1d71e..2c1853e 100644 --- a/src/http/ws-core.ts +++ b/src/http/ws-core.ts @@ -1,4 +1,5 @@ import { isHttpError } from '../signals'; +import { CHANNEL_TAP, type TappableChannel } from '../channel'; import type { Bus } from '../bus'; import { correlateRequest } from './core'; import { matchPattern } from './router'; @@ -80,7 +81,9 @@ export function boundInbound( ): WsSocket { const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE); - void fanout.pump(); + const tap = (socket.inbound as Partial>)[CHANNEL_TAP]; + if (tap) fanout.tap(tap); + else void fanout.pump(); return Object.create(socket, { inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } }, @@ -103,6 +106,24 @@ class InboundFanout { 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[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 { try { for await (const msg of this.socket.inbound) { @@ -135,13 +156,16 @@ class InboundFanout { 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) { - if (!sub.offer(msg, this.maxQueue)) { + if (sub.full(this.maxQueue)) { this.socket.close(1013, 'inbound queue full'); return false; } } + for (const sub of this.subs) sub.offer(msg); return true; } @@ -164,19 +188,22 @@ class InboundSub implements AsyncIterator { constructor(private readonly onReturn: () => void) {} - /** Hands `msg` to a waiting `next()` or queues it; false when `max` frames are already waiting. */ - offer(msg: unknown, max: number): boolean { + /** True when `max` frames are already waiting and no `next()` is there to take another. */ + 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; if (waiter) { this.waiter = null; waiter.resolve({ value: msg, done: false }); - return true; + return; } - if (this.queue.length >= max) return false; this.queue.push(msg); - return true; } next(): Promise> { diff --git a/test/ws-limits.test.ts b/test/ws-limits.test.ts index 5d95670..f58f6c7 100644 --- a/test/ws-limits.test.ts +++ b/test/ws-limits.test.ts @@ -340,6 +340,35 @@ describe('boundInbound (#107)', () => { 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', () => { const { socket } = fakeSocket(); const bounded = boundInbound(socket);