Compare commits
9
Commits
e6f6f90cc2
...
212d2fa5c4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
212d2fa5c4 | ||
|
|
d90e7ca2b0 | ||
|
|
79925595b5 | ||
|
|
e303cb3a4b | ||
|
|
6fc6e9e3c5 | ||
|
|
7c2454fe43 | ||
|
|
9f6f916063 | ||
|
|
dc88fdef10 | ||
|
|
aaef6cf5b7 |
No files matched your search
@@ -260,6 +260,26 @@ 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.
|
||||||
|
|
||||||
- **`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
|
||||||
|
|||||||
@@ -789,6 +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`);
|
||||||
|
// `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);
|
||||||
|
|||||||
+17
-3
@@ -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 };
|
||||||
|
|
||||||
@@ -62,7 +72,11 @@ export async function parseRequestBody(
|
|||||||
duplicates: 'array' | 'last',
|
duplicates: 'array' | 'last',
|
||||||
maxParts: number,
|
maxParts: 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,11 +84,11 @@ 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' };
|
||||||
|
|
||||||
|
|||||||
+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]();
|
||||||
|
|||||||
+35
-1
@@ -1,6 +1,6 @@
|
|||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import { describe, expect, it, test, vi } from 'vitest';
|
import { describe, expect, it, test, vi } from 'vitest';
|
||||||
import { Provider, Step, Route, Get, Post, Module, Transformer } from '../src/metadata';
|
import { Provider, Step, Route, Get, Post, Module, Transformer, getModuleMeta } from '../src/metadata';
|
||||||
import { JsonTransformer } from '../src/transformers';
|
import { JsonTransformer } from '../src/transformers';
|
||||||
import { Unauthorized } from '../src/signals';
|
import { Unauthorized } from '../src/signals';
|
||||||
import { createApp } from '../src/app';
|
import { createApp } from '../src/app';
|
||||||
@@ -40,6 +40,40 @@ test('inspect lists the ordered chain with origins', () => {
|
|||||||
expect(lines.map((l) => `${l.kind}:${l.name}`)).toEqual(['provider:db', 'step:user', 'handler:getUser']);
|
expect(lines.map((l) => `${l.kind}:${l.name}`)).toEqual(['provider:db', 'step:user', 'handler:getUser']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('runtime module metadata without mountpoint names module and missing field', () => {
|
||||||
|
@Route('/broken')
|
||||||
|
class BrokenCtl {
|
||||||
|
@Get('/')
|
||||||
|
get() {
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/broken', controllers: [BrokenCtl] })
|
||||||
|
class BrokenModule {}
|
||||||
|
const metadata = getModuleMeta(BrokenModule);
|
||||||
|
if (!metadata) throw new Error('test setup failed');
|
||||||
|
Object.defineProperty(metadata, 'mountpoint', { value: undefined });
|
||||||
|
|
||||||
|
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.
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|||||||
@@ -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