No files matched your search
+31
-2
@@ -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';
|
||||
}
|
||||
|
||||
/**
|
||||
* 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> {
|
||||
iterator: AsyncIterator<T>;
|
||||
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.
|
||||
* @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 subs = new Set<Sub<T>>();
|
||||
const subs = new Set<Omit<Sub<T>, 'iterator'>>();
|
||||
let done = false;
|
||||
let closedFlag = false;
|
||||
|
||||
@@ -117,5 +137,14 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
|
||||
subs.add(sub);
|
||||
return sub.iterator;
|
||||
},
|
||||
[CHANNEL_TAP](sink) {
|
||||
if (done) {
|
||||
sink.end();
|
||||
return () => {};
|
||||
}
|
||||
|
||||
subs.add(sink);
|
||||
return () => subs.delete(sink);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
|
||||
inbound: ReturnType<typeof channel<unknown>>,
|
||||
inbound: Channel<unknown>,
|
||||
ac: AbortController,
|
||||
): WsSocket {
|
||||
return {
|
||||
|
||||
+34
-7
@@ -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<TappableChannel<unknown>>)[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<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> {
|
||||
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<unknown> {
|
||||
|
||||
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<IteratorResult<unknown>> {
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user