fix(ws): give every inbound consumer its own bounded queue
boundInbound returned one shared FIFO to every `inbound` iterator, with a single waiter slot. Two consumers waiting at once left one hanging forever, sequential consumers split frames, and one consumer's return() ended the stream for all. Node used to fan out through `channel`; Deno, Bun and edge already shared one iterator before #107, so the bug was older there. Each iterator now gets its own queue, and maxWsQueue bounds each one. Frames that arrive before anyone reads still go to the first consumer, which keeps the mesh `hello`. Refs #107 Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
2 files changed
+120
-37
No files matched your search
+82
-37
@@ -69,26 +69,29 @@ function exceedsBytes(msg: unknown, max: number): boolean {
|
|||||||
*
|
*
|
||||||
* Subscribes to `socket.inbound` immediately. `channel` is fan-out, so a frame pushed with no
|
* 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
|
* 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
|
* frames — for the mesh control channel, the `hello` itself. Those early frames go to the first
|
||||||
* single-consumer FIFO over those frames, and every other capability is the original socket's.
|
* 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.
|
||||||
*/
|
*/
|
||||||
export function boundInbound(
|
export function boundInbound(
|
||||||
socket: WsSocket,
|
socket: WsSocket,
|
||||||
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
|
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
|
||||||
): WsSocket {
|
): WsSocket {
|
||||||
const fifo = new InboundFifo(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
|
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
|
||||||
|
|
||||||
void fifo.pump();
|
void fanout.pump();
|
||||||
|
|
||||||
return Object.create(socket, {
|
return Object.create(socket, {
|
||||||
inbound: { value: { [Symbol.asyncIterator]: () => fifo } },
|
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
|
||||||
}) as WsSocket;
|
}) as WsSocket;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The single-consumer queue behind {@link boundInbound}; it is its own async iterator. */
|
/** The fan-out behind {@link boundInbound}: one bounded queue per consumer. */
|
||||||
class InboundFifo implements AsyncIterator<unknown> {
|
class InboundFanout {
|
||||||
private readonly queue: unknown[] = [];
|
private readonly subs = new Set<InboundSub>();
|
||||||
private waiter: { resolve: (r: IteratorResult<unknown>) => void; reject: (e: unknown) => void } | null = null;
|
/** Holds the frames that arrive before anyone reads; handed to the first consumer. */
|
||||||
|
private first: InboundSub | null;
|
||||||
private ended = false;
|
private ended = false;
|
||||||
private failure: { err: unknown } | null = null;
|
private failure: { err: unknown } | null = null;
|
||||||
|
|
||||||
@@ -96,7 +99,9 @@ class InboundFifo implements AsyncIterator<unknown> {
|
|||||||
private readonly socket: WsSocket,
|
private readonly socket: WsSocket,
|
||||||
private readonly maxBytes: number,
|
private readonly maxBytes: number,
|
||||||
private readonly maxQueue: number,
|
private readonly maxQueue: number,
|
||||||
) {}
|
) {
|
||||||
|
this.first = this.add();
|
||||||
|
}
|
||||||
|
|
||||||
async pump(): Promise<void> {
|
async pump(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
@@ -110,6 +115,70 @@ class InboundFifo implements AsyncIterator<unknown> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
subscribe(): AsyncIterator<unknown> {
|
||||||
|
const sub = this.first ?? this.add();
|
||||||
|
this.first = null;
|
||||||
|
return sub;
|
||||||
|
}
|
||||||
|
|
||||||
|
private add(): InboundSub {
|
||||||
|
const sub = new InboundSub(() => this.subs.delete(sub));
|
||||||
|
if (this.ended) sub.settle(this.failure ?? undefined);
|
||||||
|
else this.subs.add(sub);
|
||||||
|
return sub;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Delivers or queues one frame for every consumer; returns false once it has closed the socket. */
|
||||||
|
private accept(msg: unknown): boolean {
|
||||||
|
if (exceedsBytes(msg, this.maxBytes)) {
|
||||||
|
this.socket.close(1009, 'message too large');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const sub of this.subs) {
|
||||||
|
if (!sub.offer(msg, this.maxQueue)) {
|
||||||
|
this.socket.close(1013, 'inbound queue full');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ends every consumer 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;
|
||||||
|
for (const sub of this.subs) sub.settle(failure);
|
||||||
|
this.subs.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One consumer's queue; it is its own async iterator. */
|
||||||
|
class InboundSub 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 onReturn: () => void) {}
|
||||||
|
|
||||||
|
/** Hands `msg` to a waiting `next()` or queues it; false when `max` frames are already waiting. */
|
||||||
|
offer(msg: unknown, max: number): boolean {
|
||||||
|
const waiter = this.waiter;
|
||||||
|
|
||||||
|
if (waiter) {
|
||||||
|
this.waiter = null;
|
||||||
|
waiter.resolve({ value: msg, done: false });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.queue.length >= max) return false;
|
||||||
|
this.queue.push(msg);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
next(): Promise<IteratorResult<unknown>> {
|
next(): Promise<IteratorResult<unknown>> {
|
||||||
if (this.queue.length) return Promise.resolve({ value: this.queue.shift(), done: false });
|
if (this.queue.length) return Promise.resolve({ value: this.queue.shift(), done: false });
|
||||||
if (this.failure) return Promise.reject(this.failure.err);
|
if (this.failure) return Promise.reject(this.failure.err);
|
||||||
@@ -120,39 +189,15 @@ class InboundFifo implements AsyncIterator<unknown> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A consumer that stops reading has said it wants no more; queueing for it would only close
|
// 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.
|
// the connection for a bound it no longer cares about. Other consumers keep receiving.
|
||||||
return(): Promise<IteratorResult<unknown>> {
|
return(): Promise<IteratorResult<unknown>> {
|
||||||
this.queue.length = 0;
|
this.queue.length = 0;
|
||||||
|
this.onReturn();
|
||||||
this.settle();
|
this.settle();
|
||||||
return Promise.resolve({ value: undefined, done: true });
|
return Promise.resolve({ value: undefined, done: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Delivers or queues one frame; returns false once the frame has closed the socket. */
|
settle(failure?: { err: unknown }): void {
|
||||||
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;
|
if (this.ended) return;
|
||||||
this.ended = true;
|
this.ended = true;
|
||||||
this.failure = failure ?? null;
|
this.failure = failure ?? null;
|
||||||
|
|||||||
@@ -302,6 +302,44 @@ describe('boundInbound (#107)', () => {
|
|||||||
expect((await it.next()).done).toBe(true);
|
expect((await it.next()).done).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('fans out: two consumers waiting at once both receive the frame', async () => {
|
||||||
|
const { socket, inbound } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket);
|
||||||
|
const a = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const b = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const [nextA, nextB] = [a.next(), b.next()];
|
||||||
|
inbound.push('x');
|
||||||
|
expect(await nextA).toEqual({ value: 'x', done: false });
|
||||||
|
expect(await nextB).toEqual({ value: 'x', done: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fans out: a consumer that returns does not end the next one', async () => {
|
||||||
|
const { socket, inbound } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket);
|
||||||
|
const first = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const firstNext = first.next();
|
||||||
|
inbound.push('a');
|
||||||
|
expect(await firstNext).toEqual({ value: 'a', done: false });
|
||||||
|
await first.return?.();
|
||||||
|
const second = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
const secondNext = second.next();
|
||||||
|
inbound.push('b');
|
||||||
|
expect(await secondNext).toEqual({ value: 'b', done: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fans out: the bound applies to each consumer, so one stalled reader closes 1013', async () => {
|
||||||
|
const { socket, inbound, closes } = fakeSocket();
|
||||||
|
const bounded = boundInbound(socket, { maxWsQueue: 2 });
|
||||||
|
const reader = bounded.inbound[Symbol.asyncIterator]();
|
||||||
|
bounded.inbound[Symbol.asyncIterator](); // subscribed, never reads
|
||||||
|
for (const m of ['a', 'b', 'c']) {
|
||||||
|
const got = reader.next();
|
||||||
|
inbound.push(m);
|
||||||
|
await got;
|
||||||
|
}
|
||||||
|
expect(closes).toEqual([[1013, 'inbound queue full']]);
|
||||||
|
});
|
||||||
|
|
||||||
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);
|
||||||
|
|||||||
Reference in new issue
Block a user