Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b256bc8570 |
No files matched your search
@@ -260,39 +260,6 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
- **A `@Module` without a `mountpoint` names itself at boot** (GitHub #31). The type
|
|
||||||
requires it, but JavaScript or transpile-only code could still omit it, and `createApp` failed
|
|
||||||
with `Cannot read properties of undefined (reading 'replace')` from inside the path helper. It now
|
|
||||||
fails with `<Module> @Module metadata is missing mountpoint`. `mountpoint: ''` still mounts at the
|
|
||||||
root.
|
|
||||||
|
|
||||||
- **The body parser is chosen by the media type** (GitHub #36). It was chosen by a substring of
|
|
||||||
the raw `Content-Type` header, case-sensitively, so `Content-Type: Application/JSON` reached the
|
|
||||||
handler as a string while `text/plain; x=application/json` was parsed as JSON. The same applied
|
|
||||||
to urlencoded and multipart bodies. The parser now compares the media type, the part before any
|
|
||||||
`;`, trimmed and lowercased, exactly. Any `+json` type (RFC 6839) is parsed as JSON too:
|
|
||||||
`application/problem+json` and `application/vnd.api+json`, which used to arrive as text, now
|
|
||||||
arrive parsed, and `application/json-patch+json`, which matched the old substring, still does.
|
|
||||||
|
|
||||||
- **Two concurrent `close()` calls both wait for teardown** (GitHub #45). The teardown registry
|
|
||||||
marked itself drained and returned at once to any second caller, so a `close()` from a signal
|
|
||||||
handler and another from a test hook ran teardown once, but only the first waited for it: the
|
|
||||||
second resolved while a database could still be open. Every caller now gets the promise of the
|
|
||||||
teardown already in flight, and it still runs once.
|
|
||||||
|
|
||||||
- **A graceful close that throws synchronously no longer rejects `close()`** (GitHub #47). On Deno
|
|
||||||
and Bun, `closeWithDeadline` called the graceful path directly, so a throw before it returned a
|
|
||||||
promise escaped as a rejection of `close()`, while the deadline timer stayed armed and later
|
|
||||||
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.
|
|
||||||
|
|
||||||
- **Decorating a subclass no longer changes its base class** (GitHub #44). The argument
|
- **Decorating a subclass no longer changes its base class** (GitHub #44). The argument
|
||||||
decorators (`@query`, `@param`, `@needs`, …) and the route decorators (`@Get`, `@Ws`, …) read
|
decorators (`@query`, `@param`, `@needs`, …) and the route decorators (`@Get`, `@Ws`, …) read
|
||||||
their metadata with `Reflect.getMetadata`, which walks the prototype chain, and then pushed into
|
their metadata with `Reflect.getMetadata`, which walks the prototype chain, and then pushed into
|
||||||
|
|||||||
+1
-3
@@ -789,9 +789,7 @@ function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
|
|||||||
for (const mod of modules) {
|
for (const mod of modules) {
|
||||||
const moduleMeta = getModuleMeta(mod);
|
const moduleMeta = getModuleMeta(mod);
|
||||||
if (!moduleMeta) throw new Error(`${mod.name} is not a @Module`);
|
if (!moduleMeta) throw new Error(`${mod.name} is not a @Module`);
|
||||||
// `typeof`, not falsiness: `mountpoint: ''` mounts at the root, as it always has.
|
if (!moduleMeta.mountpoint) throw new Error(`${mod.name} @Module metadata is missing mountpoint`);
|
||||||
if (typeof moduleMeta.mountpoint !== 'string')
|
|
||||||
throw new Error(`${mod.name} @Module metadata is missing mountpoint`);
|
|
||||||
const origin = `module:${mod.name}`;
|
const origin = `module:${mod.name}`;
|
||||||
collectProviders(moduleMeta.providers ?? [], origin, registry);
|
collectProviders(moduleMeta.providers ?? [], origin, registry);
|
||||||
collectSteps(moduleMeta.steps ?? [], origin, registry);
|
collectSteps(moduleMeta.steps ?? [], origin, registry);
|
||||||
|
|||||||
@@ -14,20 +14,6 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
|
|||||||
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
|
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
|
* 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
|
* that only drains once the event loop yields. `boundInbound` needs it to bound a WebSocket burst
|
||||||
|
|||||||
+3
-17
@@ -49,16 +49,6 @@ export function declaresOverLimit(contentLength: string | null | undefined, limi
|
|||||||
return contentLength != null && /^\d+$/.test(contentLength) && Number(contentLength) > limit;
|
return contentLength != null && /^\d+$/.test(contentLength) && Number(contentLength) > limit;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* The media type of a Content-Type value: the part before any parameters, trimmed and lowercased,
|
|
||||||
* since media types are case-insensitive (RFC 9110 §8.3.1). Matching a substring of the raw header
|
|
||||||
* instead let a parameter choose the parser: `text/plain; x=application/json` was parsed as JSON.
|
|
||||||
*/
|
|
||||||
function mediaType(contentType: string): string {
|
|
||||||
const semi = contentType.indexOf(';');
|
|
||||||
return (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
|
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
|
||||||
type ParseResult = { body: unknown } | { error: string; status?: number };
|
type ParseResult = { body: unknown } | { error: string; status?: number };
|
||||||
|
|
||||||
@@ -72,11 +62,7 @@ export async function parseRequestBody(
|
|||||||
duplicates: 'array' | 'last',
|
duplicates: 'array' | 'last',
|
||||||
maxParts: number,
|
maxParts: number,
|
||||||
): Promise<ParseResult> {
|
): Promise<ParseResult> {
|
||||||
const type = mediaType(contentType);
|
if (buf !== undefined && contentType.includes('application/json')) {
|
||||||
|
|
||||||
// `+json` is the structured-syntax suffix for JSON (RFC 6839): `application/problem+json`,
|
|
||||||
// `application/vnd.api+json` and `application/json-patch+json` are JSON documents too.
|
|
||||||
if (buf !== undefined && (type === 'application/json' || type.endsWith('+json'))) {
|
|
||||||
try {
|
try {
|
||||||
return { body: JSON.parse(buf.toString('utf8')) };
|
return { body: JSON.parse(buf.toString('utf8')) };
|
||||||
} catch {
|
} catch {
|
||||||
@@ -84,11 +70,11 @@ export async function parseRequestBody(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (buf !== undefined && type === 'application/x-www-form-urlencoded') {
|
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
|
||||||
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
|
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (buf !== undefined && type === 'multipart/form-data') {
|
if (buf !== undefined && contentType.includes('multipart/form-data')) {
|
||||||
const boundary = extractBoundary(contentType);
|
const boundary = extractBoundary(contentType);
|
||||||
if (!boundary) return { error: 'Invalid multipart body' };
|
if (!boundary) return { error: 'Invalid multipart body' };
|
||||||
|
|
||||||
|
|||||||
@@ -44,9 +44,7 @@ export function closeWithDeadline(
|
|||||||
};
|
};
|
||||||
|
|
||||||
// A graceful path that rejects still has to end the shutdown: the deadline covers a slow
|
// A graceful path that rejects still has to end the shutdown: the deadline covers a slow
|
||||||
// close, not a broken one, and leaving close() pending forever is the worse failure. Called
|
// close, not a broken one, and leaving close() pending forever is the worse failure.
|
||||||
// inside `then` so a graceful path that throws before returning its promise counts as a
|
void graceful().then(finish, finish);
|
||||||
// rejection too, rather than rejecting close() and leaving the timer to force a closed server.
|
|
||||||
void Promise.resolve().then(graceful).then(finish, finish);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
+3
-8
@@ -5,7 +5,6 @@ import type { Transport } from '../metadata';
|
|||||||
import type { Bus, Correlation } from '../bus';
|
import type { Bus, Correlation } from '../bus';
|
||||||
import type { NeutralOutcome } from './core';
|
import type { NeutralOutcome } from './core';
|
||||||
import { frameSink } from './compression';
|
import { frameSink } from './compression';
|
||||||
import { releaseIterator } from '../channel';
|
|
||||||
|
|
||||||
const PING_MS = 15_000;
|
const PING_MS = 15_000;
|
||||||
|
|
||||||
@@ -64,7 +63,7 @@ export async function pipeStream(
|
|||||||
if (ping) clearInterval(ping);
|
if (ping) clearInterval(ping);
|
||||||
// A client gone mid-stream: the compressor holds zlib memory outside the JS heap until destroyed.
|
// A client gone mid-stream: the compressor holds zlib memory outside the JS heap until destroyed.
|
||||||
sink.destroy();
|
sink.destroy();
|
||||||
releaseIterator(iterator);
|
void Promise.resolve(iterator.return?.()).catch(() => {});
|
||||||
};
|
};
|
||||||
|
|
||||||
res.on('close', stop);
|
res.on('close', stop);
|
||||||
@@ -79,15 +78,11 @@ export async function pipeStream(
|
|||||||
|
|
||||||
streams?.add(closer);
|
streams?.add(closer);
|
||||||
const onClose = once(res, 'close');
|
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 {
|
try {
|
||||||
while (true) {
|
while (true) {
|
||||||
const step = await Promise.race([iterator.next(), gone]);
|
const { value, done } = await iterator.next();
|
||||||
if (!step || step.done) break;
|
if (done) break;
|
||||||
const { value } = step;
|
|
||||||
|
|
||||||
if (!sink.write(encoder.encode(value))) {
|
if (!sink.write(encoder.encode(value))) {
|
||||||
await Promise.race([once(sink.drains, 'drain'), onClose]);
|
await Promise.race([once(sink.drains, 'drain'), onClose]);
|
||||||
|
|||||||
+3
-11
@@ -20,7 +20,6 @@ import { answerProbe } from './health';
|
|||||||
import { currentRoutes } from './router';
|
import { currentRoutes } from './router';
|
||||||
import { compressOutcome, compressWebStream } from './compression';
|
import { compressOutcome, compressWebStream } from './compression';
|
||||||
import type { NeutralOutcome } from './core';
|
import type { NeutralOutcome } from './core';
|
||||||
import { releaseIterator } from '../channel';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
|
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
|
||||||
@@ -43,9 +42,6 @@ export function asReadableStream(
|
|||||||
// `cancel` can land after the body has already ended, and an errored stream still unwinds through
|
// `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.
|
// its own path — so the close is latched rather than emitted from each of the three exits.
|
||||||
let closed = false;
|
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 => {
|
const close = (): void => {
|
||||||
if (closed) return;
|
if (closed) return;
|
||||||
@@ -59,9 +55,7 @@ export function asReadableStream(
|
|||||||
},
|
},
|
||||||
async pull(controller) {
|
async pull(controller) {
|
||||||
try {
|
try {
|
||||||
const step = await Promise.race([iterator.next(), gone]);
|
const { value, done } = await iterator.next();
|
||||||
if (!step) return;
|
|
||||||
const { value, done } = step;
|
|
||||||
|
|
||||||
if (done) {
|
if (done) {
|
||||||
close();
|
close();
|
||||||
@@ -89,11 +83,9 @@ export function asReadableStream(
|
|||||||
controller.close();
|
controller.close();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
// Not awaited: `return()` on a generator still waiting in `next()` would hold the cancel open.
|
async cancel() {
|
||||||
cancel() {
|
|
||||||
close();
|
close();
|
||||||
cancelled(undefined);
|
await iterator.return?.();
|
||||||
releaseIterator(iterator);
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
import { isHttpError } from '../signals';
|
import { isHttpError } from '../signals';
|
||||||
import { CHANNEL_TAP, releaseIterator, type TappableChannel } from '../channel';
|
import { CHANNEL_TAP, type TappableChannel } from '../channel';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import { correlateRequest } from './core';
|
import { correlateRequest } from './core';
|
||||||
import { matchPattern } from './router';
|
import { matchPattern } from './router';
|
||||||
@@ -460,7 +460,7 @@ export async function runWsConnection(
|
|||||||
|
|
||||||
const onAbort = () => {
|
const onAbort = () => {
|
||||||
streams?.delete(closer);
|
streams?.delete(closer);
|
||||||
releaseIterator(iterator);
|
void Promise.resolve(iterator?.return?.()).catch(() => {});
|
||||||
};
|
};
|
||||||
|
|
||||||
socket.abort.addEventListener('abort', onAbort, { once: true });
|
socket.abort.addEventListener('abort', onAbort, { once: true });
|
||||||
|
|||||||
+5
-9
@@ -25,7 +25,7 @@ export type TeardownFn = () => void | Promise<void>;
|
|||||||
*/
|
*/
|
||||||
export class TeardownRegistry {
|
export class TeardownRegistry {
|
||||||
private readonly callbacks: TeardownFn[] = [];
|
private readonly callbacks: TeardownFn[] = [];
|
||||||
private running: Promise<void> | undefined;
|
private drained = false;
|
||||||
|
|
||||||
/** Register `fn` to run on shutdown. Later registrations run first — see {@link run}. */
|
/** Register `fn` to run on shutdown. Later registrations run first — see {@link run}. */
|
||||||
add(fn: TeardownFn): void {
|
add(fn: TeardownFn): void {
|
||||||
@@ -53,16 +53,12 @@ export class TeardownRegistry {
|
|||||||
* was written, and one exists now.
|
* was written, and one exists now.
|
||||||
*
|
*
|
||||||
* Never throws, and never runs twice — `close()` is called twice by more real applications than
|
* Never throws, and never runs twice — `close()` is called twice by more real applications than
|
||||||
* anyone expects, and a second call must not re-close what the first one closed. A second call
|
* anyone expects, and a second call must not re-close what the first one closed.
|
||||||
* made while the first is still running gets the same promise rather than an early return: a
|
|
||||||
* caller that awaits `close()` must not move on with a connection the first call has yet to close.
|
|
||||||
*/
|
*/
|
||||||
run(logger: Logger): Promise<void> {
|
async run(logger: Logger): Promise<void> {
|
||||||
this.running ??= this.drain(logger);
|
if (this.drained) return;
|
||||||
return this.running;
|
this.drained = true;
|
||||||
}
|
|
||||||
|
|
||||||
private async drain(logger: Logger): Promise<void> {
|
|
||||||
for (let index = this.callbacks.length - 1; index >= 0; index--) {
|
for (let index = this.callbacks.length - 1; index >= 0; index--) {
|
||||||
try {
|
try {
|
||||||
await this.callbacks[index]();
|
await this.callbacks[index]();
|
||||||
|
|||||||
@@ -58,22 +58,6 @@ test('runtime module metadata without mountpoint names module and missing field'
|
|||||||
expect(() => createApp({ modules: [BrokenModule] })).toThrow(/BrokenModule.*mountpoint/);
|
expect(() => createApp({ modules: [BrokenModule] })).toThrow(/BrokenModule.*mountpoint/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("an empty mountpoint still mounts at the root, as it did before the missing-mountpoint check", async () => {
|
|
||||||
@Route('/')
|
|
||||||
class RootCtl {
|
|
||||||
@Get('/hi')
|
|
||||||
hi() {
|
|
||||||
return { ok: true };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Module({ mountpoint: '', controllers: [RootCtl] })
|
|
||||||
class RootModule {}
|
|
||||||
|
|
||||||
const res = await createApp({ modules: [RootModule] }).fetch(new Request('http://x/hi'));
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('ready() is a no-op on a non-mesh app, so one protocol works for both', async () => {
|
test('ready() is a no-op on a non-mesh app, so one protocol works for both', async () => {
|
||||||
// The point: code holding an `App` should not have to know whether it is a mesh app.
|
// The point: code holding an `App` should not have to know whether it is a mesh app.
|
||||||
// `await app.ready(); app.graph()` is uniform — here it changes nothing and boots nothing.
|
// `await app.ready(); app.graph()` is uniform — here it changes nothing and boots nothing.
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
|
||||||
import { closeWithDeadline } from '../src/http/shutdown';
|
|
||||||
|
|
||||||
describe('closeWithDeadline', () => {
|
|
||||||
it('treats a graceful close that throws synchronously like one that rejects (GitHub #47)', async () => {
|
|
||||||
const force = vi.fn();
|
|
||||||
const onTimeout = vi.fn();
|
|
||||||
const graceful = (): Promise<void> => {
|
|
||||||
throw new Error('sync boom');
|
|
||||||
};
|
|
||||||
|
|
||||||
await expect(closeWithDeadline(graceful, force, 20, onTimeout)).resolves.toBeUndefined();
|
|
||||||
|
|
||||||
// Past the deadline: a settled close must not leave its timer behind to force anything later.
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
|
||||||
expect(onTimeout).not.toHaveBeenCalled();
|
|
||||||
expect(force).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -380,28 +380,6 @@ describe('request hardening', () => {
|
|||||||
server.close();
|
server.close();
|
||||||
});
|
});
|
||||||
|
|
||||||
// GitHub #36: the parser is chosen by the media type alone, which is case-insensitive. A
|
|
||||||
// substring match on the raw header parsed `text/plain; x=application/json` as JSON.
|
|
||||||
it('chooses the body parser by the media type, not by a substring of the header', async () => {
|
|
||||||
const getUrl = (s: import('http').Server) => `http://127.0.0.1:${(s.address() as any).port}`;
|
|
||||||
const server = createHttpServer([{
|
|
||||||
method: 'POST', pattern: '/echo', transport: 'buffer',
|
|
||||||
handler: async (req) => ({ status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ got: req.body }) }),
|
|
||||||
}]);
|
|
||||||
await new Promise<void>((r) => server.listen(0, r));
|
|
||||||
const post = (contentType: string, body: string) =>
|
|
||||||
fetch(`${getUrl(server)}/echo`, { method: 'POST', headers: { 'content-type': contentType }, body }).then((r) => r.json());
|
|
||||||
|
|
||||||
expect(await post('Text/Plain; x=application/json', '{"a":1}')).toEqual({ got: '{"a":1}' });
|
|
||||||
expect(await post('Application/JSON; charset=utf-8', '{"a":1}')).toEqual({ got: { a: 1 } });
|
|
||||||
expect(await post('application/vnd.api+json', '{"a":1}')).toEqual({ got: { a: 1 } });
|
|
||||||
expect(await post('application/json-patch+json', '[]')).toEqual({ got: [] });
|
|
||||||
expect(await post('application/jsonx', '{"a":1}')).toEqual({ got: '{"a":1}' });
|
|
||||||
expect(await post('APPLICATION/X-WWW-FORM-URLENCODED', 'a=1')).toEqual({ got: { a: '1' } });
|
|
||||||
expect(await post('text/plain; x=application/x-www-form-urlencoded', 'a=1')).toEqual({ got: 'a=1' });
|
|
||||||
server.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('a cors.origins predicate that throws answers the request instead of taking the process down', async () => {
|
it('a cors.origins predicate that throws answers the request instead of taking the process down', async () => {
|
||||||
const warn = vi.fn();
|
const warn = vi.fn();
|
||||||
const server = createHttpServer(
|
const server = createHttpServer(
|
||||||
|
|||||||
@@ -70,23 +70,6 @@ describe('TeardownRegistry', () => {
|
|||||||
expect(runs).toBe(1);
|
expect(runs).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('makes a concurrent second close() wait for the teardown the first one started (GitHub #45)', async () => {
|
|
||||||
const order: string[] = [];
|
|
||||||
const registry = new TeardownRegistry();
|
|
||||||
registry.add(async () => {
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
||||||
order.push('torn down');
|
|
||||||
});
|
|
||||||
|
|
||||||
const logger = silentLogger();
|
|
||||||
await Promise.all([
|
|
||||||
registry.run(logger).then(() => order.push('first returned')),
|
|
||||||
registry.run(logger).then(() => order.push('second returned')),
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(order).toEqual(['torn down', 'first returned', 'second returned']);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('resolves when nothing is registered, and reports an empty size', async () => {
|
it('resolves when nothing is registered, and reports an empty size', async () => {
|
||||||
const registry = new TeardownRegistry();
|
const registry = new TeardownRegistry();
|
||||||
expect(registry.size).toBe(0);
|
expect(registry.size).toBe(0);
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import { describe, expect, it } from 'vitest';
|
|||||||
import { Bus } from '../src/bus';
|
import { Bus } from '../src/bus';
|
||||||
import { createHttpServer } from '../src/http';
|
import { createHttpServer } from '../src/http';
|
||||||
import { buildFetch } from '../src/http/web';
|
import { buildFetch } from '../src/http/web';
|
||||||
import { resolveCompression } from '../src/http/compression';
|
|
||||||
import type { RouteDef } from '../src/http/types';
|
import type { RouteDef } from '../src/http/types';
|
||||||
|
|
||||||
const events = (bus: Bus): string[] => {
|
const events = (bus: Bus): string[] => {
|
||||||
@@ -160,82 +159,3 @@ describe('stream lifecycle events, on every adapter', () => {
|
|||||||
expect(seen).toEqual(['stream:open', 'stream:close']);
|
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']);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -224,29 +224,4 @@ describe('shutdown teardown', () => {
|
|||||||
|
|
||||||
expect(runs).toBe(1);
|
expect(runs).toBe(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('makes two concurrent close() calls both wait for the one teardown (GitHub #45)', async () => {
|
|
||||||
const order: string[] = [];
|
|
||||||
let runs = 0;
|
|
||||||
const plugin: Plugin = {
|
|
||||||
name: 'slow-teardown',
|
|
||||||
mount(api) {
|
|
||||||
api.onShutdown(async () => {
|
|
||||||
runs++;
|
|
||||||
await new Promise((r) => setTimeout(r, 20));
|
|
||||||
order.push('torn down');
|
|
||||||
});
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl] })
|
|
||||||
class M {}
|
|
||||||
const app = createApp({ modules: [M], plugins: [plugin], logger: silentLogger() });
|
|
||||||
await app.listen(0);
|
|
||||||
// A signal handler and a test hook closing at once, say.
|
|
||||||
await Promise.all([app.close().then(() => order.push('first')), app.close().then(() => order.push('second'))]);
|
|
||||||
|
|
||||||
expect(runs).toBe(1);
|
|
||||||
expect(order).toEqual(['torn down', 'first', 'second']);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user