diff --git a/CHANGELOG.md b/CHANGELOG.md index b15cdb2..4ba1013 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -260,6 +260,13 @@ npm treats versions as semver and semver forbids leading zeros. ### Fixed +- **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 diff --git a/src/channel.ts b/src/channel.ts index 8cd394c..302270d 100644 --- a/src/channel.ts +++ b/src/channel.ts @@ -14,6 +14,20 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable { 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 | 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 diff --git a/src/http/stream.ts b/src/http/stream.ts index b50eedb..100fda5 100644 --- a/src/http/stream.ts +++ b/src/http/stream.ts @@ -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]); diff --git a/src/http/web.ts b/src/http/web.ts index ea079c9..0f640c7 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -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((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); }, }); } diff --git a/src/http/ws-core.ts b/src/http/ws-core.ts index 1b6eb83..393903d 100644 --- a/src/http/ws-core.ts +++ b/src/http/ws-core.ts @@ -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 }); diff --git a/test/stream-lifecycle-parity.test.ts b/test/stream-lifecycle-parity.test.ts index 3479676..da2c864 100644 --- a/test/stream-lifecycle-parity.test.ts +++ b/test/stream-lifecycle-parity.test.ts @@ -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(() => {}); + + /** Yields once, then waits forever; `return()` does whatever `onReturn` does. */ + const idle = (onReturn: () => Promise>): AsyncIterable => ({ + [Symbol.asyncIterator]: () => { + let sent = false; + return { + next: () => (sent ? hang : ((sent = true), Promise.resolve({ value: { t: 1 }, done: false }))), + return: onReturn, + }; + }, + }); + + const SOURCES: Record AsyncIterable> = { + '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 = (work: Promise, what: string): Promise => + Promise.race([work, new Promise((_, 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((r) => bus.on('stream:close', () => r())); + const streams = new Set<() => void>(); + const server = createHttpServer(route(make), [], bus, undefined, { streams, compression }); + await new Promise((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']); + }); + } +});