Compare commits
19
Commits
23ab4f4122
...
235e483bfb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
235e483bfb | ||
|
|
e7f08052f4 | ||
|
|
0ba15b7862 | ||
|
|
b005d6a44a | ||
|
|
08d3dd061b | ||
|
|
510e9c4863 | ||
|
|
ebb828a495 | ||
|
|
dae052f400 | ||
|
|
32bd4f6e4a | ||
|
|
1daa4f3cd1 | ||
|
|
1a24d4e1b6 | ||
|
|
51fa7c1a88 | ||
|
|
c7558ccbeb | ||
|
|
212d2fa5c4 | ||
|
|
d90e7ca2b0 | ||
|
|
79925595b5 | ||
|
|
e303cb3a4b | ||
|
|
6fc6e9e3c5 | ||
|
|
7c2454fe43 |
No files matched your search
@@ -115,6 +115,17 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
browsers from reusing a file for a lifetime they guessed from `Last-Modified`. To keep the old
|
browsers from reusing a file for a lifetime they guessed from `Last-Modified`. To keep the old
|
||||||
behaviour, set `static: { cacheControl }` to whatever your proxy expects.
|
behaviour, set `static: { cacheControl }` to whatever your proxy expects.
|
||||||
|
|
||||||
|
- **A node that needs the token it provides fails `createApp`** (GitHub #43). The graph check
|
||||||
|
skipped a dependency whose producer was the node itself, so a step with `needs: ['user']` and
|
||||||
|
`provides: ['user']` booted, and at request time read a value nobody had written. It now fails
|
||||||
|
as the cycle it is, naming the token and the fix: `cycle detected: auth -> auth (it needs 'user',
|
||||||
|
which only it provides). Remove 'user' from its needs, or move the work that produces 'user' into
|
||||||
|
a step it needs.` Since a token has one producer (GitHub #35), no other node can supply it; only a seeded
|
||||||
|
token (`req`, `params`) still satisfies a node's own need, because the node reads the seed.
|
||||||
|
`overrides` do not exempt the node: they replace its runner after the graph is checked. To
|
||||||
|
migrate, remove the token from the node's `needs`, or move the work that produces it into a
|
||||||
|
separate provider or step the node needs.
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- **Health probes: `createApp({ health: true })`** (#115). Off by default. `GET`/`HEAD /__live__`
|
- **Health probes: `createApp({ health: true })`** (#115). Off by default. `GET`/`HEAD /__live__`
|
||||||
@@ -260,6 +271,62 @@ 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
|
||||||
|
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
|
||||||
|
what came back. On a subclass that was the base class's own map or array, so a `@query` on
|
||||||
|
`Child.list` also appeared in `getArgs(Base, 'list')`, and a route declared on `Child` was served
|
||||||
|
by `Base` too. Each decorator now writes a copy onto the class it decorates. The subclass still
|
||||||
|
starts from what it inherits.
|
||||||
|
|
||||||
|
- **An app-scoped binding runs its factory once, however many resolve it at once** (GitHub #46).
|
||||||
|
The internal container cached the value only after the factory settled, so two resolutions that
|
||||||
|
started before then each ran it. It now caches the pending promise. A rejection is still not
|
||||||
|
cached: the next resolution retries, as before, and the callers already waiting share that one
|
||||||
|
rejection. `createApp` was not affected in practice, because it runs each provider once during
|
||||||
|
the memoized boot and registers the finished value, but the container no longer depends on that.
|
||||||
|
|
||||||
|
- **A multipart text field over 1 MiB is no longer cut short** (GitHub #39). busboy applies its
|
||||||
|
own 1 MiB `fieldSize` default unless told otherwise, so with `maxBodyBytes` raised above that a
|
||||||
|
1,100,000-character field reached the handler as its first 1,048,576, and nothing said it had
|
||||||
|
been cut. A field is now bounded by the route's body limit, the same one the whole body is held
|
||||||
|
to. If busboy still reports a field as truncated, the request fails with `413` rather than
|
||||||
|
handing the handler partial data. The Node server and `app.fetch` parse multipart through the
|
||||||
|
same path, so the fix applies to both.
|
||||||
|
|
||||||
- **`listen()` rejects when the port is taken** (#138). A bind failure such as `EADDRINUSE` or
|
- **`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
|
`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
|
never settled, and the error surfaced as an unhandled one. It now rejects with that error. The
|
||||||
|
|||||||
+3
-1
@@ -789,7 +789,9 @@ 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`);
|
||||||
if (!moduleMeta.mountpoint) throw new Error(`${mod.name} @Module metadata is missing mountpoint`);
|
// `typeof`, not falsiness: `mountpoint: ''` mounts at the root, as it always has.
|
||||||
|
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,6 +14,20 @@ 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
|
||||||
|
|||||||
+14
-10
@@ -6,8 +6,8 @@ export type Factory = (ctx: Record<string, unknown>) => unknown | Promise<unknow
|
|||||||
interface Binding {
|
interface Binding {
|
||||||
scope: Scope;
|
scope: Scope;
|
||||||
factory: Factory;
|
factory: Factory;
|
||||||
cached?: unknown;
|
/** The app-scoped value, cached as a promise from the moment the factory starts. */
|
||||||
resolved?: boolean;
|
cached?: Promise<unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */
|
/** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */
|
||||||
@@ -30,14 +30,18 @@ export class Container {
|
|||||||
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
|
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
|
||||||
const binding = this.bindings.get(token);
|
const binding = this.bindings.get(token);
|
||||||
if (!binding) throw new Error(`unknown token: ${token}`);
|
if (!binding) throw new Error(`unknown token: ${token}`);
|
||||||
if (binding.scope === 'app' && binding.resolved) return binding.cached;
|
if (binding.scope === 'request') return binding.factory(ctx);
|
||||||
const value = await binding.factory(ctx);
|
if (binding.cached) return binding.cached;
|
||||||
|
|
||||||
if (binding.scope === 'app') {
|
// The pending promise is cached, not the settled value (GitHub #46): a resolve that starts
|
||||||
binding.cached = value;
|
// while the factory is still running must wait for it, or it runs the factory a second time.
|
||||||
binding.resolved = true;
|
// A rejection is not kept — it clears the cache, so the next resolve retries, as it did when
|
||||||
}
|
// only successes were cached. The async wrapper turns a synchronous throw into that rejection.
|
||||||
|
const pending = (async () => binding.factory(ctx))();
|
||||||
return value;
|
binding.cached = pending;
|
||||||
|
pending.catch(() => {
|
||||||
|
if (binding.cached === pending) binding.cached = undefined;
|
||||||
|
});
|
||||||
|
return pending;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+14
-2
@@ -83,8 +83,20 @@ export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): Gra
|
|||||||
// validate dependencies exist
|
// validate dependencies exist
|
||||||
for (const node of nodes) {
|
for (const node of nodes) {
|
||||||
for (const key of node.needs) {
|
for (const key of node.needs) {
|
||||||
if (!seedKeys.includes(key) && !producedBy.has(key)) {
|
if (seedKeys.includes(key)) continue;
|
||||||
throw new Error(`missing dependency: ${key} needed by ${node.name}${note}`);
|
const producer = producedBy.get(key);
|
||||||
|
|
||||||
|
if (!producer) throw new Error(`missing dependency: ${key} needed by ${node.name}${note}`);
|
||||||
|
|
||||||
|
// A node that needs its own token is a cycle of one (GitHub #43): it would read a value nobody
|
||||||
|
// wrote yet. `producers` already allows one producer per token, so no other node can supply
|
||||||
|
// it; only a seed makes the need real, and the seed case continued above. Same wording as the
|
||||||
|
// cycle check below, so both read as the one error they are.
|
||||||
|
if (producer === node) {
|
||||||
|
throw new Error(
|
||||||
|
`cycle detected: ${node.name} -> ${node.name} (it needs '${key}', which only it provides)${note}. ` +
|
||||||
|
`Remove '${key}' from its needs, or move the work that produces '${key}' into a step it needs.`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-8
@@ -49,6 +49,16 @@ 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 };
|
||||||
|
|
||||||
@@ -61,8 +71,13 @@ export async function parseRequestBody(
|
|||||||
contentType: string,
|
contentType: string,
|
||||||
duplicates: 'array' | 'last',
|
duplicates: 'array' | 'last',
|
||||||
maxParts: number,
|
maxParts: number,
|
||||||
|
maxFieldBytes?: number,
|
||||||
): Promise<ParseResult> {
|
): Promise<ParseResult> {
|
||||||
if (buf !== undefined && contentType.includes('application/json')) {
|
const type = mediaType(contentType);
|
||||||
|
|
||||||
|
// `+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 {
|
||||||
@@ -70,18 +85,19 @@ export async function parseRequestBody(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
|
if (buf !== undefined && type === '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 && contentType.includes('multipart/form-data')) {
|
if (buf !== undefined && type === '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' };
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
|
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates, maxFieldBytes }) };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
|
// HttpError = the busboy peer dep is missing (501) or a field is over the limit (413);
|
||||||
|
// anything else = malformed input (400).
|
||||||
if (isHttpError(error)) return { error: error.message, status: error.status };
|
if (isHttpError(error)) return { error: error.message, status: error.status };
|
||||||
return { error: 'Invalid multipart body' };
|
return { error: 'Invalid multipart body' };
|
||||||
}
|
}
|
||||||
@@ -114,12 +130,13 @@ export function acquireBody(
|
|||||||
// this whole path without a single promise, and an `async` wrapper here would allocate one
|
// this whole path without a single promise, and an `async` wrapper here would allocate one
|
||||||
// regardless. Same reason `handle()` is not async.
|
// regardless. Same reason `handle()` is not async.
|
||||||
return isPromise(acquired)
|
return isPromise(acquired)
|
||||||
? acquired.then((settled) => parseAcquired(settled, matched, opts, req))
|
? acquired.then((settled) => parseAcquired(settled, limit, matched, opts, req))
|
||||||
: parseAcquired(acquired, matched, opts, req);
|
: parseAcquired(acquired, limit, matched, opts, req);
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseAcquired(
|
function parseAcquired(
|
||||||
acquired: { bytes: Buffer | undefined } | BodyFailure,
|
acquired: { bytes: Buffer | undefined } | BodyFailure,
|
||||||
|
limit: number,
|
||||||
matched: MatchedRoute,
|
matched: MatchedRoute,
|
||||||
opts: HttpOptions | undefined,
|
opts: HttpOptions | undefined,
|
||||||
req: ErrorRequest,
|
req: ErrorRequest,
|
||||||
@@ -135,7 +152,9 @@ function parseAcquired(
|
|||||||
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
|
||||||
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
|
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
|
||||||
|
|
||||||
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
|
// A field is bounded by the body limit alone. busboy's own 1 MiB default would otherwise cut any
|
||||||
|
// larger field that `maxBodyBytes` was raised to admit.
|
||||||
|
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts, limit).then((parsed) =>
|
||||||
'error' in parsed
|
'error' in parsed
|
||||||
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
|
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
|
||||||
: { body: parsed.body },
|
: { body: parsed.body },
|
||||||
|
|||||||
@@ -44,7 +44,9 @@ 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.
|
// close, not a broken one, and leaving close() pending forever is the worse failure. Called
|
||||||
void graceful().then(finish, finish);
|
// inside `then` so a graceful path that throws before returning its promise counts as a
|
||||||
|
// rejection too, rather than rejecting close() and leaving the timer to force a closed server.
|
||||||
|
void Promise.resolve().then(graceful).then(finish, finish);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
+8
-3
@@ -5,6 +5,7 @@ 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;
|
||||||
|
|
||||||
@@ -63,7 +64,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();
|
||||||
void Promise.resolve(iterator.return?.()).catch(() => {});
|
releaseIterator(iterator);
|
||||||
};
|
};
|
||||||
|
|
||||||
res.on('close', stop);
|
res.on('close', stop);
|
||||||
@@ -78,11 +79,15 @@ 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 { value, done } = await iterator.next();
|
const step = await Promise.race([iterator.next(), gone]);
|
||||||
if (done) break;
|
if (!step || step.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]);
|
||||||
|
|||||||
+11
-3
@@ -20,6 +20,7 @@ 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
|
||||||
@@ -42,6 +43,9 @@ 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;
|
||||||
@@ -55,7 +59,9 @@ export function asReadableStream(
|
|||||||
},
|
},
|
||||||
async pull(controller) {
|
async pull(controller) {
|
||||||
try {
|
try {
|
||||||
const { value, done } = await iterator.next();
|
const step = await Promise.race([iterator.next(), gone]);
|
||||||
|
if (!step) return;
|
||||||
|
const { value, done } = step;
|
||||||
|
|
||||||
if (done) {
|
if (done) {
|
||||||
close();
|
close();
|
||||||
@@ -83,9 +89,11 @@ export function asReadableStream(
|
|||||||
controller.close();
|
controller.close();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
async cancel() {
|
// Not awaited: `return()` on a generator still waiting in `next()` would hold the cancel open.
|
||||||
|
cancel() {
|
||||||
close();
|
close();
|
||||||
await iterator.return?.();
|
cancelled(undefined);
|
||||||
|
releaseIterator(iterator);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -1,5 +1,5 @@
|
|||||||
import { isHttpError } from '../signals';
|
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 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);
|
||||||
void Promise.resolve(iterator?.return?.()).catch(() => {});
|
releaseIterator(iterator);
|
||||||
};
|
};
|
||||||
|
|
||||||
socket.abort.addEventListener('abort', onAbort, { once: true });
|
socket.abort.addEventListener('abort', onAbort, { once: true });
|
||||||
|
|||||||
+9
-5
@@ -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 drained = false;
|
private running: Promise<void> | undefined;
|
||||||
|
|
||||||
/** 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,12 +53,16 @@ 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.
|
* anyone expects, and a second call must not re-close what the first one closed. A second call
|
||||||
|
* 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.
|
||||||
*/
|
*/
|
||||||
async run(logger: Logger): Promise<void> {
|
run(logger: Logger): Promise<void> {
|
||||||
if (this.drained) return;
|
this.running ??= this.drain(logger);
|
||||||
this.drained = true;
|
return this.running;
|
||||||
|
}
|
||||||
|
|
||||||
|
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]();
|
||||||
|
|||||||
+2
-1
@@ -124,7 +124,8 @@ export type RouteDecorator = (
|
|||||||
function routeDecorator(method: HttpMethod, transport: Transport): RouteDecorator {
|
function routeDecorator(method: HttpMethod, transport: Transport): RouteDecorator {
|
||||||
return (path, opts) => (target, propertyKey) => {
|
return (path, opts) => (target, propertyKey) => {
|
||||||
const ctor = target.constructor;
|
const ctor = target.constructor;
|
||||||
const routes = (Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [];
|
// A copy, as in `record` (params.ts): the inherited array belongs to the base class (GitHub #44).
|
||||||
|
const routes = [...((Reflect.getMetadata(K.routes, ctor) as RouteMeta[]) ?? [])];
|
||||||
routes.push({
|
routes.push({
|
||||||
method,
|
method,
|
||||||
path,
|
path,
|
||||||
|
|||||||
+14
-2
@@ -21,6 +21,8 @@ export interface MultipartBody {
|
|||||||
export interface MultipartOpts {
|
export interface MultipartOpts {
|
||||||
maxParts: number;
|
maxParts: number;
|
||||||
duplicates: 'array' | 'last';
|
duplicates: 'array' | 'last';
|
||||||
|
/** Largest text field accepted, in bytes. Unset leaves busboy's own default of 1 MiB. */
|
||||||
|
maxFieldBytes?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -79,6 +81,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm
|
|||||||
* @param raw The full (already size-capped) request body.
|
* @param raw The full (already size-capped) request body.
|
||||||
* @param boundary The boundary token (see {@link extractBoundary}).
|
* @param boundary The boundary token (see {@link extractBoundary}).
|
||||||
* @throws HttpError 501 when the optional `busboy` peer dependency is not installed.
|
* @throws HttpError 501 when the optional `busboy` peer dependency is not installed.
|
||||||
|
* @throws HttpError 413 when a text field is larger than `maxFieldBytes`.
|
||||||
* @throws Error 'Invalid multipart body' on malformed input or when `maxParts` is exceeded.
|
* @throws Error 'Invalid multipart body' on malformed input or when `maxParts` is exceeded.
|
||||||
*/
|
*/
|
||||||
export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): Promise<MultipartBody> {
|
export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpts): Promise<MultipartBody> {
|
||||||
@@ -93,16 +96,25 @@ export function parseMultipart(raw: Buffer, boundary: string, opts: MultipartOpt
|
|||||||
const fail = () => reject(new Error('Invalid multipart body'));
|
const fail = () => reject(new Error('Invalid multipart body'));
|
||||||
let bb: NodeJS.WritableStream & NodeJS.EventEmitter;
|
let bb: NodeJS.WritableStream & NodeJS.EventEmitter;
|
||||||
|
|
||||||
|
// busboy flags a field as truncated once it *reaches* `fieldSize`, so a field of exactly
|
||||||
|
// `maxFieldBytes` needs one byte of headroom to count as whole.
|
||||||
|
const fieldSize = opts.maxFieldBytes === undefined ? undefined : opts.maxFieldBytes + 1;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
bb = busboy({
|
bb = busboy({
|
||||||
headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
|
headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
|
||||||
limits: { parts: opts.maxParts },
|
limits: { parts: opts.maxParts, fieldSize },
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
return fail();
|
return fail();
|
||||||
}
|
}
|
||||||
|
|
||||||
bb.on('field', (name: string, value: string) => addField(body.fields, name, value, opts.duplicates));
|
bb.on('field', (name: string, value: string, info: { valueTruncated: boolean }) => {
|
||||||
|
// busboy cuts a field at `fieldSize` and only flags it. Partial data is not the field the
|
||||||
|
// client sent, so refuse the body as too large, like any other over-limit body.
|
||||||
|
if (info.valueTruncated) return reject(new HttpError(413, 'Payload Too Large'));
|
||||||
|
addField(body.fields, name, value, opts.duplicates);
|
||||||
|
});
|
||||||
|
|
||||||
bb.on('file', (name: string, stream: Readable, info: { filename?: string; mimeType?: string }) => {
|
bb.on('file', (name: string, stream: Readable, info: { filename?: string; mimeType?: string }) => {
|
||||||
const chunks: Buffer[] = [];
|
const chunks: Buffer[] = [];
|
||||||
|
|||||||
+4
-4
@@ -31,10 +31,10 @@ const ARGS = Symbol('gt:args');
|
|||||||
function record(target: object, methodKey: string | symbol | undefined, spec: ArgSpec): void {
|
function record(target: object, methodKey: string | symbol | undefined, spec: ArgSpec): void {
|
||||||
if (methodKey === undefined) return; // constructor params not supported
|
if (methodKey === undefined) return; // constructor params not supported
|
||||||
const ctor = target.constructor as Ctor;
|
const ctor = target.constructor as Ctor;
|
||||||
const map: Record<string, ArgSpec[]> = Reflect.getMetadata(ARGS, ctor) ?? {};
|
// Copy, never mutate (GitHub #44): `getMetadata` walks the prototype chain, so on a subclass the
|
||||||
const list = map[String(methodKey)] ?? [];
|
// map and list it returns are the base class's, and pushing into them decorated the base too.
|
||||||
list.push(spec);
|
const map: Record<string, ArgSpec[]> = { ...(Reflect.getMetadata(ARGS, ctor) ?? {}) };
|
||||||
map[String(methodKey)] = list;
|
map[String(methodKey)] = [...(map[String(methodKey)] ?? []), spec];
|
||||||
Reflect.defineMetadata(ARGS, map, ctor);
|
Reflect.defineMetadata(ARGS, map, ctor);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -58,6 +58,22 @@ 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.
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -17,6 +17,52 @@ test('resolve is async even for sync factories', async () => {
|
|||||||
await expect(c.resolve('cfg')).resolves.toEqual({ port: 3000 });
|
await expect(c.resolve('cfg')).resolves.toEqual({ port: 3000 });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GitHub #46: only the settled value was cached, so a second resolve that started before the first
|
||||||
|
// factory settled ran the factory again — two pools for one app-scoped token.
|
||||||
|
test('concurrent resolutions of an app-scoped token share one factory call', async () => {
|
||||||
|
const c = new Container();
|
||||||
|
const pending: (() => void)[] = [];
|
||||||
|
const factory = vi.fn(() => new Promise((resolve) => pending.push(() => resolve({ pool: {} }))));
|
||||||
|
c.register('db', 'app', factory);
|
||||||
|
const both = Promise.all([c.resolve('db'), c.resolve('db')]);
|
||||||
|
await Promise.resolve();
|
||||||
|
for (const release of pending) release();
|
||||||
|
const [a, b] = await both;
|
||||||
|
expect(factory).toHaveBeenCalledTimes(1);
|
||||||
|
expect(a).toBe(b);
|
||||||
|
});
|
||||||
|
|
||||||
|
// A rejection is not cached: the next resolve retries, as it did before #46. Callers that were
|
||||||
|
// already waiting on the failing attempt share its rejection rather than starting their own.
|
||||||
|
test('a rejected app-scoped factory is shared while in flight, then retried', async () => {
|
||||||
|
const c = new Container();
|
||||||
|
let calls = 0;
|
||||||
|
const factory = vi.fn(async () => {
|
||||||
|
calls += 1;
|
||||||
|
if (calls === 1) throw new Error('refused');
|
||||||
|
return { pool: calls };
|
||||||
|
});
|
||||||
|
c.register('db', 'app', factory);
|
||||||
|
const results = await Promise.allSettled([c.resolve('db'), c.resolve('db')]);
|
||||||
|
expect(results.map((r) => r.status)).toEqual(['rejected', 'rejected']);
|
||||||
|
expect(factory).toHaveBeenCalledTimes(1);
|
||||||
|
await expect(c.resolve('db')).resolves.toEqual({ pool: 2 });
|
||||||
|
await expect(c.resolve('db')).resolves.toEqual({ pool: 2 });
|
||||||
|
expect(factory).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a factory that throws synchronously rejects, and is retried', async () => {
|
||||||
|
const c = new Container();
|
||||||
|
let calls = 0;
|
||||||
|
c.register('db', 'app', () => {
|
||||||
|
calls += 1;
|
||||||
|
if (calls === 1) throw new Error('sync');
|
||||||
|
return 'ok';
|
||||||
|
});
|
||||||
|
await expect(c.resolve('db')).rejects.toThrow('sync');
|
||||||
|
await expect(c.resolve('db')).resolves.toBe('ok');
|
||||||
|
});
|
||||||
|
|
||||||
test('resolve throws a clear error for an unknown token', async () => {
|
test('resolve throws a clear error for an unknown token', async () => {
|
||||||
const c = new Container();
|
const c = new Container();
|
||||||
await expect(c.resolve('missing')).rejects.toThrow(/unknown token: missing/);
|
await expect(c.resolve('missing')).rejects.toThrow(/unknown token: missing/);
|
||||||
|
|||||||
@@ -52,6 +52,22 @@ describe('one producer per token', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GitHub #43: a node that needs its own token reads a value nobody wrote. With one producer per
|
||||||
|
// token, nothing else can provide it either, so only a seed makes the need real.
|
||||||
|
describe('self-dependency', () => {
|
||||||
|
it('counts as missing when the token is not seeded', () => {
|
||||||
|
expect(() => topoSort([node('auth', ['user'], ['user'])], [])).toThrow(
|
||||||
|
/cycle detected: auth -> auth \(it needs 'user', which only it provides\)/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes when the token is seeded, since the node reads the seed', () => {
|
||||||
|
expect(topoSort([node('normalize', ['params'], ['params'])], ['req', 'params']).map((n) => n.name)).toEqual([
|
||||||
|
'normalize',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const N = (name: string, needs: string[] = []) => ({ name, needs, provides: [name], origin: 'm' });
|
const N = (name: string, needs: string[] = []) => ({ name, needs, provides: [name], origin: 'm' });
|
||||||
|
|
||||||
describe('subgraphFor', () => {
|
describe('subgraphFor', () => {
|
||||||
|
|||||||
@@ -380,6 +380,28 @@ 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,6 +70,23 @@ 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);
|
||||||
|
|||||||
@@ -110,3 +110,18 @@ describe('@Html', () => {
|
|||||||
expect(getHtmlMeta(C, 'm')).toBeUndefined();
|
expect(getHtmlMeta(C, 'm')).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GitHub #44: the route decorator had the same read-the-inherited-array-then-push pattern as
|
||||||
|
// `record` in params.ts, so a route on a subclass was added to the base controller as well.
|
||||||
|
describe('route inheritance', () => {
|
||||||
|
class Base { @Get('/a') a() {} }
|
||||||
|
class Child extends Base { @Get('/b') b() {} }
|
||||||
|
|
||||||
|
it('a route on a subclass leaves the base class unchanged', () => {
|
||||||
|
expect(getRoutes(Base).map((route) => route.handlerName)).toEqual(['a']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('the subclass keeps the inherited routes and adds its own', () => {
|
||||||
|
expect(getRoutes(Child).map((route) => route.handlerName)).toEqual(['a', 'b']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -153,6 +153,22 @@ describe('multipart limits on app.fetch (#105)', () => {
|
|||||||
expect(await r.text()).toContain('Invalid multipart body');
|
expect(await r.text()).toContain('Invalid multipart body');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GitHub #39: busboy's own 1 MiB field limit used to apply whatever maxBodyBytes allowed, and cut
|
||||||
|
// the field without an error. A field is now bounded only by the body limit, on both adapters.
|
||||||
|
it('a text field over 1 MiB reaches the handler whole when maxBodyBytes allows it', async () => {
|
||||||
|
@Route('/') class C { @Post('/u', { maxBodyBytes: 2_000_000 }) u(@body() b: any) { return { length: b.fields.big.length }; } }
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
app = createApp({ modules: [CMod] });
|
||||||
|
const big = () => { const fd = new FormData(); fd.set('big', 'x'.repeat(1_100_000)); return fd; };
|
||||||
|
|
||||||
|
const viaFetch = await app.fetch(new Request('http://x/u', { method: 'POST', body: big() }));
|
||||||
|
expect(await viaFetch.json()).toEqual({ length: 1_100_000 });
|
||||||
|
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const viaNode = await fetch(`http://127.0.0.1:${(server.address() as any).port}/u`, { method: 'POST', body: big() });
|
||||||
|
expect(await viaNode.json()).toEqual({ length: 1_100_000 });
|
||||||
|
});
|
||||||
|
|
||||||
it('T7: the server-level maxParts applies when the route sets none', async () => {
|
it('T7: the server-level maxParts applies when the route sets none', async () => {
|
||||||
@Route('/') class C { @Post('/u') u(@body() b: any) { return b; } }
|
@Route('/') class C { @Post('/u') u(@body() b: any) { return b; } }
|
||||||
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
|
||||||
|
|||||||
@@ -79,6 +79,14 @@ describe('parseMultipart', () => {
|
|||||||
await expect(parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).rejects.toThrow();
|
await expect(parseMultipart(b, B, { maxParts: 2, duplicates: 'last' })).rejects.toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GitHub #39: busboy cuts a field at its size limit and only flags it, so the parser has to refuse
|
||||||
|
// the body rather than hand the handler partial data.
|
||||||
|
it('a field over maxFieldBytes → rejects with 413 instead of truncating', async () => {
|
||||||
|
const b = body([field('a', 'x'.repeat(10))]);
|
||||||
|
await expect(parseMultipart(b, B, { ...opts, maxFieldBytes: 4 })).rejects.toMatchObject({ status: 413 });
|
||||||
|
expect((await parseMultipart(b, B, { ...opts, maxFieldBytes: 10 })).fields.a).toBe('x'.repeat(10));
|
||||||
|
});
|
||||||
|
|
||||||
it('malformed input with no matching boundary → rejects', async () => {
|
it('malformed input with no matching boundary → rejects', async () => {
|
||||||
await expect(parseMultipart(Buffer.from('garbage'), B, opts)).rejects.toThrow();
|
await expect(parseMultipart(Buffer.from('garbage'), B, opts)).rejects.toThrow();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -83,6 +83,17 @@ describe('one producer per token', () => {
|
|||||||
await expect(createApp({ modules: [AppModule], plugins: [one, two] }).boot()).resolves.toBeUndefined();
|
await expect(createApp({ modules: [AppModule], plugins: [one, two] }).boot()).resolves.toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GitHub #43. "Provided by another node" cannot rescue a self-dependency: a second producer of
|
||||||
|
// `user` is the CARD-18 failure above. And an override changes a runner, not the graph, so the
|
||||||
|
// check that rejects the node runs before any override could.
|
||||||
|
it('a node that needs the token it provides fails boot, with or without an override', () => {
|
||||||
|
const loop = adds('loop', { kind: 'step', name: 'loop', needs: ['loop'], provides: ['loop'] });
|
||||||
|
expect(() => createApp({ modules: [AppModule], plugins: [loop] })).toThrow(/cycle detected: loop -> loop/);
|
||||||
|
expect(() => createApp({ modules: [AppModule], plugins: [loop], overrides: { loop: 1 } })).toThrow(
|
||||||
|
/cycle detected: loop -> loop/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it('T5: overrides replace the runner of an existing token, not add a producer', async () => {
|
it('T5: overrides replace the runner of an existing token, not add a producer', async () => {
|
||||||
const app = createApp({ modules: [AppModule], overrides: { user: { id: 1 } } });
|
const app = createApp({ modules: [AppModule], overrides: { user: { id: 1 } } });
|
||||||
const res = await app.fetch(new Request('http://x/u/me'));
|
const res = await app.fetch(new Request('http://x/u/me'));
|
||||||
|
|||||||
@@ -187,3 +187,25 @@ describe('resolveArgs validation', () => {
|
|||||||
}).toThrow();
|
}).toThrow();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// GitHub #44: `record` read the inherited map and pushed into it, so a subclass's decorator landed
|
||||||
|
// on the base class too.
|
||||||
|
describe('inheritance', () => {
|
||||||
|
class Base {
|
||||||
|
list(@query('page') _page: unknown) {}
|
||||||
|
}
|
||||||
|
class Child extends Base {
|
||||||
|
override list(@query('page') _page: unknown, @query('sort') _sort?: unknown) {}
|
||||||
|
other(@param('id') _id: unknown) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
it('decorating a subclass method leaves the base class unchanged', () => {
|
||||||
|
expect(getArgs(Base, 'list')).toEqual([{ index: 0, source: 'query', key: 'page' }]);
|
||||||
|
expect(getArgs(Base, 'other')).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('the subclass keeps what it inherited and adds its own', () => {
|
||||||
|
expect(getArgs(Child, 'list').map((spec) => spec.key)).toEqual(['page', 'page', 'sort']);
|
||||||
|
expect(getArgs(Child, 'other')).toEqual([{ index: 0, source: 'params', key: 'id' }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -13,6 +13,7 @@ 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[] => {
|
||||||
@@ -159,3 +160,82 @@ 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,4 +224,29 @@ 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