Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6eaa519059 | ||
|
|
06869e5f01 | ||
|
|
c7f4a35008 | ||
|
|
44c783439c |
No files matched your search
@@ -141,6 +141,27 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
before they boot or bind. Migrate by dropping `tls` from `createApp` and configuring TLS on the
|
before they boot or bind. Migrate by dropping `tls` from `createApp` and configuring TLS on the
|
||||||
runtime's server, or terminating it at a proxy. An app without `tls` is unaffected.
|
runtime's server, or terminating it at a proxy. An app without `tls` is unaffected.
|
||||||
|
|
||||||
|
- **`provide()` and `run()` must return an object holding the tokens they provide, and a handler may
|
||||||
|
not return a `Response`.** Both mistakes used to pass silently:
|
||||||
|
- **Providers and steps.** A provider that returned its value bare (`return client` instead of
|
||||||
|
`return { db: client }`) booted. `db` was then `undefined` in every handler, and the client's own
|
||||||
|
properties were spread over the request context. A step that forgot its `return` did the same per
|
||||||
|
request. Now a provider that breaks the contract fails the boot, and a step fails the request. The
|
||||||
|
error names the node and the fix: `provider 'db' returned an object with 'query', but it must return
|
||||||
|
an object holding what it provides: return { db: <value> }`. Plugin nodes added with `scope.add` are
|
||||||
|
held to the same rule for every token in their `provides`. A key whose value is `undefined` still
|
||||||
|
counts (`return { cache: undefined }`).
|
||||||
|
- **Handlers.** A handler that returned a Fetch `Response` was JSON-encoded and went out as `200 {}`,
|
||||||
|
losing its status, headers and body. It now fails the request with a `TypeError` that says what to
|
||||||
|
do instead.
|
||||||
|
|
||||||
|
**Migrate:**
|
||||||
|
- Return `{ <token>: value }` from every `provide()` and `run()`.
|
||||||
|
- Return a plain value from a handler, use `@Transformer` to set the status and headers, or throw an
|
||||||
|
`HttpError` for an error status.
|
||||||
|
|
||||||
|
Code that already followed the documented contract is unaffected.
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- **Every type a public signature uses can now be imported.** These were already in the
|
- **Every type a public signature uses can now be imported.** These were already in the
|
||||||
|
|||||||
+58
-3
@@ -567,6 +567,52 @@ function emptyRegistry(): Registry {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wraps a provider's `provide()` or a step's `run()` so its result is checked against the contract:
|
||||||
|
* an object holding every token the node provides. Without this, `return client` instead of
|
||||||
|
* `return { db: client }` booted fine. `db` was then `undefined`, and the client's own properties
|
||||||
|
* were spread over every request's context. The check stays synchronous for a synchronous node,
|
||||||
|
* so a plain step pays a type test rather than an extra microtask on the hot path.
|
||||||
|
*/
|
||||||
|
function keyedRunner(kind: string, name: string, provides: readonly string[], run: Runner): Runner {
|
||||||
|
const fail = (output: unknown): never => {
|
||||||
|
const example = provides.map((token) => `${token}: <value>`).join(', ');
|
||||||
|
throw new TypeError(
|
||||||
|
`${kind} '${name}' returned ${describeOutput(output)}, but it must return an object holding what it ` +
|
||||||
|
`provides: return { ${example} }`,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// A @Provider or @Step provides one token: test it directly rather than through `every` and its
|
||||||
|
// callback, which measured as a 3-4% drop on a 3-step pipeline under Deno and Bun.
|
||||||
|
const [only] = provides;
|
||||||
|
const check =
|
||||||
|
provides.length === 1
|
||||||
|
? (output: unknown): unknown =>
|
||||||
|
output !== null && typeof output === 'object' && only! in output ? output : fail(output)
|
||||||
|
: (output: unknown): unknown =>
|
||||||
|
output !== null && typeof output === 'object' && provides.every((token) => token in output)
|
||||||
|
? output
|
||||||
|
: fail(output);
|
||||||
|
|
||||||
|
return (ctx) => {
|
||||||
|
const output = run(ctx);
|
||||||
|
return output instanceof Promise ? output.then(check) : check(output);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function describeOutput(output: unknown): string {
|
||||||
|
if (output === null || output === undefined) return String(output);
|
||||||
|
if (typeof output !== 'object') return `a ${typeof output}`;
|
||||||
|
const keys = Object.keys(output);
|
||||||
|
return keys.length
|
||||||
|
? `an object with ${keys
|
||||||
|
.slice(0, 5)
|
||||||
|
.map((k) => `'${k}'`)
|
||||||
|
.join(', ')}`
|
||||||
|
: 'an empty object';
|
||||||
|
}
|
||||||
|
|
||||||
/** Registers a module's `@Provider` classes as app-scope provider nodes. */
|
/** Registers a module's `@Provider` classes as app-scope provider nodes. */
|
||||||
function collectProviders(providers: Ctor[], origin: string, registry: Registry): void {
|
function collectProviders(providers: Ctor[], origin: string, registry: Registry): void {
|
||||||
for (const ProviderClass of providers) {
|
for (const ProviderClass of providers) {
|
||||||
@@ -585,7 +631,10 @@ function collectProviders(providers: Ctor[], origin: string, registry: Registry)
|
|||||||
);
|
);
|
||||||
const instance: any = new ProviderClass();
|
const instance: any = new ProviderClass();
|
||||||
registry.providerInstances.set(meta.provides, instance);
|
registry.providerInstances.set(meta.provides, instance);
|
||||||
registry.setRunner(meta.provides, (ctx) => instance.provide(ctx));
|
registry.setRunner(
|
||||||
|
meta.provides,
|
||||||
|
keyedRunner('provider', meta.provides, [meta.provides], (ctx) => instance.provide(ctx)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -596,7 +645,10 @@ function collectSteps(steps: Ctor[], origin: string, registry: Registry): void {
|
|||||||
registry.stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
|
registry.stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
|
||||||
if (meta.export) registry.exportedSteps.push(meta.provides);
|
if (meta.export) registry.exportedSteps.push(meta.provides);
|
||||||
const instance: any = new StepClass();
|
const instance: any = new StepClass();
|
||||||
registry.setRunner(meta.provides, (ctx) => instance.run(ctx));
|
registry.setRunner(
|
||||||
|
meta.provides,
|
||||||
|
keyedRunner('step', meta.provides, [meta.provides], (ctx) => instance.run(ctx)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -854,7 +906,10 @@ function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registr
|
|||||||
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
|
const node = { name: scopeNode.name, needs: scopeNode.needs, provides: scopeNode.provides, origin: 'plugin' };
|
||||||
if (scopeNode.kind === 'provider') registry.providerNodes.push(node);
|
if (scopeNode.kind === 'provider') registry.providerNodes.push(node);
|
||||||
else registry.stepNodes.push(node);
|
else registry.stepNodes.push(node);
|
||||||
registry.setRunner(scopeNode.name, scopeNode.run);
|
registry.setRunner(
|
||||||
|
scopeNode.name,
|
||||||
|
keyedRunner(`plugin ${scopeNode.kind}`, scopeNode.name, scopeNode.provides, scopeNode.run),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -132,6 +132,16 @@ export async function runPipeline(args: {
|
|||||||
try {
|
try {
|
||||||
context = await runSteps(steps, context, bus, correlation);
|
context = await runSteps(steps, context, bus, correlation);
|
||||||
const result = await handler(context);
|
const result = await handler(context);
|
||||||
|
|
||||||
|
// A handler returns a value and a transformer shapes the response. A Fetch `Response` is not a
|
||||||
|
// value: JSON-encoded, it went out as `200 {}`, with its status, headers and body all lost.
|
||||||
|
if (typeof Response !== 'undefined' && result instanceof Response) {
|
||||||
|
throw new TypeError(
|
||||||
|
'a handler returned a Response object, which green-tea does not send as is. Return a plain value ' +
|
||||||
|
'(sent as JSON), use @Transformer to set the status and headers, or throw an HttpError for an error status',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const streaming = isAsyncIterable(result);
|
const streaming = isAsyncIterable(result);
|
||||||
const contract = TRANSPORT_RETURN[transport];
|
const contract = TRANSPORT_RETURN[transport];
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ test('CARD-17 T1: /__ready__ 503 booting while a slow provider boots, /__live__
|
|||||||
class SlowDb {
|
class SlowDb {
|
||||||
async provide() {
|
async provide() {
|
||||||
await new Promise<void>((resolve) => (finish = resolve));
|
await new Promise<void>((resolve) => (finish = resolve));
|
||||||
return {};
|
return { slowDb: {} };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [SlowDb] })
|
@Module({ mountpoint: '/', controllers: [Ctl], providers: [SlowDb] })
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ Deno.test('CARD-17 T1: /__ready__ 503 booting while a slow provider boots, /__li
|
|||||||
class SlowDb {
|
class SlowDb {
|
||||||
async provide() {
|
async provide() {
|
||||||
await new Promise<void>((resolve) => (finish = resolve));
|
await new Promise<void>((resolve) => (finish = resolve));
|
||||||
return {};
|
return { slowDb: {} };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [SlowDb] })
|
@Module({ mountpoint: '/', controllers: [Ctl], providers: [SlowDb] })
|
||||||
|
|||||||
+2
-2
@@ -51,7 +51,7 @@ describe('CARD-17: health probes through app.fetch', () => {
|
|||||||
class SlowDb {
|
class SlowDb {
|
||||||
async provide() {
|
async provide() {
|
||||||
await new Promise<void>((resolve) => (finish = resolve));
|
await new Promise<void>((resolve) => (finish = resolve));
|
||||||
return {};
|
return { slowDb: {} };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [SlowDb] })
|
@Module({ mountpoint: '/', controllers: [Ctl], providers: [SlowDb] })
|
||||||
@@ -76,7 +76,7 @@ describe('CARD-17: health probes through app.fetch', () => {
|
|||||||
class Watched {
|
class Watched {
|
||||||
provide() {
|
provide() {
|
||||||
started = true;
|
started = true;
|
||||||
return {};
|
return { watched: {} };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Watched] })
|
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Watched] })
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
/**
|
||||||
|
* The contracts a node and a handler are held to, enforced rather than assumed. `provide()` and
|
||||||
|
* `run()` return an object holding every token they provide; a handler returns a value, not a
|
||||||
|
* Fetch `Response`. Before RC.1, breaking either was silent: the token came out `undefined` (with
|
||||||
|
* the returned object's own properties spread over the request context), or the response went
|
||||||
|
* out as `200 {}`.
|
||||||
|
*/
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { createApp, Module, Provider, Route, Get, Step, needs } from '../src/index';
|
||||||
|
import type { Plugin } from '../src/plugin';
|
||||||
|
|
||||||
|
const quiet = { debug() {}, info() {}, warn() {}, error() {} };
|
||||||
|
|
||||||
|
/** Captures the error a request failed with, and answers 500 with its message. */
|
||||||
|
function capture() {
|
||||||
|
const seen: { error?: unknown } = {};
|
||||||
|
const onError = (error: unknown) => {
|
||||||
|
seen.error = error;
|
||||||
|
return { status: 500, headers: {}, body: JSON.stringify({ message: (error as Error).message }) };
|
||||||
|
};
|
||||||
|
return { seen, onError };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('provide() must return an object keyed by its token', () => {
|
||||||
|
it('a provider returning the bare value fails the boot, naming the fix', async () => {
|
||||||
|
@Provider({ provides: 'db' })
|
||||||
|
class Db {
|
||||||
|
provide() {
|
||||||
|
return { query: () => [] }; // the client itself, not { db: client }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Route('/')
|
||||||
|
class C {
|
||||||
|
@Get('/') get(@needs('db') db: unknown) {
|
||||||
|
return { db: db !== undefined };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', providers: [Db], controllers: [C] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
const app = createApp({ modules: [M], logger: quiet });
|
||||||
|
await expect(app.boot()).rejects.toThrow(
|
||||||
|
"provider 'db' returned an object with 'query', but it must return an object holding what it provides: return { db: <value> }",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('an async provider resolving to a non-object fails the boot too', async () => {
|
||||||
|
@Provider({ provides: 'config' })
|
||||||
|
class Config {
|
||||||
|
async provide() {
|
||||||
|
return 'production';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', providers: [Config] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
await expect(createApp({ modules: [M], logger: quiet }).boot()).rejects.toThrow(
|
||||||
|
"provider 'config' returned a string",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a keyed provider whose value is undefined is still keyed, and boots', async () => {
|
||||||
|
@Provider({ provides: 'cache' })
|
||||||
|
class Cache {
|
||||||
|
provide() {
|
||||||
|
return { cache: undefined };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', providers: [Cache] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
await expect(createApp({ modules: [M], logger: quiet }).boot()).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('run() must return an object keyed by its token', () => {
|
||||||
|
it('a step returning nothing fails the request with a message that names the step and the fix', async () => {
|
||||||
|
@Step({ provides: 'user', needs: ['req'] })
|
||||||
|
class Auth {
|
||||||
|
run() {
|
||||||
|
// forgot `return { user }`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Route('/')
|
||||||
|
class C {
|
||||||
|
@Get('/me') me(@needs('user') user: unknown) {
|
||||||
|
return { user };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', steps: [Auth], controllers: [C] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
const { seen, onError } = capture();
|
||||||
|
const res = await createApp({ modules: [M], logger: quiet, onError }).fetch(new Request('http://x/me'));
|
||||||
|
expect(res.status).toBe(500);
|
||||||
|
expect((seen.error as Error).message).toBe(
|
||||||
|
"step 'user' returned undefined, but it must return an object holding what it provides: return { user: <value> }",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a step returning its token keyed works as before', async () => {
|
||||||
|
@Step({ provides: 'user', needs: ['req'] })
|
||||||
|
class Auth {
|
||||||
|
run() {
|
||||||
|
return { user: 'ana' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Route('/')
|
||||||
|
class C {
|
||||||
|
@Get('/me') me(@needs('user') user: string) {
|
||||||
|
return { user };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', steps: [Auth], controllers: [C] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
const res = await createApp({ modules: [M], logger: quiet }).fetch(new Request('http://x/me'));
|
||||||
|
expect(await res.json()).toEqual({ user: 'ana' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a plugin node is held to the same contract for every token it provides', async () => {
|
||||||
|
const plugin: Plugin = {
|
||||||
|
name: 'audit',
|
||||||
|
mount(api) {
|
||||||
|
api.scope.add({ kind: 'step', name: 'audit', needs: [], provides: ['audit', 'auditId'], run: () => ({ audit: true }) });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
@Route('/')
|
||||||
|
class C {
|
||||||
|
@Get('/') get(@needs('auditId') id: unknown) {
|
||||||
|
return { id };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
const { seen, onError } = capture();
|
||||||
|
const res = await createApp({ modules: [M], plugins: [plugin], logger: quiet, onError }).fetch(new Request('http://x/'));
|
||||||
|
expect(res.status).toBe(500);
|
||||||
|
expect((seen.error as Error).message).toContain("plugin step 'audit' returned an object with 'audit'");
|
||||||
|
expect((seen.error as Error).message).toContain('return { audit: <value>, auditId: <value> }');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('a handler returns a value, not a Response', () => {
|
||||||
|
it('a returned Response fails the request instead of going out as 200 {}', async () => {
|
||||||
|
@Route('/')
|
||||||
|
class C {
|
||||||
|
@Get('/') get() {
|
||||||
|
return new Response('created', { status: 201 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [C] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
const { seen, onError } = capture();
|
||||||
|
const res = await createApp({ modules: [M], logger: quiet, onError }).fetch(new Request('http://x/'));
|
||||||
|
expect(res.status).toBe(500);
|
||||||
|
expect((seen.error as Error).message).toContain('a handler returned a Response object');
|
||||||
|
expect((seen.error as Error).message).toContain('@Transformer');
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user