fix(http): end an idle stream as soon as the client leaves (GitHub #40)
Both stream adapters waited for the source's pending next() after the client had disconnected. A source idle between events, such as an SSE feed with nothing to send, may never settle that next(), so on Node pipeStream never reached its finally: stream:close did not fire and the closer stayed registered, which graceful shutdown then still treated as a live stream. Through app.fetch, the ReadableStream's cancel awaited return(), which an async generator only runs once its pending next() settles, so cancelling the body did not settle either, with or without compression wrapping it. Each pull is now raced against the disconnect: the response's close event on Node, and the stream's cancel on the fetch path. The source's return() is called without being waited on, through a small releaseIterator helper that also guards a return() that throws synchronously, which on Node escaped from the close listener as an uncaught exception. The WebSocket abort listener already released its iterator this way and now uses the same helper. The new cases in stream-lifecycle-parity drive both adapters, with and without compression, against an async generator, a return() that never settles and a return() that throws. All twelve need the fix except the uncompressed fetch case with a generator, which already passed. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
6 files changed
+122
-8
No files matched your search
@@ -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
@@ -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
@@ -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
@@ -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 });
|
||||
|
||||
Reference in new issue
Block a user