Merge pull request 'fix(http): end an idle stream as soon as the client leaves (GitHub #40)' (#167) from fix/stream-cancel-on-disconnect into develop
CI / dco (push) Has been skipped
CI / build (push) Successful in 29s
CI / runtimes (bun) (push) Successful in 20s
CI / runtimes (deno) (push) Successful in 33s
CI / runtimes (edge) (push) Successful in 19s
Promote → GitHub / push-github (push) Successful in 6s

This commit was merged in pull request #167.
This commit is contained in:
chrnx committed 2026-10-24 23:27:30 +00:00
commit 32bd4f6e4a
6 files changed
+122 -8

No files matched your search

+7
View File
@@ -286,6 +286,13 @@ npm treats versions as semver and semver forbids leading zeros.
forced the server and logged a timeout nobody was waiting for. A synchronous throw is now handled
like a rejection: `close()` resolves, and the timer is cleared.
- **A client leaving an idle stream ends it at once** (GitHub #40). Both stream adapters waited for
the source's pending `next()` after the client had gone, so an SSE feed with nothing to send kept
its connection alive: on Node, `stream:close` never fired and the stream stayed registered for
graceful shutdown; through `app.fetch`, cancelling the body did not settle. The pull is now raced
against the disconnect, and the source's `return()` is called without being waited on, so one
that hangs or throws can no longer hold up or break the cleanup. Compressed streams included.
- **`listen()` rejects when the port is taken** (#138). A bind failure such as `EADDRINUSE` or
`EACCES` arrives as the server's `error` event, which `listen()` did not handle: the promise
never settled, and the error surfaced as an unhandled one. It now rejects with that error. The
+14
View File
@@ -14,6 +14,20 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
}
/**
* Internal: tells a source its consumer has gone, without waiting for it to finish. An async
* generator runs `return()` only once its pending `next()` settles, which for an idle source may be
* never, and a `return()` may also throw or reject. None of that may hold up or break the cleanup
* that calls this (GitHub #40). Not exported from the package.
*/
export function releaseIterator(iterator: AsyncIterator<unknown> | undefined): void {
try {
void Promise.resolve(iterator?.return?.()).catch(() => {});
} catch {
/* a return() that throws synchronously */
}
}
/**
* 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
+8 -3
View File
@@ -5,6 +5,7 @@ import type { Transport } from '../metadata';
import type { Bus, Correlation } from '../bus';
import type { NeutralOutcome } from './core';
import { frameSink } from './compression';
import { releaseIterator } from '../channel';
const PING_MS = 15_000;
@@ -63,7 +64,7 @@ export async function pipeStream(
if (ping) clearInterval(ping);
// A client gone mid-stream: the compressor holds zlib memory outside the JS heap until destroyed.
sink.destroy();
void Promise.resolve(iterator.return?.()).catch(() => {});
releaseIterator(iterator);
};
res.on('close', stop);
@@ -78,11 +79,15 @@ export async function pipeStream(
streams?.add(closer);
const onClose = once(res, 'close');
// `next()` is raced against the disconnect (GitHub #40): an idle source's may never settle, and
// waiting on it kept this loop and its closer alive long after the client had gone.
const gone = onClose.then(() => undefined);
try {
while (true) {
const { value, done } = await iterator.next();
if (done) break;
const step = await Promise.race([iterator.next(), gone]);
if (!step || step.done) break;
const { value } = step;
if (!sink.write(encoder.encode(value))) {
await Promise.race([once(sink.drains, 'drain'), onClose]);
+11 -3
View File
@@ -20,6 +20,7 @@ import { answerProbe } from './health';
import { currentRoutes } from './router';
import { compressOutcome, compressWebStream } from './compression';
import type { NeutralOutcome } from './core';
import { releaseIterator } from '../channel';
/**
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
@@ -42,6 +43,9 @@ export function asReadableStream(
// `cancel` can land after the body has already ended, and an errored stream still unwinds through
// its own path — so the close is latched rather than emitted from each of the three exits.
let closed = false;
// Settles on `cancel`, so a `pull` waiting on an idle source's `next()` stops waiting (GitHub #40).
let cancelled!: (step: undefined) => void;
const gone = new Promise<undefined>((resolve) => (cancelled = resolve));
const close = (): void => {
if (closed) return;
@@ -55,7 +59,9 @@ export function asReadableStream(
},
async pull(controller) {
try {
const { value, done } = await iterator.next();
const step = await Promise.race([iterator.next(), gone]);
if (!step) return;
const { value, done } = step;
if (done) {
close();
@@ -83,9 +89,11 @@ export function asReadableStream(
controller.close();
}
},
async cancel() {
// Not awaited: `return()` on a generator still waiting in `next()` would hold the cancel open.
cancel() {
close();
await iterator.return?.();
cancelled(undefined);
releaseIterator(iterator);
},
});
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { isHttpError } from '../signals';
import { CHANNEL_TAP, type TappableChannel } from '../channel';
import { CHANNEL_TAP, releaseIterator, type TappableChannel } from '../channel';
import type { Bus } from '../bus';
import { correlateRequest } from './core';
import { matchPattern } from './router';
@@ -460,7 +460,7 @@ export async function runWsConnection(
const onAbort = () => {
streams?.delete(closer);
void Promise.resolve(iterator?.return?.()).catch(() => {});
releaseIterator(iterator);
};
socket.abort.addEventListener('abort', onAbort, { once: true });
+80
View File
@@ -13,6 +13,7 @@ import { describe, expect, it } from 'vitest';
import { Bus } from '../src/bus';
import { createHttpServer } from '../src/http';
import { buildFetch } from '../src/http/web';
import { resolveCompression } from '../src/http/compression';
import type { RouteDef } from '../src/http/types';
const events = (bus: Bus): string[] => {
@@ -159,3 +160,82 @@ describe('stream lifecycle events, on every adapter', () => {
expect(seen).toEqual(['stream:open', 'stream:close']);
});
});
// GitHub #40. A source idle between events (an SSE feed waiting on something that may never happen)
// has a `next()` that does not settle. Both adapters waited on it after the client left: Node kept
// `pipeStream` running and its closer registered, so shutdown still saw a live stream, and the
// fetch adapter's `cancel` waited on `return()`, which an async generator only runs once its pending
// `next()` settles. The source's own `return()` must not be able to hold that up either.
describe('a client leaving an idle stream', () => {
const hang = new Promise<never>(() => {});
/** Yields once, then waits forever; `return()` does whatever `onReturn` does. */
const idle = (onReturn: () => Promise<IteratorResult<unknown>>): AsyncIterable<unknown> => ({
[Symbol.asyncIterator]: () => {
let sent = false;
return {
next: () => (sent ? hang : ((sent = true), Promise.resolve({ value: { t: 1 }, done: false }))),
return: onReturn,
};
},
});
const SOURCES: Record<string, () => AsyncIterable<unknown>> = {
'an async generator': async function* () {
yield { t: 1 };
await hang;
},
'a return() that never settles': () => idle(() => hang),
'a return() that throws': () =>
idle(() => {
throw new Error('return failed');
}),
};
/** Fails with a message instead of the test timing out. */
const within = <T>(work: Promise<T>, what: string): Promise<T> =>
Promise.race([work, new Promise<never>((_, reject) => setTimeout(() => reject(new Error(`${what}: hung`)), 1000))]);
for (const [source, make] of Object.entries(SOURCES))
for (const compression of [undefined, resolveCompression(true)]) {
const label = `${source}${compression ? ', compressed' : ''}`;
it(`node: ${label} — finishes and unregisters on disconnect`, async () => {
const bus = new Bus();
const closed = new Promise<void>((r) => bus.on('stream:close', () => r()));
const streams = new Set<() => void>();
const server = createHttpServer(route(make), [], bus, undefined, { streams, compression });
await new Promise<void>((r) => server.listen(0, r));
const { port } = server.address() as { port: number };
const ac = new AbortController();
try {
const res = await fetch(`http://127.0.0.1:${port}/feed`, {
signal: ac.signal,
headers: { 'accept-encoding': 'gzip' },
});
await res.body!.getReader().read();
ac.abort();
await within(closed, 'stream:close');
expect(streams.size).toBe(0); // nothing left for a graceful shutdown to wait on
} finally {
server.closeAllConnections();
server.close();
}
});
it(`fetch: ${label} — cancel settles at once`, async () => {
const bus = new Bus();
const seen = events(bus);
const res = await buildFetch(route(make), { bus, compression })(
new Request('http://x/feed', { headers: { 'accept-encoding': 'gzip' } }),
);
const reader = res.body!.getReader();
await reader.read();
await within(reader.cancel(), 'cancel()');
expect(seen).toEqual(['stream:open', 'stream:close']);
});
}
});