22 Commits
Author SHA1 Message Date
chrnx 0adab69466 docs(changelog): record the tier-2 work in Unreleased
CI / dco (pull_request) Successful in 5s
CI / build (pull_request) Successful in 28s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
The event stream's contract, the read-only `events` token, the reserved framework names,
the unmatched-route label, the budget bookkeeping, and the `onError` crash.

Grouped by what a reader is looking for rather than one bullet per commit: the three
observability issues describe one contract and read better as one entry plus the two
fields it needed.

The reserved names get their own paragraph saying plainly that they **can fail an app
that boots today**, because a changelog that buries a breaking change under a feature
heading is how someone finds it from a stack trace instead.

Heading still `[Unreleased]`. The version and the date belong to the cut.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:08:47 -05:00
chrnx 1c4f3fb8cb perf(http): skip the request-budget bookkeeping when no budget is set
Every request registered a `close` listener and set an acquire flag, including in the
apps — most of them — that never set `maxConcurrentRequests`. `acquire()` returns `true`
unconditionally when the limit is unset and `release()` early-returns for the same reason,
so both the closure and the EventEmitter registration were pure overhead: a per-request
cost, on the hot path, for a feature that is off.

The gate exposes `limited` rather than each adapter re-deriving it from `opts`, because the
gate is what knows. `acquire()` cannot say it — its `true` means "admitted" and "not
counting" alike, which is exactly why a caller reading only the result pays either way.

With a budget configured nothing changes: the listener is what releases a slot when a
client disconnects mid-handler, and it comes back. The guard is about the unset case, not
about dropping the feature, and the test asserts both halves so a fix for one cannot
quietly become a regression in the other.

Verified non-vacuous: reverting `src/` fails the assertion with the listener it counts.

Closes #74.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 11:01:52 -05:00
chrnx 1e76921d49 feat(di): a read-only events token, and framework names nobody can take
Three things that turned out to be one decision.

## `@needs('events')`

`app.bus` is public and `Bus` is an exported type, but the bus was not a graph token, so
`@needs('bus')` failed at boot. There is a good reason for the difference — putting the
`Bus` in the graph hands `emit` to every node and turns a one-way observation channel into
something anything can forge events on — and it was written down nowhere, inferable only
by reading `provideBuiltins` and noticing what is absent.

The read-only half is a token now: `events`, bound to `{ on }`, the same narrowing plugins
already get. `@needs('events')` works the way `@needs('logger')` does, which is the
symmetry a reader expects, and `emit` still belongs to nobody.

A plugin remains the right home for observation and the docs say so, because it gets
`on` and `onShutdown` *together*. The token gives the subscribe half alone: a `@Provider`
that subscribes should release in `dispose()` — `on()` returns its own unsubscribe — and a
`@Step` should not subscribe at all, since it runs per request and would add a listener
each time.

## The boot error teaches it

Documenting it prevents the mistake for a reader; it does nothing for the person typing
`@needs('bus')`, which is who the issue was about. That need now fails with what it should
have used and why, rather than the generic "nothing provides it" plus a nearest-match that
has nothing near enough to suggest.

## Framework names are reserved

**Behaviour change.** Builtins were registered with `if (!runners.has(name))`, so a
provider called `logger` silently replaced the framework's own and every `@needs('logger')`
in the app got something that was not the logger core writes to — a divergence you
discover from a log line that never appeared. `logger`, `rooms`, `events` and `bus` are
reserved now, enforced in `setRunner`, which is the single point modules, plugins and mesh
exports all register through. Taking one is a boot error naming it.

`bus` is reserved without being provided, so `@needs('bus')` cannot resolve to whatever a
user happened to call `bus` and be wrong in silence.

This replaces a test that asserted the old shadowing as a feature.

Closes #67.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:57:47 -05:00
chrnx c00f714aa8 feat(bus): give an unmatched request a bounded route to be labelled by
`route:unmatched` was the one terminal request event carrying no `route`, so the only
subject a consumer could reach was `name` — and on that event `name` is the concrete,
caller-controlled path.

The cardinality doctrine is already written into the codebase and it is right: a metrics
consumer that labels a counter with a concrete path gets one label per distinct URL, and
unbounded label cardinality takes down the metrics backend rather than the application.
That reasoning applies hardest to exactly this event. A matched route's path is bounded by
the route table; an unmatched one is bounded by nothing at all, and a scanner walking
/aaa, /aab, /aac is a memory leak with a metrics backend attached.

The framework did not create the trap knowingly. It just left the one field that avoids
it empty, precisely where it mattered most.

`route:unmatched` and the `request:end` that follows it now both carry
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE` so nobody has to hardcode the
string to compare against it. A single series for every path that was never a route,
rather than a fallback each consumer invents and some get wrong. It cannot collide with a
pattern a user can declare, since those start with `/`.

Written down alongside it, because a field alone does not teach the rule: `name` is
caller-controlled and must not be a metric label — true of `request:start` too, which is
not terminal and so was never the one anyone counted. And `route:unmatched` is not a
synonym for failure: a static file served by `createApp({ static })` matched no route
either and answers 200, so the status comes from `request:end`, like everything else.

Closes #65.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:37:41 -05:00
chrnx 5294e62a5a fix(errors): an onError that throws degrades to the built-in renderer
`createApp({ onError })` is the advertised way to render errors, it runs on the request
path, and it ran with no boundary around it. A renderer that threw did not produce a 500
— it took the process with it, exit code 1.

This is #72 in a different callback, and easier to reach: not a cross-origin request, but
*any* request that produces an error. The stack from the reproduction goes through
`unmatchedOutcome`, so the renderer produces the 404 too — an app with a custom renderer
and no matching route was one request away from exiting.

It is also the worst-timed crash there was. The renderer only runs once something has
already gone wrong, so the failure mode read: an error occurs, the code written to report
it fails, and instead of a degraded report the server ends.

All six call sites funnel through `renderError`, so the guard goes there once. A renderer
that throws falls back to `errorToResponse` — the built-in rendering, which is exactly
what the option overrides and therefore the honest thing to fall back to. The original
error still gets its response; that is the whole point. The renderer's own failure is
logged separately and names both errors, because they are different errors and a reader
chasing the wrong one loses an afternoon.

Verified against the built `dist/` with the issue's own reproduction: `404`, process
alive, one error line naming the renderer.

`viewEngine` was checked in the same pass, since it is the other user callback on a render
path and its having a boundary was not something to assume. It has one — the pipeline's
catch covers it, so a broken engine is a 500. Asserted now rather than left to inference.

Amends the `request:failed` test added a commit ago, which asserted the crashing behaviour
as its baseline: a throwing renderer now yields the fallback's status rather than none.
The `finally` that carries the emission stays, demoted from first line of defence to
second — a failure whose reporting is what broke is the worst one to lose.

Closes #80.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:35:03 -05:00
chrnx 3930804fb3 feat(bus): give request:failed a status, and write down the three-event overlap
One request that throws emits three events, and nothing said which of them to count. The
obvious first implementation counts the failure twice — once from `request:failed` and
once from the `request:end` that follows it, under whatever status it invents for the one
that had none. `route:unmatched` overlaps the same way, so a 404 is two events and one
outcome. Both mistakes are silent: the metrics simply lie.

The division of labour is now stated on `EventPayload`, where a consumer reads it:
`request:end` is terminal, universal and carries the status the client received, so it is
the request counter; `request:failed` means *handler code threw*, which no status can
express on its own since a rendered 422 is also a throw; `route:unmatched` means no route
ran. The last two are additional, not alternatives.

`request:failed` also carries a `status` now, so an error counter can break down by
status without joining back through `requestId` for something the emitter already had.

Getting it required moving the emission after the render rather than before, and the two
reasons are worth keeping: `onError` may turn any throw into any status, so deriving one
from the error would be a guess a custom renderer makes wrong — and the emission sits in
`finally`, so a renderer that *throws* cannot swallow the event. That case is the only one
where the event has no status, and the field's doc says so rather than leaving a reader to
find out.

Closes #64.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:26:00 -05:00
chrnx 5d8363d225 feat(bus): guarantee that every request:end has a request:start
`request:start` had one emitter and `request:end` had three, so the pairing every
consumer would reasonably assume held by accident rather than by promise. The
`maxConcurrentRequests` merge added the first terminal path that breaks it: a shed
request emits `request:end` and nothing before it, because it never reaches `handle()`.

Both shed paths now emit the pair, through one shared `emitShedPair` rather than two
copies — the guarantee lives in one place, and the two adapters already had a duplicate
of this block between them.

## Why the pair rather than documenting `request:end` as standalone

Both were defensible and the alternative was seriously considered. It loses on one
concrete case: the obvious in-flight gauge.

    bus.on('request:start', () => inFlight++);
    bus.on('request:end',   () => inFlight--);

Without the guarantee that drifts negative the moment a server sheds — under load, which
is exactly when an operator is reading it, and it fails by producing a plausible wrong
number rather than an error. Documenting "do not do that" asks every consumer to read
the warning; guaranteeing the pair makes the obvious code correct.

Emitting a `start` for a shed request is not a fabrication, which was the objection worth
answering: the request *did* arrive. The gate refused it before the router, and
`request:start` says a request arrived, not that it routed.

The cost of the guarantee is that it binds every future emitter, and that is real. It is
paid down by `test/lifecycle-pairing.test.ts`, which enumerates every response shape —
200, 404, 500, 413, 204 preflight, and 503 on both adapters — and asserts the pair and
the shared `requestId`. The constraint is now something CI enforces rather than something
a contributor has to remember. Verified non-vacuous: dropping the `request:start`
emission fails the two shed rows and nothing else.

Also writes down, next to `LifecycleEvent` where a consumer reads it, the half of this
that is not new: `request:end` is terminal and universal and is the one to count;
`request:failed` and `route:unmatched` describe the same request and are additional.

Closes #73.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 10:21:34 -05:00
chrnx 0f2f62d8c1 Merge pull request 'docs(changelog): record the unreleased work, without cutting a version' (#79) from chore/changelog-unreleased into develop
CI / runtimes (edge) (push) Successful in 11s
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 20s
2026-09-01 14:59:27 +00:00
chrnx 4c9e606cfb docs(changelog): record the unreleased work, without cutting a version
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 20s
Everything on `develop` since `26.8.0-beta.1` that a user would notice: the request
budget and the connection-drop warning from the contribution merge, `handleSignals`,
the extension-point type exports, the single header resolution, and the two crashes
(the CORS predicate, and the JSR package's missing `require`).

The heading stays `[Unreleased]`. The version bump and the dated section belong to the
cut, not to the work.

Left out on purpose: the two `ci(release)` commits. They change how the workflow spends
a dist-tag and whether it publishes release notes — real, and invisible to anyone
reading this file to find out what changed in the package they installed.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:47:57 -05:00
chrnx f08956bea8 Merge pull request 'Tier 1 for 26.9.0-beta.1: the four that block the cut' (#78) from beta/tier-1 into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 13s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 14s
2026-09-01 14:44:41 +00:00
chrnx b8b3548f15 perf(cors): resolve the request's headers once, not two or three times
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
`security` and `cors` were computed twice for every request and three times for a
preflight: once in the adapter, to seed the headers a response written *above*
`handle()` still has to carry — a shed 503, a 413 from the body reader — and again in
`dispatch`, plus a third time inside `corsPreflightHeaders`.

Nothing was incorrect, because the predicate is expected to be pure with respect to one
request. The cost is that `cors.origins` is a predicate precisely so it can be a lookup:
an allowlist in Redis, a tenant query. The framework charged the caller's latency budget
and their backend two to three times for an answer whose inputs did not change in
between, and made a predicate with a counter in it count double.

`handle()` now takes the headers the adapter already computed and hands them down, with
`computeInjected` kept as the fallback for a caller that has none.
`corsPreflightHeaders` extends that result instead of re-deriving it. The Node adapter
was carrying its own copy of `computeInjected`, inlined; it uses the real one now, which
is what removes the duplicate rather than papering over it.

Measured against the built `dist/`, same script that produced the numbers in the issue:

    GET with Origin      2x -> 1x
    OPTIONS preflight    3x -> 1x
    buildFetch, Origin   2x -> 1x
    GET without Origin   0x -> 0x   (never reached the predicate; unchanged)

The risk here is not the call count, it is that `injected` carries the security headers
onto every response shape — so the tests that matter are the existing ones across
`transport-security`, `http-headers`, `fetch`, `parity` and `web-stream`, all green.
The two new tests assert the count directly, on both adapters, which is the assertion
that keeps it from drifting back.

Closes #77.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:27:32 -05:00
chrnx 855e044d2a fix(types): export the extension-point types, not just the extension points
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 11s
CI / runtimes (deno) (pull_request) Successful in 20s
`Transformer` was exported and `TransformerFn` was not, so a custom transformer could
be attached but not typed. The workaround is to borrow the type off a value —
`const text: typeof JsonTransformer = ...` — which works and reads like a trick,
because it is one. `ErrorRenderer` and `StreamEncoder`, the two neighbouring extension
points, were both already exported; this one was an oversight rather than a decision.

Checking the rest of the barrel for the same shape turned up four more. A plugin split
into named functions rather than one inline arrow cannot annotate what it receives:
`Plugin` types the arrow, and `PluginApi`, `ScopeApi` and `ScopeNode` — the chain
reached through `api.scope.add`, which is how a plugin contributes to the graph — were
all unreachable. So was `Hooks`, which makes `createApp({ hooks })` typeable only
inline, and `TeardownFn`, the shape every one of those three doors takes.

Types only. Nothing at runtime moves, and no existing export changes.

Covered by a type test that fails to compile if any of them leaves the barrel again,
including the two that were already there — the failure mode this fixes is a barrel
edit nobody notices until a user writes the annotation.

Closes #66.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:15:35 -05:00
chrnx e5d5fb801a feat(shutdown): opt into SIGINT/SIGTERM with createApp({ handleSignals })
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 30s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
The README promised shutdown was *"an extension point, not a SIGTERM handler you
write"*. Half of it was true: `dispose()`, `onShutdown` and `hooks` all deliver the
*content* of teardown, but nothing called `close()`, so every application still wrote
the handler — and wrote it three times, because the spelling is per runtime. Forget it
and the container is SIGKILLed after its grace period, every `dispose()` the registry
so carefully ordered never runs, and nothing reports it.

`createApp({ handleSignals: true })` registers SIGINT/SIGTERM to close and exit.

Off by default, and that is the design rather than caution: a library that installs
process-wide handlers behind your back is worse than one that installs none, because
when the process exits is the application's call. Both halves are now supported and
documented — keep the handler, or hand it over. What is not optional either way is
that *something* calls `close()`, and the README now says so instead of implying the
framework already had it covered.

Declared once on `createApp`, wired per runtime by whichever boot call runs:
`listen()`, `serveDeno()` and `serveBun()` each pass the closer that drains *their*
server to `app.handleSignals`, which returns a close that also unregisters. On Deno
that unregistering is load-bearing rather than tidy — a live `Deno.addSignalListener`
holds the process open, so an app that closed itself would otherwise hang.

Unregistering first also means a *second* signal falls through to the platform default
and ends the process at once. That is deliberate: Ctrl-C twice is the way out of a
teardown that is stuck, and swallowing it for the length of a 10s budget would read as
a hang. An orchestrator sends SIGTERM once and then SIGKILL, so it never gets there.

Tested against real processes, because a handler whose job is to exit its own process
cannot be fired by hand in the runner: Node covers SIGTERM, SIGINT, the double-signal
escape hatch and the default-off case; Deno covers `Deno.addSignalListener`/`Deno.exit`,
which is the API that actually differs. Bun shares Node's `process` path.

Closes #70.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:09:56 -05:00
chrnx 4896ee86d2 fix(jsr): resolve require from source, not from tsup's banner
CI / dco (pull_request) Successful in 6s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
JSR publishes `src/` and runs no bundler, so the `createRequire` banner tsup gives
the ESM build (tsup.config.ts) never exists there. Every lazy `require(...)` in the
source had nothing to resolve, and one of them was unguarded: `@Html('file')` and
template mode died at boot on Deno with `ReferenceError: require is not defined`.

The two guarded sites were worse than the crash, because they answered confidently
and wrongly. `static` reported *"needs a filesystem and is unavailable on this
runtime (edge)"* while running on Deno, which has one; multipart reported busboy as
not installed while it sat in node_modules. Both blamed the runtime for a packaging
problem, and both named a runtime the reader was not on.

Route all ten call sites through one `nodeRequire`, which prefers the ambient
`require` — so the CJS build and the banner-carrying ESM build behave exactly as
before — and otherwise rebuilds one from `process.getBuiltinModule('node:module')`.
Node 22.3+, Deno and Bun all expose that synchronously, which is the requirement:
every caller sits on a sync path a dynamic `import()` could not serve. It resolves
from `process.cwd()`, since a peer dependency like busboy belongs to the application,
not to a module served over https from a registry.

Where neither exists — workerd, where esbuild rewrites the call into its own throwing
stub — the behaviour is unchanged: the guarded sites still catch, and their "edge has
no filesystem" story is finally the true one.

Covered by a Deno suite that imports `src/` exactly as JSR serves it. The other Deno
tests already did that; none of them touched a path that loads a Node builtin lazily,
which is how a package that died at boot kept a green suite.

Closes #69.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 08:50:42 -05:00
chrnx bb0b01cf26 fix(cors): deny the origin when the origins predicate throws
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 29s
`CorsOptions.origins` accepts a predicate, and it runs on the request path above the
region where errors convert to a response. A predicate that threw became a rejected
promise nobody awaited, and Node's default for that is to exit — so one cross-origin
GET took the process down, with `onError` never reaching it.

The trigger is a browser: `originAllowed` only runs when an `Origin` header is present,
so the crash is reachable by any cross-origin client and by no test that forgets the
header, which is how it survived a green suite.

Guard the call at `originAllowed`, the single point all four call sites funnel through
(the Node handler, `computeInjected` on both adapters, and the preflight path). A
predicate that throws denies the origin: a lookup that failed has not said yes, and a
broken allowlist must never widen into an open one. The failure is reported through the
app logger rather than swallowed — `HttpOptions` already carries one.

The published behaviour changes for a throwing predicate only. Every other origin shape
is untouched, and the security headers still land on the response.

Amends one test from the `maxConcurrentRequests` contribution, which asserted the old
crash as its baseline while proving the gate does not leak a slot. It still proves that,
against a transient failure that is now answered rather than fatal.

Closes #72.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 08:39:11 -05:00
chrnx d93037e2a0 Merge pull request 'Merge contrib: cap concurrent requests, from an outside contributor' (#75) from contrib into develop
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 14s
CI / dco (push) Has been skipped
CI / build (push) Successful in 30s
2026-09-01 13:29:40 +00:00
hgshreyas ff94e55496 feat: cap concurrent requests across runtimes
CI / dco (push) Has been skipped
CI / build (push) Successful in 28s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (bun) (push) Successful in 59s
CI / runtimes (edge) (push) Successful in 11s
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / build (pull_request) Successful in 29s
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-31 08:53:14 -05:00
hgshreyas 82e1678dea fix: warn when connection limit drops a socket
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
2026-08-30 12:55:20 -05:00
chrnx 4b04421ddd Merge pull request 'ci(release): publish the release notes, not just the tag' (#62) from ci/github-releases into develop
CI / dco (pull_request) Successful in 3s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 25s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 19s
Promote → GitHub / push-github (push) Failing after 6s
CI / runtimes (bun) (push) Successful in 15s
CI / dco (push) Has been skipped
CI / build (push) Successful in 25s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 13s
2026-08-19 19:32:14 +00:00
chrnx 0fad12688d ci(release): publish the release notes, not just the tag
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 18s
The repository had two tags and no releases, so the only way to find out what
a version changed was to open CHANGELOG.md and scroll to the right heading.
The release page is where people who do not read changelogs look, and a
repository with tags and no releases reads as abandoned.

Notes come from CHANGELOG.md rather than from the commit range. The section
was written for humans and already exists by the time a tag is cut; generated
notes would restate merge subjects nobody chose. `scripts/changelog-section.mjs`
extracts one version's section and makes its relative links absolute against
the tag — a release body resolves them against the release page, not the
repository, so `./BENCHMARKS.md` would have 404'd.

That script is a parser writing text that cannot be corrected quietly once it
is published, so its boundaries are pinned by a test rather than checked by
eye at release time. Both of the bugs it caught while being written are in
there: a section swallowing the `[label]: url` block that follows the oldest
version, and a relative link surviving into a body.

The step is idempotent like the publishes before it, so a re-run finishes what
is left instead of stopping here, and `--verify-tag` keeps it from inventing a
tag — it attaches to the one that triggered the run and cannot move it. A
prerelease is marked as one, which is what keeps the "Latest" badge off a beta.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:31:05 -05:00
chrnx ead71dc1b1 Merge pull request 'ci(release): spend the publish's one dist-tag on latest while there is no stable' (#60) from ci/publish-under-latest into develop
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 17s
CI / runtimes (edge) (pull_request) Successful in 11s
Promote → GitHub / push-github (push) Failing after 6s
CI / dco (push) Has been skipped
CI / build (push) Successful in 24s
CI / runtimes (bun) (push) Successful in 14s
CI / runtimes (deno) (push) Successful in 18s
CI / runtimes (edge) (push) Successful in 12s
2026-08-19 19:18:20 +00:00
chrnx 19fcc18899 ci(release): spend the publish's one dist-tag on latest while there is no stable
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 24s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 12s
`npm dist-tag` cannot use Trusted Publishing. The OIDC exchange lives inside
`publish.js` and nowhere else, so the token it returns is publish-scoped: the
step added in the previous commit got `E401` on v26.8.0-beta.1, after both
registries had already taken the version.

That leaves one npm write per release, and it has to go where it counts.
While no stable exists, `latest` and `beta` mean the same thing — there is
nothing else to install — so `latest` takes the publish, because that is what
a bare `npm install @green-tea/core` resolves to and an untouched `latest`
hands the default install an older build than the one just released. The
channel tag is moved by hand; the step prints the command and AGENTS.md says
when it applies.

This is temporary by construction. Once a stable version exists it owns
`latest`, a beta published afterwards must not drag it backwards, and the
publish goes back to setting the channel tag directly — with nothing left to
move by hand.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-08-19 14:17:12 -05:00
49 changed files with 2606 additions and 166 deletions

No files matched your search

+49 -37
View File
@@ -16,7 +16,7 @@ jobs:
PKG: '@green-tea/core' PKG: '@green-tea/core'
permissions: permissions:
id-token: write # OIDC for Trusted Publishing (also enables provenance) id-token: write # OIDC for Trusted Publishing (also enables provenance)
contents: read contents: write # create the GitHub release for this tag
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
@@ -42,19 +42,41 @@ jobs:
# types, module analysis — and learning about them after npm has published leaves the tag # types, module analysis — and learning about them after npm has published leaves the tag
# half-shipped. Seconds, against a failure mode with no clean recovery. # half-shipped. Seconds, against a failure mode with no clean recovery.
- run: deno publish --dry-run - run: deno publish --dry-run
# A publish sets exactly one dist-tag, and it is the only npm write this workflow can make:
# Trusted Publishing's OIDC exchange lives inside `npm publish` and nowhere else, so the token
# it produces is rejected by `npm dist-tag` (E401, learned on v26.8.0-beta.1). So the one tag
# the publish gets has to be the one that matters most.
#
# While no stable release exists, `latest` and the channel tag mean the same thing — there is
# nothing else to install — and `latest` takes it, because that is what a bare
# `npm install @green-tea/core` resolves to. Leaving it behind on an older beta would hand the
# default install an older build than the one just released. The channel tag is then moved by
# hand; the step prints the command. Once a stable version exists it owns `latest` for good,
# a later beta must not drag it backwards, and the channel tag becomes the automatic one again.
- name: Publish to npmjs - name: Publish to npmjs
run: | run: |
VERSION=$(node -p "require('./package.json').version") VERSION=$(node -p "require('./package.json').version")
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')") CHANNEL=$(node -e "const m=process.argv[1].match(/-([a-z]+)/);console.log(m?m[1]:'latest')" "$VERSION")
# Read the list into a variable so a failed lookup fails the step, rather than passing for
# "no stable exists" and pointing `latest` at a prerelease that should not have it.
VERSIONS=$(npm view "$PKG" versions --json)
if [ "$CHANNEL" != latest ] \
&& ! node -e "process.exit([].concat(JSON.parse(process.argv[1])).some(v=>!v.includes('-'))?0:1)" "$VERSIONS"; then
TAG=latest
else
TAG=$CHANNEL
fi
echo "$VERSION under dist-tag: $TAG" echo "$VERSION under dist-tag: $TAG"
# Skip rather than fail when the version is already up. A step after this one can fail — # Skip rather than fail when the version is already up, so a re-run after a later failure
# the dist-tag move below does — and a re-run of the job has to be able to finish the # can finish the remaining work instead of dying on a duplicate npm rejects anyway.
# remaining work instead of dying on a duplicate npm rejects anyway.
if npm view "$PKG@$VERSION" version >/dev/null 2>&1; then if npm view "$PKG@$VERSION" version >/dev/null 2>&1; then
echo "npm already has $VERSION" echo "npm already has $VERSION"
else else
npm publish --access public --tag "$TAG" npm publish --access public --tag "$TAG"
fi fi
if [ "$TAG" != "$CHANNEL" ]; then
echo "::notice::Move the channel tag by hand: npm dist-tag add $PKG@$VERSION $CHANNEL"
fi
# JSR last, deliberately. npm allows an unpublish within 72 hours; JSR versions are immutable # JSR last, deliberately. npm allows an unpublish within 72 hours; JSR versions are immutable
# and can never be replaced or removed. Ordered so a failure here costs a re-run, while a # and can never be replaced or removed. Ordered so a failure here costs a re-run, while a
# failure *after* it would cost a version number permanently. Version and entry points come # failure *after* it would cost a version number permanently. Version and entry points come
@@ -65,43 +87,33 @@ jobs:
run: | run: |
VERSION=$(node -p "require('./package.json').version") VERSION=$(node -p "require('./package.json').version")
PKG=${PKG#@} PKG=${PKG#@}
# 404 until the version exists — and it stays 404 for a package with no versions yet, which # 404 until the version exists, and also for a package with no versions at all — which is
# is the state this repository is actually in, so the guard must not read that as an error. # what this one was until v26.8.0-beta.1 — so the guard must not read a 404 as an error.
if curl -fsS -o /dev/null "https://api.jsr.io/scopes/${PKG%%/*}/packages/${PKG#*/}/versions/$VERSION"; then if curl -fsS -o /dev/null "https://api.jsr.io/scopes/${PKG%%/*}/packages/${PKG#*/}/versions/$VERSION"; then
echo "JSR already has $VERSION" echo "JSR already has $VERSION"
else else
deno publish deno publish
fi fi
# `latest` is what a bare `npm install @green-tea/core` resolves to, and while there is no
# stable release the docs promise it is the newest beta. `npm publish --tag beta` sets exactly # The release page is where people who do not read a changelog find out what changed, and a
# one tag, so `latest` has to be moved separately — and `npm dist-tag` cannot use Trusted # repository with tags and no releases reads as abandoned. Notes come from CHANGELOG.md rather
# Publishing, whose OIDC exchange lives only inside `npm publish`. So we run that same exchange # than from the commit range: the section was written for humans and already exists by the time
# by hand (id-token → short-lived npm token) rather than keep a long-lived token in a secret for # a tag is cut, and generated notes would restate merge subjects nobody chose.
# one command. Last on purpose: both registries already have the version, and a dist-tag is the #
# only thing here that can be redone. If this step fails, the release is out but `latest` is # Idempotent like the publishes above, so a re-run after a later failure does not stop here.
# stale — recover with `npm dist-tag add @green-tea/core@<version> latest`. # `--verify-tag` refuses to invent a tag: the release attaches to the one that triggered this
- name: Point `latest` at this release while no stable exists # run and can never move it. A prerelease is marked as such, which is what keeps GitHub's
# "Latest" badge off a beta.
- name: Create the GitHub release
env:
GH_TOKEN: ${{ github.token }}
run: | run: |
VERSION=$(node -p "require('./package.json').version") VERSION=$(node -p "require('./package.json').version")
case "$VERSION" in TAG=${GITHUB_REF_NAME}
*-*) ;; if gh release view "$TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
*) echo "$VERSION is stable — npm publish already put it on latest"; exit 0 ;; echo "release $TAG already exists"; exit 0
esac
# A stable release owns `latest` for good; a beta published afterwards must never drag it
# backwards, so the newest-beta rule applies only until the first stable exists.
# Read the list first so a failed lookup fails the step, rather than reading as "no stable
# exists" and moving `latest` backwards on the strength of a network error.
VERSIONS=$(npm view "$PKG" versions --json)
if node -e "process.exit([].concat(JSON.parse(process.argv[1])).some(v=>!v.includes('-'))?0:1)" "$VERSIONS"; then
echo "a stable version exists — leaving latest where it is"; exit 0
fi fi
URL=$(node -p "const u=new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL);u.searchParams.set('audience','npm:registry.npmjs.org');u.href") node scripts/changelog-section.mjs "$VERSION" "$TAG" > /tmp/notes.md
ID_TOKEN=$(curl -fsS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$URL" \ case "$VERSION" in *-*) PRE=--prerelease ;; *) PRE= ;; esac
| node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).value") gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --title "$TAG" \
echo "::add-mask::$ID_TOKEN" --notes-file /tmp/notes.md --verify-tag $PRE
NODE_AUTH_TOKEN=$(curl -fsS -X POST -H "Authorization: Bearer $ID_TOKEN" \
"https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/$(node -p "encodeURIComponent(process.env.PKG)")" \
| node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).token")
echo "::add-mask::$NODE_AUTH_TOKEN"
export NODE_AUTH_TOKEN
npm dist-tag add "$PKG@$VERSION" latest
+14
View File
@@ -85,6 +85,20 @@ Bumping `package.json` and `deno.json` ahead of the tag is fine and necessary
*next* publish will be called, and the docs repo's `verify:release` compares the tag against them. *next* publish will be called, and the docs repo's `verify:release` compares the tag against them.
A version number is a plan; a changelog heading is a receipt. A version number is a plan; a changelog heading is a receipt.
**After a beta release, move the channel tag by hand.** A publish sets exactly one dist-tag, and it
is the only npm write the release workflow can make — Trusted Publishing's OIDC exchange lives inside
`npm publish`, so the token it hands back is rejected by `npm dist-tag` (`E401`, learned the hard way
on `v26.8.0-beta.1`). While there is no stable release the publish spends that one tag on `latest`,
since that is what a bare `npm install @green-tea/core` resolves to, and the workflow prints the
command for the rest:
```bash
npm dist-tag add @green-tea/core@<version> beta
```
Once a stable version exists this stops being a chore: `latest` belongs to the stable release, the
publish gives a beta its channel tag directly, and there is nothing left to move.
## CI ## CI
The audit gate is scoped, not severity-filtered: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. A critical in the test runner reaches nobody; a high in `reflect-metadata` reaches everyone. It runs *after* the code gates, because an advisory published by a third party must never decide whether a contributor sees their own lint and typecheck output. The audit gate is scoped, not severity-filtered: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. A critical in the test runner reaches nobody; a high in `reflect-metadata` reaches everyone. It runs *after* the code gates, because an advisory published by a third party must never decide whether a contributor sees their own lint and typecheck output.
+142
View File
@@ -8,6 +8,148 @@ npm treats versions as semver and semver forbids leading zeros.
## [Unreleased] ## [Unreleased]
### Added
- **A request budget, not just a connection cap.** `createApp({ limits: { maxConcurrentRequests } })`
bounds how many handlers run at once, per server and per Fetch adapter instance; over the budget a
request gets `503` with `Retry-After: 1` instead of queueing behind the ones already running. It is
opt-in and unlimited by default, and it counts *executing handlers* rather than open connections —
the slot is released when routing and the handler finish, so a long-lived SSE stream or a WebSocket
upgrade does not hold one for its lifetime. On Node a client disconnect releases the slot early. A
handler that never returns keeps its slot, which is the honest behaviour for a budget of this shape.
Contributed by @hgshreyas.
Node's connection cap also stopped being silent: reaching `maxConnections` now logs a warning
naming the dropped peer, rate-limited to one a minute. Until now the socket was destroyed with no
HTTP response and nothing said so, which reads from the outside like a network fault.
- **`createApp({ handleSignals: true })` registers `SIGINT`/`SIGTERM` to close and exit.** Off by
default, and that is the design rather than caution: a library that installs process-wide handlers
behind your back is worse than one that installs none, because when the process exits is the
application's call. Both halves are supported — keep the handler, or hand it over. What is not
optional either way is that *something* calls `close()`; the teardown registry only runs from
there, so a container `SIGKILL`ed after its grace period skips every `dispose()` and reports
nothing.
Declared once and wired per runtime by whichever boot call runs — `listen()`, `serveDeno()` and
`serveBun()` each attach it to the closer that drains *their* server, so `process.on` on Node and
Bun and `Deno.addSignalListener` on Deno stop being the application's problem. `close()`
unregisters, which means a *second* signal falls through to the platform default and ends the
process at once: Ctrl-C twice is the way out of a teardown that is stuck.
- **The extension-point types are exported, not just the extension points.** `TransformerFn` — the
type of `@Transformer`'s only argument — could not be imported, so a custom transformer was
attached with its shape redeclared inline or borrowed off a value as `typeof JsonTransformer`.
Checking the barrel for the same oversight turned up four more, all now exported: `PluginApi`,
`ScopeApi` and `ScopeNode`, the chain reached through `api.scope.add`, without which a plugin split
into named functions cannot annotate what it receives; plus `Hooks` and `TeardownFn`. Types only —
nothing at runtime moved and no existing export changed.
- **The lifecycle stream has a contract now, not just events.** `request:end` is documented as
terminal and universal — it fires for every request shape and is the only one carrying the status
the client received, which makes it the request counter. `request:failed` means *handler code
threw*, which no status expresses on its own since a rendered `422` is also a throw, and
`route:unmatched` means *no route ran*. Both are **additional** to `request:end`, not alternatives
to it: one failing request emits three events and a 404 emits two, all sharing a `requestId`, and
an exporter that treats them as separate outcomes counts the same request twice. Silently — the
metrics just come out wrong.
`request:failed` now carries `status`, so an error counter can break down by status without
joining back through `requestId` for something the emitter already had. It is absent in exactly
one case: a custom `onError` that threw while producing it, where the framework does not know what
was sent and will not guess.
- **`@needs('events')` reaches the read-only half of the bus** — `{ on }`, the same narrowing
plugins already get, exported as the `Events` type. `app.bus` was public and a plugin could
subscribe, but the bus was not a graph token, so `@needs('bus')` failed at boot and nothing said
why. It still is not one, and that is the design: handing `emit` to every node turns a one-way
observation channel into something anything can forge events on. `@needs('bus')` now fails saying
exactly that, and pointing at the two things that do work.
A plugin remains the right home for observation, because it gets `on` and `onShutdown` *together*.
This token gives the subscribe half alone — `on()` returns its own unsubscribe for a `@Provider`
to release in `dispose()`, and a `@Step` should not subscribe at all, since it runs per request
and would add a listener each time.
### Changed
- **A request's security and CORS headers are computed once.** They were derived twice per request
and three times for a preflight — once in the adapter, to seed the headers a response written
before routing still has to carry, and again during dispatch. Nothing was incorrect, but
`cors.origins` is a predicate precisely so it can be a lookup: an allowlist in Redis, a tenant
query. Running it two or three times charged the caller's latency budget and their backend for an
answer whose inputs had not changed in between, and made a predicate with a counter in it count
double.
- **Every `request:end` is now preceded by a `request:start` carrying the same `requestId`.** The
pairing held by accident until `maxConcurrentRequests` arrived: `request:start` had a single
emitter, so nothing could break it, and a shed request emitted only the `request:end`. A consumer
that opens per-request state on the first and closes it on the second — an in-flight gauge, most
obviously — would have drifted under shedding, which is when an operator is reading it, and would
have done so by producing a plausible wrong number rather than an error. It is a guarantee now,
written next to `LifecycleEvent` and enforced by a test that enumerates every response shape.
- **An unmatched request carries a bounded `route`.** `route:unmatched` was the one terminal request
event with no `route`, so the only subject a consumer could reach was `name` — which on that event
is the concrete, caller-controlled path. A matched path is bounded by the route table; an
unmatched one is bounded by nothing, and a scanner walking `/aaa`, `/aab`, `/aac` is a memory leak
with a metrics backend attached. It and the `request:end` that follows now carry
`route: '<unmatched>'`, exported as `UNMATCHED_ROUTE`. Written down alongside it: `name` is
caller-controlled and must never be a metric label.
- **Framework token names are reserved.** `logger`, `rooms`, `events` and `bus` cannot be declared
by a module, plugin or mesh export; taking one is a boot error naming it. Built-ins used to be
registered only if the name was free, so a provider called `logger` silently replaced the
framework's own and every `@needs('logger')` in the app got something that was not the logger core
writes to — a divergence discovered from a log line that never appeared. `bus` is reserved without
being provided, so `@needs('bus')` cannot resolve to whatever a user happened to call `bus`.
**This can fail an app that boots today**, which is the point of it, and the fix is to rename.
- **No per-request bookkeeping when no request budget is set.** Every request registered a `close`
listener and set a flag for `maxConcurrentRequests`, which is opt-in and unlimited by default — so
most applications paid a closure and an `EventEmitter` registration per request, on the hot path,
for a feature that was off. Unchanged where a budget *is* configured: the listener is what
releases a slot when a client disconnects mid-handler.
### Fixed
- **A `cors.origins` predicate that throws no longer takes the process down.** The predicate runs on
the request path, above the region where errors convert to a response, so a throw became a rejected
promise nobody awaited — and Node's default for that is to exit. One cross-origin request was
enough, `onError` never saw it, and the trigger is a browser: the predicate is only reached when an
`Origin` header is present, so no test that forgets the header can catch it. A predicate that throws
now **denies** the origin and the failure is logged. A lookup that failed has not said yes, and a
broken allowlist must never widen into an open one.
- **The JSR package works.** JSR serves `src/` rather than the tsup build, and the ESM build's
`createRequire` banner therefore never existed there — so every lazy `require()` in the source had
nothing to resolve. `@Html('file')` and template mode died at boot on Deno with `ReferenceError:
require is not defined`. Two other sites were worse than the crash because they answered
confidently and wrongly: `static` reported *"needs a filesystem and is unavailable on this runtime
(edge)"* while running on Deno, which has one, and multipart reported `busboy` as not installed
while it sat in `node_modules`. Both blamed the runtime for a packaging problem, and both named a
runtime the reader was not on.
Every call site now resolves through one helper that prefers the ambient `require` — so both npm
builds behave exactly as before — and otherwise rebuilds one from
`process.getBuiltinModule('node:module')`, which Node, Deno and Bun all expose synchronously. On
workerd, which offers neither, nothing changes and the guarded sites' "edge has no filesystem"
story is finally the true one.
- **A custom `onError` that throws no longer takes the process down.** `createApp({ onError })` is
the advertised way to render errors, it runs on the request path, and it ran with no boundary — a
renderer that threw exited the process, exit code 1. It is the same shape as the CORS predicate
crash above and easier to reach: not a cross-origin request, but *any* request that produces an
error. The renderer produces the 404 too, so an app with a custom renderer and no matching route
was one request away from exiting.
It was also the worst-timed crash there was, since the renderer only runs once something has
already gone wrong: an error occurs, the code written to report it fails, and instead of a
degraded report the server ends. A renderer that throws now falls back to the built-in rendering —
which is exactly what the option overrides — so the original error still gets its response, and
the renderer's own failure is logged separately, naming both.
## [26.8.0-beta.1] - 2026-08-19 ## [26.8.0-beta.1] - 2026-08-19
### Added ### Added
+3 -2
View File
@@ -141,10 +141,11 @@ without growing the runtime dependency tree past `reflect-metadata`:
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. - **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. - **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. Configurable, and safe before you configure anything. - **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core. - **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`. - **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Shutdown is an extension point, not a `SIGTERM` handler you write.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook. - **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
- **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck.
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line. - **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations. - **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env node
// Prints one version's section of CHANGELOG.md, for a GitHub release body.
//
// Reads the current file rather than the tag's copy on purpose: the changelog is the record, so a
// correction to an old entry should reach the release that describes it.
//
// Usage: node scripts/changelog-section.mjs <version> [tag]
// The optional tag makes relative links absolute — a release body resolves them against the release
// page, not the repository, and pinning to the tag keeps the link on the file as that version had it.
import { readFileSync } from 'node:fs';
const REPO = 'Expressive-Tea/green-tea';
const [version, tag] = process.argv.slice(2);
if (!version) {
console.error('usage: changelog-section.mjs <version> [tag]');
process.exit(2);
}
const lines = readFileSync(new URL('../CHANGELOG.md', import.meta.url), 'utf8').split('\n');
const isHeading = (l) => l.startsWith('## [');
// The `[label]: url` block at the bottom of the file belongs to no section. Without this the last
// section swallows it, since nothing else comes after.
const isLinkRef = (l) => /^\[[^\]]+\]:\s+\S/.test(l);
const start = lines.findIndex((l) => l.startsWith(`## [${version}]`));
if (start === -1) {
console.error(`no section for ${version}. Headings in CHANGELOG.md:\n${lines.filter(isHeading).join('\n')}`);
process.exit(1);
}
const rest = lines.slice(start + 1);
const stop = rest.findIndex((l) => isHeading(l) || isLinkRef(l));
const body = (stop === -1 ? rest : rest.slice(0, stop)).join('\n').trim();
const absolute = tag
? body.replace(/\]\(\.\/([^)\s]+)\)/g, `](https://github.com/${REPO}/blob/${tag}/$1)`)
: body;
console.log(absolute);
+128 -21
View File
@@ -1,5 +1,5 @@
import type http from 'http'; import type http from 'http';
import { Bus } from '../bus'; import { Bus, type Events } from '../bus';
import { createDefaultLogger, logRequests, type Logger } from '../logger'; import { createDefaultLogger, logRequests, type Logger } from '../logger';
import { Container } from '../container'; import { Container } from '../container';
import { topoSort, subgraphFor, GraphNode, nearest } from '../graph'; import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
@@ -13,6 +13,7 @@ import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
import { TeardownRegistry } from '../lifecycle'; import { TeardownRegistry } from '../lifecycle';
import { installSignalHandlers } from '../http/signals-shutdown';
import type { Hooks } from './types'; import type { Hooks } from './types';
import { import {
Ctor, Ctor,
@@ -40,7 +41,7 @@ import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect'; import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern } from '../http/router'; import { compilePattern } from '../http/router';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types'; export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
type Runner = (ctx: any) => any; type Runner = (ctx: any) => any;
@@ -61,7 +62,7 @@ interface Registry {
exportedProviders: string[]; exportedProviders: string[];
exportedSteps: string[]; exportedSteps: string[];
exportedRoutes: RouteEntry[]; exportedRoutes: RouteEntry[];
setRunner(name: string, runner: Runner): void; setRunner(name: string, runner: Runner, framework?: boolean): void;
} }
/** /**
@@ -85,6 +86,8 @@ interface PipelineDeps {
planSteps(plan: RoutePlan): PipelineStep[]; planSteps(plan: RoutePlan): PipelineStep[];
bus: Bus; bus: Bus;
onError?: ErrorRenderer; onError?: ErrorRenderer;
/** Where a failing `onError` is reported — the renderer's error is not the request's. */
logger: Logger;
} }
/** /**
@@ -139,6 +142,25 @@ export function createApp(opts: {
* Must not exceed `shutdownTimeoutMs`; `createApp` throws rather than clamping silently. * Must not exceed `shutdownTimeoutMs`; `createApp` throws rather than clamping silently.
*/ */
teardownTimeoutMs?: number; teardownTimeoutMs?: number;
/**
* Register `SIGINT`/`SIGTERM` to run `close()` and exit the process (default: `false`).
*
* Off by default because a library that installs process-wide handlers behind your back is worse
* than one that installs none — when the process exits is the application's call, not ours. Turn
* it on and the framework absorbs the last runtime difference an app otherwise has: `process.on`
* on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each.
*
* Leaving it off is a supported choice, not a gap — write the handler yourself if you want the
* control. What is *not* optional either way is that something calls `close()`: the teardown
* registry only runs from there, so a container `SIGKILL`ed after its grace period skips every
* `dispose()` the registry so carefully ordered, and reports nothing.
*
* Registered by `listen()`, `serveDeno()` and `serveBun()`, and taken back off by `close()` —
* so a *second* signal arriving mid-shutdown falls through to the platform default and ends the
* process at once. Ctrl-C twice is the way out of a teardown that is stuck; once is the way to
* let it finish.
*/
handleSignals?: boolean;
/** /**
* Where every framework diagnostic is written (default: structured JSON, human-readable on a TTY). * Where every framework diagnostic is written (default: structured JSON, human-readable on a TTY).
* *
@@ -188,7 +210,7 @@ export function createApp(opts: {
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry; const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs); const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs);
mountPlugins(opts.plugins, bus, registry, teardown); mountPlugins(opts.plugins, bus, registry, teardown);
provideBuiltins(registry, logger); provideBuiltins(registry, logger, bus);
// For each route, resolve which providers/steps feed it via topo order. // For each route, resolve which providers/steps feed it via topo order.
// MVP: every route depends on every declared step + provider in the app graph. // MVP: every route depends on every declared step + provider in the app graph.
@@ -209,7 +231,7 @@ export function createApp(opts: {
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan); const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan); const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError }; const pipelineDeps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError, logger };
let meshControl: MeshControl | undefined; let meshControl: MeshControl | undefined;
// mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize. // mesh teacup: connect remote teapots and splice their scopes/routes in, then finalize.
@@ -274,6 +296,7 @@ export function createApp(opts: {
const fetchOpts: HttpOptions = { const fetchOpts: HttpOptions = {
bus, bus,
logger,
limits: opts.limits, limits: opts.limits,
tls: opts.tls, tls: opts.tls,
trustProxy: opts.trustProxy, trustProxy: opts.trustProxy,
@@ -285,7 +308,7 @@ export function createApp(opts: {
}; };
const fetchFn = buildAppFetch( const fetchFn = buildAppFetch(
routePlans, routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError }, { providedSeed, planSteps, bus, onError: opts.onError, logger },
fetchOpts, fetchOpts,
bootApp, bootApp,
devRoutes, devRoutes,
@@ -305,6 +328,7 @@ export function createApp(opts: {
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, {
bus, bus,
logger,
limits: opts.limits, limits: opts.limits,
streams, streams,
tls: opts.tls, tls: opts.tls,
@@ -317,15 +341,52 @@ export function createApp(opts: {
}); });
server.on('close', () => closeLinks(meshLinks)); server.on('close', () => closeLinks(meshLinks));
await new Promise<void>((resolve) => server!.listen(port, resolve)); await new Promise<void>((resolve) => server!.listen(port, resolve));
// After the socket is up, so a boot that throws never leaves a handler behind pointing at an
// app that never served.
handleSignals(close);
return server; return server;
}; };
const close = (options: { timeoutMs?: number } = {}): Promise<void> => // Torn down by whichever close runs first, signal-driven or hand-called. On Deno that is
closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger, teardown, opts.teardownTimeoutMs); // load-bearing rather than tidy: a live `Deno.addSignalListener` keeps the process up, so an app
// that closed itself and expected to exit would simply hang.
let removeSignalHandlers: (() => void) | undefined;
const clearSignalHandlers = (): void => {
removeSignalHandlers?.();
removeSignalHandlers = undefined;
};
const close = (options: { timeoutMs?: number } = {}): Promise<void> => {
clearSignalHandlers();
return closeApp(
server,
meshLinks,
streams,
options,
opts.shutdownTimeoutMs,
logger,
teardown,
opts.teardownTimeoutMs,
);
};
const handleSignals = <T extends (options?: { timeoutMs?: number }) => Promise<void>>(closer: T): T => {
if (!opts.handleSignals) return closer;
const wrapped = ((options?: { timeoutMs?: number }) => {
clearSignalHandlers();
return closer(options);
}) as T;
removeSignalHandlers = installSignalHandlers(() => wrapped(), logger);
return wrapped;
};
return { return {
listen, listen,
close, close,
handleSignals,
ready, ready,
fetch: fetchFn, fetch: fetchFn,
upgrade: upgradeFn, upgrade: upgradeFn,
@@ -345,7 +406,12 @@ export function createApp(opts: {
function emptyRegistry(): Registry { function emptyRegistry(): Registry {
const runners = new Map<string, Runner>(); // node name -> runtime fn const runners = new Map<string, Runner>(); // node name -> runtime fn
const setRunner = (name: string, runner: Runner) => { const setRunner = (name: string, runner: Runner, framework = false) => {
if (!framework && RESERVED_TOKENS.has(name))
throw new Error(
`'${name}' is reserved by the framework and cannot be provided by a module, plugin or mesh export — ` +
`rename it. The framework's own '${name}' is what '@needs' resolves to.`,
);
if (runners.has(name)) if (runners.has(name))
throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`); throw new Error(`duplicate provider/step name '${name}' — names must be unique across modules and plugins`);
runners.set(name, runner); runners.set(name, runner);
@@ -534,22 +600,46 @@ function mountPlugins(plugins: Plugin[] | undefined, bus: Bus, registry: Registr
} }
/** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */ /** Auto-provides a shared {@link Rooms} instance unless the user already declared a `rooms` provider. */
function provideBuiltins(registry: Registry, logger: Logger): void { /**
* Token names the framework owns. Declaring one is a boot error, not a silent override.
*
* Builtins used to be registered with `if (!runners.has(name))`, so a provider called `logger`
* quietly replaced the framework's own and every `@needs('logger')` in the app got something else.
* That is the kind of thing that is discovered from a log line that never appeared.
*
* `bus` is reserved without being provided, on purpose. It is not a graph token — putting the `Bus`
* itself in the graph would hand `emit` to every node and turn a one-way observation channel into
* something anything can forge events on. Reserving the name means `@needs('bus')` can say that,
* instead of resolving to whatever a user happened to call `bus` and being wrong in silence.
*/
const RESERVED_TOKENS = new Set(['logger', 'rooms', 'events', 'bus']);
function provideBuiltins(registry: Registry, logger: Logger, bus: Bus): void {
const builtin = (name: string, value: () => Record<string, unknown>): void => {
registry.providerNodes.push({ name, needs: [], provides: [name], origin: 'builtin' });
registry.providerMeta.set(name, { optional: false });
registry.setRunner(name, value, true);
};
// `logger` is registered as an ordinary provider *in addition to* being framework infrastructure, // `logger` is registered as an ordinary provider *in addition to* being framework infrastructure,
// so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the // so a step or handler reaches it with `@needs('logger')` like any other dependency. It is the
// same object createApp holds, not a second one — core cannot depend on the graph for something // same object createApp holds, not a second one — core cannot depend on the graph for something
// it must use while the graph is still resolving. // it must use while the graph is still resolving.
if (!registry.runners.has('logger')) { builtin('logger', () => ({ logger }));
registry.providerNodes.push({ name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' });
registry.providerMeta.set('logger', { optional: false });
registry.setRunner('logger', () => ({ logger }));
}
if (registry.runners.has('rooms')) return;
const roomsInstance = new Rooms(); const roomsInstance = new Rooms();
registry.providerNodes.push({ name: 'rooms', needs: [], provides: ['rooms'], origin: 'builtin' }); builtin('rooms', () => ({ rooms: roomsInstance }));
registry.providerMeta.set('rooms', { optional: false });
registry.setRunner('rooms', () => ({ rooms: roomsInstance })); // merge object -> ctx.rooms // The read-only half of the bus, and only the read-only half: `on`, never `emit`. The same
// narrowing a plugin gets, for the same reason — an observation channel anything can write to is
// not one.
//
// A subscription is not like the other injectables, and the difference is the scope that reaches
// it. A `@Provider` runs once, so subscribing there is fine; a `@Step` runs *per request*, and a
// step that calls `on()` registers a listener on every one of them. `on()` returns its own
// unsubscribe for the provider that wants to clean up in `dispose()` — but a plugin, which gets
// `on` and `onShutdown` together, remains the right home for observation.
builtin('events', () => ({ events: { on: bus.on.bind(bus) } satisfies Events }));
} }
// Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling // Boot-time nudge: a route whose need-closure pulls this many steps is almost always a modeling
@@ -607,6 +697,21 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
for (const plan of routePlans) { for (const plan of routePlans) {
for (const need of plan.needs) { for (const need of plan.needs) {
if (allowed.has(need)) continue; if (allowed.has(need)) continue;
// The generic message plus a nearest-match is right for a typo and useless here: nothing is
// spelled nearly enough like `bus` to suggest, and the reader's mistake is not a typo but a
// reasonable guess about the shape. `@needs('logger')` teaches that framework things are
// graph tokens, so `@needs('bus')` is the next instinct — and the boot error is the first
// news that it is not the same shape. Say why, where they are.
if (need === 'bus') {
throw new Error(
`handler '${plan.handlerName}' needs 'bus' — the Bus is not a graph token, because a node ` +
`that could reach it could also emit, and an observation channel anything can write to ` +
`is not one. Use @needs('events') for the read-only half ({ on }), or write a plugin, ` +
`which gets on() and onShutdown() together and is the right home for observation.`,
);
}
const hint = nearest(need, allowed); const hint = nearest(need, allowed);
throw new Error( throw new Error(
`handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`, `handler '${plan.handlerName}' needs '${need}' but nothing (local or mesh) provides it${hint ? ` — did you mean '${hint}'?` : ''}`,
@@ -947,7 +1052,7 @@ function buildMeshControl(
if (!mesh?.secret || !hasExports) return undefined; if (!mesh?.secret || !hasExports) return undefined;
const { container, orderedProviders, orderedSteps } = deps; const { container, orderedProviders, orderedSteps } = deps;
const { bus, providedSeed, planSteps, onError } = deps.deps; const { bus, providedSeed, planSteps, onError, logger } = deps.deps;
const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes }); const manifest = buildManifest({ providers: exportedProviders, steps: exportedSteps, routes: exportedRoutes });
const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => { const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
@@ -986,6 +1091,7 @@ function buildMeshControl(
transformer: plan.transformer, transformer: plan.transformer,
bus, bus,
onError, onError,
logger,
transport: plan.transport, transport: plan.transport,
correlation: { correlation: {
requestId: env.correlation?.requestId, requestId: env.correlation?.requestId,
@@ -1011,7 +1117,7 @@ function buildMeshControl(
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */ /** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] { function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus, onError } = deps; const { providedSeed, planSteps, bus, onError, logger } = deps;
const local = routePlans const local = routePlans
.filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate .filter((plan) => plan.transport !== 'ws') // buffer | sse | ndjson | negotiate
@@ -1030,6 +1136,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
transformer: plan.transformer, transformer: plan.transformer,
bus, bus,
onError, onError,
logger,
transport: plan.transport, transport: plan.transport,
// `route` is the pattern, never req.url — a metrics consumer labelling on concrete // `route` is the pattern, never req.url — a metrics consumer labelling on concrete
// paths gets one label per distinct URL, and that takes down the metrics backend. // paths gets one label per distinct URL, and that takes down the metrics backend.
+9
View File
@@ -38,6 +38,15 @@ export interface Explain {
export interface App { export interface App {
listen(port: number): Promise<http.Server>; listen(port: number): Promise<http.Server>;
close(options?: { timeoutMs?: number }): Promise<void>; close(options?: { timeoutMs?: number }): Promise<void>;
/**
* Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or
* returns `closer` untouched when `createApp({ handleSignals })` was not set.
*
* `listen()`, `serveDeno()` and `serveBun()` each call this with the closer that actually drains
* their server, which is why the option is declared once on `createApp` and works on all three.
* Call it yourself only if you serve the app some other way.
*/
handleSignals<T extends (options?: { timeoutMs?: number }) => Promise<void>>(closer: T): T;
/** /**
* Resolves the dependency graph, then returns. For a mesh app that means connecting to its * Resolves the dependency graph, then returns. For a mesh app that means connecting to its
* teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every * teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every
+5 -1
View File
@@ -117,7 +117,10 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
// Object.assign rather than a fresh object: Bun.serve returns more than the ambient above // Object.assign rather than a fresh object: Bun.serve returns more than the ambient above
// declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name. // declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name.
return Object.assign(server, { return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> => // Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
// runtime's own signal API — and so the close it returns takes the handlers back off, which
// Deno requires to exit at all.
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline( closeWithDeadline(
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design. // Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
// `app.close()` returns at its no-server guard on Bun, but still drains the teardown // `app.close()` returns at its no-server guard on Bun, but still drains the teardown
@@ -133,5 +136,6 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu
runtime: 'bun', runtime: 'bun',
}), }),
), ),
),
}); });
} }
+93 -3
View File
@@ -1,4 +1,28 @@
/** Names of every lifecycle event the framework emits over the {@link Bus}. */ /**
* Names of every lifecycle event the framework emits over the {@link Bus}.
*
* ### The request pair is a guarantee
*
* **Every `request:end` is preceded by a `request:start` carrying the same `requestId`.** A
* consumer may open per-request state on the first and close it on the second without checking
* whether the request got as far as a route — a shed `503` emits the pair as surely as a `200`
* does.
*
* This is a promise to emitters as much as to subscribers: a terminal path that emits one must
* emit the other, in that order. It held by accident until `maxConcurrentRequests` added the first
* terminal path that does not reach the router, and `test/lifecycle-pairing.test.ts` enumerates
* every response shape so that the next one cannot break it quietly. The alternative — documenting
* `request:end` as standalone — was rejected because it makes the obvious consumer wrong: an
* in-flight gauge counting `start` up and `end` down would drift negative under shedding, which is
* exactly when an operator is reading it.
*
* ### `request:end` is terminal and universal; the others are additional
*
* `request:end` fires for every dispatched request — handled, thrown and unmatched alike — and is
* the only one of these carrying the real status. **Count it, and nothing else.**
* `request:failed` and `route:unmatched` describe the *same* request and fire in addition to it, so
* a consumer that counts them as separate outcomes counts one request twice. See `EventPayload`.
*/
export type LifecycleEvent = export type LifecycleEvent =
| 'boot:provider:start' | 'boot:provider:start'
| 'boot:provider:ok' | 'boot:provider:ok'
@@ -17,12 +41,18 @@ export type LifecycleEvent =
// came up, and a deploy watching for trouble wants to tell those apart. // came up, and a deploy watching for trouble wants to tell those apart.
| 'mesh:boot:retry' | 'mesh:boot:retry'
| 'plugin:mounted' | 'plugin:mounted'
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a
// request arrived, not that it routed.
| 'request:start' | 'request:start'
| 'request:end' | 'request:end'
// "handler code threw", and *additional* to the `request:end` that follows it — a rendered 422 is
// also a throw, which is a thing a status alone cannot express.
| 'request:failed' | 'request:failed'
| 'route:matched' | 'route:matched'
// Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would // Covers a 404 *and* a 405 — the report's `route.not_found` names one outcome and would
// misreport the other, and "no route ran" is the fact a consumer actually wants. // misreport the other, and "no route ran" is the fact a consumer actually wants. It is also not
// a synonym for "the request failed": a static file served from `createApp({ static })` matched
// no route either, and answers 200. Read the status from the `request:end` that follows.
| 'route:unmatched'; | 'route:unmatched';
/** /**
@@ -31,8 +61,39 @@ export type LifecycleEvent =
* *
* Everything past `name` is optional and stays that way. Boot and mesh events have no request to * Everything past `name` is optional and stays that way. Boot and mesh events have no request to
* name, and requiring a shape they cannot fill would only mean inventing values for it. * name, and requiring a shape they cannot fill would only mean inventing values for it.
*
* ### One failed request produces three events
*
* A single request that throws emits `request:start`, then `request:failed`, then `request:end`.
* All three carry the same `requestId`, and the first implementation anyone writes counts the
* failure twice — once from `request:failed` and once from the `request:end` that follows it,
* under whatever status it invents for the one that had none. `route:unmatched` overlaps the same
* way: it fires *in addition to* the `request:end` that follows, so a 404 is two events and one
* outcome.
*
* The division of labour, which is the thing to build against:
*
* - **`request:end`** — terminal, universal, and the only one carrying the status the client
* received. This is the request counter and the latency histogram.
* - **`request:failed`** — *handler code threw*, which no status can express on its own: a
* rendered `422` is also a throw. This is a separate error counter, not a second request
* counter.
* - **`route:unmatched`** — *no route ran*, covering 404 and 405 alike. Also additional.
*
* `logRequests` gets this right and is worth reading as a reference (`src/logger.ts`): it takes
* the outcome from `request:end` and only the message from `request:failed`.
*/ */
export interface EventPayload { export interface EventPayload {
/**
* What the event is about, for a human reading a log line.
*
* **Never use this as a metric label.** On the request events it is caller-controlled: for a
* matched request it is the route pattern, but on `request:start` and `route:unmatched` it is
* built from the path that arrived. A matched path is bounded by the route table; an unmatched
* one is bounded by nothing at all, and a scanner walking `/aaa`, `/aab`, `/aac` becomes one
* label per distinct URL — a memory leak with a metrics backend attached. Label on {@link route},
* which is bounded by construction.
*/
name: string; name: string;
scope?: string; scope?: string;
error?: unknown; error?: unknown;
@@ -41,10 +102,23 @@ export interface EventPayload {
requestId?: string; requestId?: string;
/** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */ /** A `traceparent` header carried verbatim. Core parses nothing — that is the exporter's job. */
traceId?: string; traceId?: string;
/** The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}. */ /**
* The matched *pattern* (`/users/:id`), never the concrete path — see {@link Correlation}.
*
* Bounded by the route table, which is what makes it the field to label a metric on. When nothing
* matched it is `'<unmatched>'` rather than absent, on `route:unmatched` and on the `request:end`
* that follows it: a single series for every path that was never a route, instead of a fallback
* each consumer invents and some get wrong. It cannot collide with a real pattern, which always
* starts with `/`.
*/
route?: string; route?: string;
method?: string; method?: string;
transport?: string; transport?: string;
/**
* The status the client received. Present on `request:end` always, and on `request:failed`
* except when a custom `onError` renderer threw while producing it — the one case where the
* framework does not know what was sent, and will not guess.
*/
status?: number; status?: number;
} }
@@ -58,6 +132,22 @@ export interface EventPayload {
*/ */
export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>; export type Correlation = Pick<EventPayload, 'requestId' | 'traceId' | 'route' | 'method' | 'transport'>;
/**
* The read-only half of the {@link Bus}, as `@needs('events')` hands it over.
*
* `on` and deliberately not `emit`: a channel anything can write to is not an observation channel,
* and the framework's own events would stop being trustworthy the moment a node could forge one.
* Plugins get exactly this same narrowing.
*
* `on` returns its own unsubscribe. Use it — a `@Provider` that subscribes should release in
* `dispose()`, and a `@Step` should not subscribe at all, since it runs once per request and would
* add a listener each time. A plugin, which gets `on` and `onShutdown` together, is the home this
* token exists to point at rather than replace.
*/
export interface Events {
on: Bus['on'];
}
/** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */ /** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */
export class Bus { export class Bus {
private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>(); private readonly listeners = new Map<LifecycleEvent, Set<(p: EventPayload) => void>>();
+5 -1
View File
@@ -76,7 +76,10 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
// Object.assign rather than a fresh object: Deno.serve returns more than the ambient above // Object.assign rather than a fresh object: Deno.serve returns more than the ambient above
// declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name. // declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name.
return Object.assign(server, { return Object.assign(server, {
close: (closeOptions: { timeoutMs?: number } = {}): Promise<void> => // Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this
// runtime's own signal API — and so the close it returns takes the handlers back off, which
// Deno requires to exit at all.
close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise<void> =>
closeWithDeadline( closeWithDeadline(
// Drain, then hand over to the app so registered teardown runs — D7 of the teardown design. // Drain, then hand over to the app so registered teardown runs — D7 of the teardown design.
// `app.close()` returns at its no-server guard on Deno, but still drains the teardown // `app.close()` returns at its no-server guard on Deno, but still drains the teardown
@@ -101,5 +104,6 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer {
{ timeoutMs: ms, runtime: 'deno' }, { timeoutMs: ms, runtime: 'deno' },
), ),
), ),
),
}); });
} }
+1 -1
View File
@@ -129,7 +129,7 @@ function parseAcquired(
return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) => return parseRequestBody(acquired.bytes, contentType, duplicates, maxParts).then((parsed) =>
'error' in parsed 'error' in parsed
? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError) } ? { fail: renderError(new HttpError(parsed.status ?? 400, parsed.error), req, opts?.onError, opts?.logger) }
: { body: parsed.body }, : { body: parsed.body },
); );
} }
+80 -12
View File
@@ -9,6 +9,7 @@ import { acquireBody, type BodyReader } from './body';
import type { RouteDef, HttpOptions } from './types'; import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { nodeRequire } from '../node-require';
/** /**
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import. * `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
@@ -23,15 +24,15 @@ import type { Bus } from '../bus';
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly * CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
* why that job is pinned to the floor rather than to the current release. * why that job is pinned to the floor rather than to the current release.
* *
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates the * The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
* `require` — and the ESM build has a real one, from the `createRequire` banner in `tsup.config.ts`. * It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on
* every distribution of this package and not just the bundled ones.
*/ */
const randomUUID: () => string = (() => { const randomUUID: () => string = (() => {
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto; const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!(); if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
// eslint-disable-next-line @typescript-eslint/no-require-imports return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
return (require('node:crypto') as { randomUUID: () => string }).randomUUID;
})(); })();
/** /**
@@ -132,7 +133,7 @@ export function computeInjected(
req: { secure: boolean; headers: Record<string, string | string[] | undefined> }, req: { secure: boolean; headers: Record<string, string | string[] | undefined> },
): Record<string, string> { ): Record<string, string> {
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) }; const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts.logger));
return injected; return injected;
} }
@@ -143,7 +144,7 @@ function errorOutcome(
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
headers: Record<string, string> = {}, headers: Record<string, string> = {},
): HandleResult { ): HandleResult {
const rendered = renderError(error, req, opts?.onError); const rendered = renderError(error, req, opts?.onError, opts?.logger);
return { return {
injected, injected,
outcome: { outcome: {
@@ -191,6 +192,15 @@ async function unmatchedOutcome(
return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {}); return errorOutcome(error, req, injected, opts, allow.length ? { allow: allow.join(', ') } : {});
} }
/**
* The `route` reported for a request no route matched.
*
* A bounded value rather than an empty field, and deliberately unlike any pattern a user can
* declare — a route pattern starts with `/`, so this cannot collide with one. It aggregates as a
* single series where the concrete path would produce one per distinct URL.
*/
export const UNMATCHED_ROUTE = '<unmatched>';
/** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */ /** What `dispatch` learned along the way that `handle` needs in order to describe the request afterwards. */
interface Trace { interface Trace {
route?: string; route?: string;
@@ -211,6 +221,7 @@ export function handle(
routes: RouteDef[], routes: RouteDef[],
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
req: NeutralRequest, req: NeutralRequest,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> { ): Promise<HandleResult | Preflight> {
const bus = opts?.bus; const bus = opts?.bus;
@@ -226,10 +237,52 @@ export function handle(
bus.hasListeners('route:unmatched') bus.hasListeners('route:unmatched')
) )
) { ) {
return dispatch(routes, opts, req, undefined, undefined); return dispatch(routes, opts, req, undefined, undefined, injected);
} }
return observedDispatch(routes, opts, req, bus); return observedDispatch(routes, opts, req, bus, injected);
}
/**
* Whether anything is listening for the request pair — the one check both adapters need before
* paying for a `performance.now()` on a request they are about to refuse.
*/
export function watchingRequests(bus: Bus | undefined): bus is Bus {
return bus !== undefined && (bus.hasListeners('request:start') || bus.hasListeners('request:end'));
}
/**
* Emits the lifecycle pair for a request shed before routing.
*
* A shed request never reaches {@link handle}, so `observedDispatch` — the emitter every other
* terminal path goes through — never sees it, and an adapter that emitted only `request:end` would
* be the first thing in the tree to break the pairing {@link LifecycleEvent} guarantees. Both
* events are emitted here, in order, so a consumer that opens per-`requestId` state on
* `request:start` and closes it on `request:end` does not start leaking half-open entries the first
* time a server sheds — under load, which is when it can least afford them.
*
* Each event keeps its own listener guard: the pairing is a promise to a subscriber of *both*, and
* costs nothing for a subscriber of one.
*/
export function emitShedPair(
bus: Bus,
req: { method: string; url: string; requestId?: string; traceId?: string },
startedAt: number,
): void {
const name = `${req.method} ${req.url}`;
if (bus.hasListeners('request:start'))
bus.emit('request:start', { name, method: req.method, requestId: req.requestId, traceId: req.traceId });
if (bus.hasListeners('request:end'))
bus.emit('request:end', {
name,
method: req.method,
status: 503,
durationMs: performance.now() - startedAt,
requestId: req.requestId,
traceId: req.traceId,
});
} }
async function observedDispatch( async function observedDispatch(
@@ -237,6 +290,7 @@ async function observedDispatch(
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
req: NeutralRequest, req: NeutralRequest,
bus: Bus, bus: Bus,
injected?: Record<string, string>,
): Promise<HandleResult | Preflight> { ): Promise<HandleResult | Preflight> {
const watchingEnd = bus.hasListeners('request:end'); const watchingEnd = bus.hasListeners('request:end');
const startedAt = watchingEnd ? performance.now() : 0; const startedAt = watchingEnd ? performance.now() : 0;
@@ -250,7 +304,7 @@ async function observedDispatch(
traceId: req.traceId, traceId: req.traceId,
}); });
const result = await dispatch(routes, opts, req, bus, trace); const result = await dispatch(routes, opts, req, bus, trace, injected);
if (watchingEnd) { if (watchingEnd) {
// A preflight is a 204 the router never routed; a stream has no status of its own and is a 200 // A preflight is a 204 the router never routed; a stream has no status of its own and is a 200
@@ -276,8 +330,13 @@ async function dispatch(
req: NeutralRequest, req: NeutralRequest,
bus: Bus | undefined, bus: Bus | undefined,
trace: Trace | undefined, trace: Trace | undefined,
precomputed?: Record<string, string>,
): Promise<HandleResult | Preflight> { ): Promise<HandleResult | Preflight> {
const injected = computeInjected(opts, req); // Both adapters compute this before routing, because a response written above `handle()` — a
// shed 503, a 413 from the body reader — has to carry the same headers as one written below it.
// Recomputing here would run `security` and, worse, the `origins` predicate a second time for
// one request. `computeInjected` stays as the fallback for callers that have nothing yet.
const injected = precomputed ?? computeInjected(opts, req);
let path: string; let path: string;
try { try {
@@ -287,15 +346,24 @@ async function dispatch(
} }
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
return { preflight: corsPreflightHeaders(opts.cors, req) }; return { preflight: corsPreflightHeaders(opts.cors, req, injected) };
} }
const matched = resolveRoute(routes, req.method, path); const matched = resolveRoute(routes, req.method, path);
if (!matched) { if (!matched) {
// `name` here is the path that arrived, and it is the one value in this payload that must never
// become a metric label: a matched route's path is bounded by the route table, an unmatched one
// is bounded by nothing at all, and a scanner walking /aaa, /aab, /aac is a memory leak with a
// metrics backend attached. So the event carries a bounded `route` as well, and so does the
// `request:end` that follows it, rather than leaving every consumer to invent the same fallback
// and some of them to get it wrong.
if (trace) trace.route = UNMATCHED_ROUTE;
if (bus?.hasListeners('route:unmatched')) if (bus?.hasListeners('route:unmatched'))
bus.emit('route:unmatched', { bus.emit('route:unmatched', {
name: `${req.method} ${path}`, name: `${req.method} ${path}`,
route: UNMATCHED_ROUTE,
method: req.method, method: req.method,
requestId: req.requestId, requestId: req.requestId,
traceId: req.traceId, traceId: req.traceId,
@@ -342,7 +410,7 @@ async function dispatch(
traceId: req.traceId, traceId: req.traceId,
}); });
} catch (error) { } catch (error) {
result = renderError(error, req, opts?.onError); result = renderError(error, req, opts?.onError, opts?.logger);
} }
if (isStreamResult(result)) { if (isStreamResult(result)) {
+43
View File
@@ -0,0 +1,43 @@
/**
* Per-server/adapter request budget.
*
* `acquire()` reserves one in-flight request slot. `release()` returns that slot when routing and
* handler execution finishes; a returned stream does not hold the slot for the stream's lifetime.
*/
export interface RequestGate {
/**
* Whether a budget is actually configured.
*
* Exposed rather than left for each adapter to re-derive from `opts`, because the gate is what
* knows: `acquire()` returns `true` unconditionally when there is no limit, so a caller reading
* only its result cannot tell "admitted" from "not counting", and pays for the bookkeeping either
* way. `maxConcurrentRequests` is opt-in, so for most applications this is `false` and every
* per-request cost behind it should be skipped entirely.
*/
limited: boolean;
acquire(): boolean;
release(): void;
}
/** Creates an unlimited gate when `limit` is undefined or non-positive. */
export function createRequestGate(limit: number | undefined): RequestGate {
let active = 0;
const limited = limit !== undefined && limit > 0;
return {
limited,
acquire(): boolean {
if (limit === undefined || limit <= 0) return true;
if (active >= limit) return false;
active++;
return true;
},
release(): void {
if (limit === undefined || limit <= 0) return;
if (active > 0) active--;
},
};
}
+95 -22
View File
@@ -1,15 +1,24 @@
import type http from 'http'; import type http from 'http';
import type https from 'https'; import type https from 'https';
import { createRequestGate } from './request-gate';
import { renderError, type ErrorRequest } from '../transformers'; import { renderError, type ErrorRequest } from '../transformers';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { buildSecurityHeaders, resolveCors } from '../security';
import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request'; import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
import { pipeStream } from './stream'; import { pipeStream } from './stream';
import { attachWs } from './ws'; import { attachWs } from './ws';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders } from './headers';
import { handle, correlateRequest } from './core'; import {
handle,
correlateRequest,
computeInjected,
emitShedPair,
watchingRequests,
type HandleResult,
type Preflight,
} from './core';
import type { BodyFailure, BodyReader } from './body'; import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import { nodeRequire } from '../node-require';
interface HandlerConfig { interface HandlerConfig {
routes: RouteDef[]; routes: RouteDef[];
@@ -43,17 +52,29 @@ export function createHttpServer(
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe // Node http/https are loaded lazily so importing createApp stays edge/workerd-safe
// (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen(). // (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen().
// eslint-disable-next-line @typescript-eslint/no-require-imports const nodeHttp = nodeRequire<typeof import('http')>('http');
const nodeHttp = require('http') as typeof import('http'); const nodeHttps = nodeRequire<typeof import('https')>('https');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const nodeHttps = require('https') as typeof import('https');
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
const server: http.Server = (opts?.tls const server: http.Server = (opts?.tls
? nodeHttps.createServer(opts.tls as https.ServerOptions, handler) ? nodeHttps.createServer(opts.tls as https.ServerOptions, handler)
: nodeHttp.createServer(handler)) as unknown as http.Server; : nodeHttp.createServer(handler)) as unknown as http.Server;
const maxConnections = opts?.limits?.maxConnections ?? 1000; const maxConnections = opts?.limits?.maxConnections ?? 1000;
if (maxConnections > 0) server.maxConnections = maxConnections;
if (maxConnections > 0) {
server.maxConnections = maxConnections;
let lastDropWarn = 0;
server.on('drop', ({ remoteAddress, remotePort }) => {
const now = Date.now();
if (now - lastDropWarn < 60_000) return;
lastDropWarn = now;
opts?.logger?.warn(
`maxConnections (${maxConnections}) reached \u2014 dropped connection from ${remoteAddress ?? 'unknown'}:${remotePort ?? 'unknown'}`,
{ maxConnections, remoteAddress, remotePort },
);
});
}
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
@@ -73,6 +94,7 @@ function createRequestHandler(cfg: HandlerConfig) {
const { routes, bus, opts, trustProxy } = cfg; const { routes, bus, opts, trustProxy } = cfg;
// Built once per server, not once per request — see `BodyReader`. // Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts); const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => { return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
// Install the security-header patch BEFORE any routing/response so every path // Install the security-header patch BEFORE any routing/response so every path
@@ -80,23 +102,74 @@ function createRequestHandler(cfg: HandlerConfig) {
const secure = deriveSecure(req, trustProxy); const secure = deriveSecure(req, trustProxy);
// Derived before the body is read, so a 413 rejected below still carries an identity. // Derived before the body is read, so a 413 rejected below still carries an identity.
const correlation = correlateRequest(req.headers); const correlation = correlateRequest(req.headers);
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) }; // One computation for the whole request: this object is patched into every response below, and
// handed to `handle()` so routing does not derive it a second time — `security` is pure, but
// `cors.origins` may be a predicate with a network call in it.
const injected = computeInjected(opts, { secure, headers: req.headers });
patchResponseHeaders(res, injected); patchResponseHeaders(res, injected);
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily let result: HandleResult | Preflight;
// by reference at writeHead time, so keys added here still land on every response. let acquired = false;
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); const watching = watchingRequests(bus);
const startedAt = watching ? performance.now() : 0;
const result = await handle(routes, opts, { try {
...correlation, if (!gate.acquire()) {
method: req.method ?? 'GET', if (watching)
url: req.url ?? '/', emitShedPair(
headers: req.headers, bus,
readBody, {
source: req, method: req.method ?? 'GET',
secure, url: req.url ?? '/',
ip: deriveIp(req, trustProxy), requestId: correlation.requestId,
}); traceId: correlation.traceId,
},
startedAt,
);
res.writeHead(503, {
'content-type': 'application/json',
'retry-after': '1',
connection: 'close',
});
res.end(JSON.stringify({ error: 'Service Unavailable' }));
return;
}
// Both the flag and the listener are skipped when no budget is configured, which is most
// applications: `maxConcurrentRequests` is opt-in and unlimited by default. A closure and an
// EventEmitter registration per request, on the hot path, for a feature that is off is a cost
// with nothing on the other side of it.
if (gate.limited) {
acquired = true;
res.once('close', () => {
if (!acquired) return;
acquired = false;
gate.release();
});
}
result = await handle(
routes,
opts,
{
...correlation,
method: req.method ?? 'GET',
url: req.url ?? '/',
headers: req.headers,
readBody,
source: req,
secure,
ip: deriveIp(req, trustProxy),
},
injected,
);
} finally {
if (acquired) {
acquired = false;
gate.release();
}
}
if ('preflight' in result) { if ('preflight' in result) {
res.writeHead(204, result.preflight); res.writeHead(204, result.preflight);
@@ -131,7 +204,7 @@ function readRequestBytes(
return readBodyBytes(req, limit).then( return readBodyBytes(req, limit).then(
(bytes) => ({ bytes }), (bytes) => ({ bytes }),
(error: unknown) => { (error: unknown) => {
const rendered = renderError(error, errorRequest(req), opts?.onError); const rendered = renderError(error, errorRequest(req), opts?.onError, opts?.logger);
return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } }; return { fail: { ...rendered, headers: { ...rendered.headers, connection: 'close' } } };
}, },
); );
+125
View File
@@ -0,0 +1,125 @@
// src/http/signals-shutdown.ts — SIGINT/SIGTERM → close(), opt-in, one spelling per runtime.
import type { Logger } from '../logger';
/** The two signals an orchestrator actually sends: Ctrl-C, and every container runtime's stop. */
const SIGNALS = ['SIGINT', 'SIGTERM'] as const;
type Signal = (typeof SIGNALS)[number];
interface SignalApi {
runtime: string;
on(signal: Signal, handler: () => void): void;
off(signal: Signal, handler: () => void): void;
exit(code: number): void;
}
interface DenoSignals {
addSignalListener(signal: Signal, handler: () => void): void;
removeSignalListener(signal: Signal, handler: () => void): void;
exit(code: number): void;
}
interface ProcessSignals {
on(signal: Signal, handler: () => void): unknown;
off?(signal: Signal, handler: () => void): unknown;
removeListener?(signal: Signal, handler: () => void): unknown;
exit(code: number): void;
}
/**
* Deno first, on purpose. Its `node:process` shim does carry signal support, but `Deno.exit` and
* `Deno.addSignalListener` are the APIs Deno itself documents, and a listener registered natively
* is the one `removeSignalListener` can take back — which matters here, because a Deno signal
* listener holds the process open until it is removed. Node and Bun share `process`.
*/
function signalApi(): SignalApi | undefined {
const deno = (globalThis as { Deno?: DenoSignals }).Deno;
if (typeof deno?.addSignalListener === 'function')
return {
runtime: 'deno',
on: (signal, handler) => deno.addSignalListener(signal, handler),
off: (signal, handler) => deno.removeSignalListener(signal, handler),
exit: (code) => deno.exit(code),
};
const proc = (globalThis as { process?: ProcessSignals }).process;
if (typeof proc?.on === 'function' && typeof proc.exit === 'function') {
const remove = proc.off ?? proc.removeListener;
return {
runtime: 'node',
on: (signal, handler) => void proc.on(signal, handler),
off: (signal, handler) => void remove?.call(proc, signal, handler),
exit: (code) => proc.exit(code),
};
}
return undefined;
}
/**
* Registers SIGINT/SIGTERM to run `close` and then exit. Returns the function that takes those
* handlers back off — which is not optional bookkeeping on Deno, where a live signal listener keeps
* the process from exiting on its own.
*
* The close is expected to unregister first thing, which leaves a **second signal falling through
* to the platform default** — an immediate end to the process, teardown or no teardown. That is
* the escape hatch, and it is deliberate: a developer pressing Ctrl-C twice wants out now, and
* swallowing it for the length of a 10s shutdown budget would read as a hang. An orchestrator
* sends `SIGTERM` once and then `SIGKILL`, so it never reaches this path.
*
* If the close throws, the process still exits — with 1, because a shutdown that failed halfway is
* not a clean one and an orchestrator should be told.
*/
export function installSignalHandlers(close: () => Promise<void>, logger: Logger): () => void {
const api = signalApi();
if (!api) {
logger.warn(
'handleSignals: this runtime delivers no process signals, so nothing was registered — call close() yourself',
);
return () => {};
}
const registered: Array<[Signal, () => void]> = [];
const remove = (): void => {
while (registered.length) {
const [signal, handler] = registered.pop()!;
api.off(signal, handler);
}
};
for (const signal of SIGNALS) {
const handler = (): void => {
logger.info(`${signal} received — closing`, { signal, runtime: api.runtime });
void close().then(
() => api.exit(0),
(error: unknown) => {
logger.error(`shutdown failed after ${signal}`, {
signal,
err: error instanceof Error ? error.message : String(error),
});
api.exit(1);
},
);
};
try {
api.on(signal, handler);
registered.push([signal, handler]);
} catch (error) {
// Deno throws for SIGTERM on Windows, where the signal does not exist. Registering what the
// platform does have beats refusing to start over the one it does not.
logger.warn(`handleSignals: ${signal} is unavailable on this platform — skipping it`, {
signal,
err: error instanceof Error ? error.message : String(error),
});
}
}
return remove;
}
+4
View File
@@ -5,11 +5,13 @@ import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
import type { WsRequest, WsSocket } from './ws-core'; import type { WsRequest, WsSocket } from './ws-core';
import type { StaticResolver } from '../views'; import type { StaticResolver } from '../views';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import type { Logger } from '../logger';
/** Per-request and per-server resource ceilings applied by the server. */ /** Per-request and per-server resource ceilings applied by the server. */
export interface RequestLimits { export interface RequestLimits {
maxBodyBytes?: number; // default 1_000_000 maxBodyBytes?: number; // default 1_000_000
maxConnections?: number; // default 1000; <= 0 means unlimited (Node only) maxConnections?: number; // default 1000; <= 0 means unlimited (Node only)
maxConcurrentRequests?: number; // default unlimited; <= 0 means unlimited
requestTimeoutMs?: number; // default 30_000 requestTimeoutMs?: number; // default 30_000
headersTimeoutMs?: number; // default 10_000 headersTimeoutMs?: number; // default 10_000
keepAliveTimeoutMs?: number; // default 5_000 keepAliveTimeoutMs?: number; // default 5_000
@@ -24,6 +26,8 @@ export interface HttpOptions {
* a separate channel for it. * a separate channel for it.
*/ */
bus?: Bus; bus?: Bus;
/** Where this server writes diagnostics. Optional because `createHttpServer` takes no options at all in tests. */
logger?: Logger;
limits?: RequestLimits; limits?: RequestLimits;
streams?: Set<() => void>; streams?: Set<() => void>;
tls?: TlsOptions; tls?: TlsOptions;
+80 -22
View File
@@ -1,5 +1,14 @@
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import { handle, computeInjected, correlateRequest, type HandleResult } from './core'; import { createRequestGate } from './request-gate';
import {
handle,
computeInjected,
correlateRequest,
emitShedPair,
watchingRequests,
type HandleResult,
type Preflight,
} from './core';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders } from './headers';
import type { BodyFailure, BodyReader, MaybePromise } from './body'; import type { BodyFailure, BodyReader, MaybePromise } from './body';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
@@ -68,7 +77,7 @@ function readFetchBytes(
url: url.pathname + url.search, url: url.pathname + url.search,
headers: headersToRecord(request.headers), headers: headersToRecord(request.headers),
}; };
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError) }; return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
} }
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) }; return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
@@ -127,6 +136,7 @@ function outcomeToResponse(result: HandleResult): Response {
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
// Built once per server, not once per request — see `BodyReader`. // Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts); const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
return async (request: Request): Promise<Response> => { return async (request: Request): Promise<Response> => {
const url = new URL(request.url); const url = new URL(request.url);
@@ -139,29 +149,77 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
// this adapter builds itself — carries the same security/CORS headers every other one does. // this adapter builds itself — carries the same security/CORS headers every other one does.
const injected = computeInjected(opts, { secure, headers }); const injected = computeInjected(opts, { secure, headers });
const result = await handle(routes, opts, { let result: HandleResult | Preflight;
...correlation, let acquired = false;
method: request.method, const watching = watchingRequests(opts?.bus);
url: path, const startedAt = watching ? performance.now() : 0;
headers,
readBody, try {
source: request, if (!gate.acquire()) {
secure, if (watching)
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is emitShedPair(
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket opts!.bus!,
// peer address to fall back to on the fetch path, so the untrusted case is simply ''. {
ip: opts?.trustProxy method: request.method,
? String(headers['x-forwarded-for'] ?? '') url: path,
.split(',')[0] requestId: correlation.requestId,
.trim() traceId: correlation.traceId,
: '', },
}); startedAt,
);
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
status: 503,
headers: mergeInjectedHeaders(
{
'content-type': 'application/json',
'retry-after': '1',
},
injected,
),
});
}
acquired = gate.limited;
result = await handle(
routes,
opts,
{
...correlation,
method: request.method,
url: path,
headers,
readBody,
source: request,
secure,
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
// is simply ''.
ip: opts?.trustProxy
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
},
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request.
injected,
);
} finally {
// Release when routing/handling finishes, not when a returned stream finishes.
// Long-lived streams therefore do not permanently consume the request budget.
if (acquired) gate.release();
}
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and // Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
// so picks up the same authoritative security headers `injected` carries (Node's writeHead patch // so picks up the same authoritative security headers `injected` carries.
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
if ('preflight' in result) { if ('preflight' in result) {
return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) }); return new Response(null, {
status: 204,
headers: mergeInjectedHeaders(result.preflight, injected),
});
} }
return outcomeToResponse(result); return outcomeToResponse(result);
+2 -2
View File
@@ -1,6 +1,7 @@
import { channel } from '../channel'; import { channel } from '../channel';
import type { App } from '../app/types'; import type { App } from '../app/types';
import type { WsRequest, WsSocket } from './ws-core'; import type { WsRequest, WsSocket } from './ws-core';
import { nodeRequire } from '../node-require';
/** /**
* Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket * Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket
@@ -123,8 +124,7 @@ export function loadWebSocketCtor(): SocketCtor {
if (platform) return platform; if (platform) return platform;
// eslint-disable-next-line @typescript-eslint/no-require-imports return nodeRequire<SocketCtor>('ws');
return require('ws') as SocketCtor;
} }
/** /**
+2 -2
View File
@@ -3,14 +3,14 @@ import { channel } from '../channel';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core'; import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
import type { WsRouteDef, MeshControl } from './types'; import type { WsRouteDef, MeshControl } from './types';
import { nodeRequire } from '../node-require';
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
function loadWss(): any | null { function loadWss(): any | null {
try { try {
// `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket // `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket
// support don't fail. When absent this throws and we fall back to null (501 on upgrade). // support don't fail. When absent this throws and we fall back to null (501 on upgrade).
// eslint-disable-next-line @typescript-eslint/no-require-imports return nodeRequire<{ WebSocketServer: unknown }>('ws').WebSocketServer;
return require('ws').WebSocketServer;
} catch { } catch {
return null; return null;
} }
+6 -3
View File
@@ -40,8 +40,10 @@ export {
Options, Options,
Html, Html,
} from './metadata'; } from './metadata';
export type { Transport, HttpMethod, RouteDecorator } from './metadata'; export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata';
export type { Plugin } from './plugin'; export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin';
export type { Hooks } from './app';
export type { TeardownFn } from './lifecycle';
// Transformers & error signals // Transformers & error signals
export { JsonTransformer } from './transformers'; export { JsonTransformer } from './transformers';
@@ -58,7 +60,7 @@ export {
// Bus & flow // Bus & flow
export { Bus } from './bus'; export { Bus } from './bus';
export type { LifecycleEvent, EventPayload, Correlation } from './bus'; export type { LifecycleEvent, EventPayload, Correlation, Events } from './bus';
export { flow, Flow } from './flow'; export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow'; export type { StepFn, CompiledFlow } from './flow';
@@ -79,6 +81,7 @@ export type { StreamEncoder } from './encoders';
// HTTP, security & validation // HTTP, security & validation
export type { RequestLimits } from './http'; export type { RequestLimits } from './http';
export { UNMATCHED_ROUTE } from './http/core';
export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export type { TlsOptions, CorsOptions, SecurityOptions } from './security';
export type { UploadedFile, MultipartBody } from './multipart'; export type { UploadedFile, MultipartBody } from './multipart';
export type { StandardSchemaV1 } from './standard-schema'; export type { StandardSchemaV1 } from './standard-schema';
+2 -2
View File
@@ -1,6 +1,7 @@
// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency. // src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency.
import { Readable } from 'stream'; import { Readable } from 'stream';
import { HttpError } from './signals'; import { HttpError } from './signals';
import { nodeRequire } from './node-require';
/** A single uploaded file part decoded from a multipart body. */ /** A single uploaded file part decoded from a multipart body. */
export interface UploadedFile { export interface UploadedFile {
@@ -67,8 +68,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm
try { try {
// `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is // `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is
// lazy-required and its absence surfaces as a clear 501 rather than a load-time crash. // lazy-required and its absence surfaces as a clear 501 rather than a load-time crash.
// eslint-disable-next-line @typescript-eslint/no-require-imports return nodeRequire('busboy');
return require('busboy');
} catch { } catch {
return null; return null;
} }
+44
View File
@@ -0,0 +1,44 @@
// src/node-require.ts — one `require` that survives being published as source.
type Require = <T>(id: string) => T;
interface NodeProcess {
cwd?: () => string;
getBuiltinModule?: (id: string) => unknown;
}
let cached: Require | null | undefined;
function resolveRequire(): Require | undefined {
// The CJS build has a native one, and tsup gives the ESM build one through a `createRequire`
// banner (tsup.config.ts). Both npm paths stop here.
if (typeof require === 'function') return require as Require;
// JSR publishes `src/` and runs no bundler, so on that path nothing ever defined `require`.
// `process.getBuiltinModule` is the way back: Node 22.3+, Deno and Bun all expose it, and all
// three do it *synchronously* — which is the whole requirement, since every caller here sits on
// a sync path that a dynamic `import()` could not serve.
const proc = (globalThis as { process?: NodeProcess }).process;
const nodeModule = proc?.getBuiltinModule?.('node:module') as
{ createRequire?: (from: string) => Require } | undefined;
if (!nodeModule?.createRequire || !proc?.cwd) return undefined;
// Resolve from the application's directory rather than from this file: served from JSR this
// module lives under an `https://` URL with no `node_modules` beneath it, while an optional peer
// dependency such as `busboy` is installed in the app that asked for it.
return nodeModule.createRequire(`${proc.cwd()}/`);
}
/**
* Loads a Node builtin or an installed package, synchronously.
*
* Throws on a runtime that can offer neither — workerd, where `node:fs` and `busboy` are genuinely
* out of reach. Every caller already guards for that and reports it in its own terms; what they
* must not do is report it when the module is in fact reachable, which is what a bare `require`
* caused on JSR by failing with `ReferenceError` before any of them was consulted.
*/
export function nodeRequire<T>(id: string): T {
if (cached === undefined) cached = resolveRequire() ?? null;
if (cached === null) throw new Error(`cannot load '${id}': this runtime provides no CommonJS require`);
return cached<T>(id);
}
+30 -11
View File
@@ -3,6 +3,7 @@ import { renderError, type ErrorRenderer } from './transformers';
import { isAsyncIterable } from './channel'; import { isAsyncIterable } from './channel';
import type { TransformerFn, Transport } from './metadata'; import type { TransformerFn, Transport } from './metadata';
import { TransportMismatchError } from './signals'; import { TransportMismatchError } from './signals';
import type { Logger } from './logger';
/** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */ /** A single step in a request pipeline: a named unit whose `run` merges its output into the shared context. */
export interface PipelineStep { export interface PipelineStep {
@@ -113,9 +114,10 @@ export async function runPipeline(args: {
bus: Bus; bus: Bus;
transport: Transport; transport: Transport;
onError?: ErrorRenderer; onError?: ErrorRenderer;
logger?: Logger;
correlation?: Correlation; correlation?: Correlation;
}): Promise<PipelineResult> { }): Promise<PipelineResult> {
const { steps, handler, transformer, seed, bus, transport, onError, correlation = {} } = args; const { steps, handler, transformer, seed, bus, transport, onError, logger, correlation = {} } = args;
// context is intentionally `any`: each step merges arbitrary keys into the accumulator // context is intentionally `any`: each step merges arbitrary keys into the accumulator
let context: any = { ...seed }; let context: any = { ...seed };
@@ -137,16 +139,33 @@ export async function runPipeline(args: {
const transformed = transformer(result); const transformed = transformer(result);
return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body }; return { status: transformed.status ?? 200, headers: transformed.headers ?? {}, body: transformed.body };
} catch (error) { } catch (error) {
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
// what produces a trace that says a request failed without saying where.
if (bus.hasListeners('request:failed'))
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, ...correlation });
const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> }; const req = (context.req ?? {}) as { method?: string; url?: string; headers?: Record<string, unknown> };
return renderError( let status: number | undefined;
error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never }, try {
onError, const rendered = renderError(
); error,
{ method: req.method ?? '', url: req.url ?? '', headers: (context.headers ?? req.headers ?? {}) as never },
onError,
logger,
);
status = rendered.status;
return rendered;
} finally {
// Both fire for a failing step, deliberately: `request:step:error` above marks the span,
// this marks the trace. A tracing exporter needs each, and only emitting the outer one is
// what produces a trace that says a request failed without saying where.
//
// Emitted after the render rather than before it, because the status is only decided there:
// `onError` may turn any throw into any status, so deriving one from the error would be a
// guess that a custom renderer makes wrong.
//
// In `finally` rather than after the call, so that nothing between here and the emit can cost
// us the only record that a request failed. `renderError` already contains a throwing
// `onError` and degrades to the built-in rendering, so this is a second line rather than the
// first — but a failure whose reporting is what broke is the worst one to lose.
if (bus.hasListeners('request:failed'))
bus.emit('request:failed', { name: correlation.route ?? 'pipeline', error, status, ...correlation });
}
} }
} }
+12 -1
View File
@@ -14,7 +14,18 @@ export interface ScopeNode {
export interface ScopeApi { export interface ScopeApi {
add(node: ScopeNode): void; add(node: ScopeNode): void;
} }
/** The capabilities handed to a plugin: event subscription, node registration, and teardown. */ /**
* The capabilities handed to a plugin: event subscription, node registration, and teardown.
*
* This is the home for observation, and the reason is the pairing: `bus.on` arrives next to
* `onShutdown`, so whatever a plugin subscribes to it can also release. A graph node can reach the
* same read-only slice through `@needs('events')`, but it gets the subscribe half without the
* unsubscribe half — and a `@Step` reaching it would register a listener per request.
*
* The `Bus` itself is deliberately not here and is not a graph token either: handing over `emit`
* would turn a one-way observation channel into something any node can forge events on.
* `@needs('bus')` fails at boot and says so.
*/
export interface PluginApi { export interface PluginApi {
bus: { on: Bus['on'] }; bus: { on: Bus['on'] };
scope: ScopeApi; scope: ScopeApi;
+26 -5
View File
@@ -1,5 +1,7 @@
// src/security.ts — pure header computation, no server deps // src/security.ts — pure header computation, no server deps
import type { Logger } from './logger';
/** TLS material for an HTTPS server. */ /** TLS material for an HTTPS server. */
export interface TlsOptions { export interface TlsOptions {
key: Buffer | string; key: Buffer | string;
@@ -75,22 +77,36 @@ export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: bo
return headers; return headers;
} }
function originAllowed(spec: CorsOptions['origins'], origin: string): boolean { function originAllowed(spec: CorsOptions['origins'], origin: string, logger?: Logger): boolean {
if (spec === '*') return true; if (spec === '*') return true;
if (typeof spec === 'function') return spec(origin);
if (Array.isArray(spec)) return spec.includes(origin); if (Array.isArray(spec)) return spec.includes(origin);
return spec === origin; if (typeof spec !== 'function') return spec === origin;
// The predicate is user code on the request path — a Redis allowlist, a tenant lookup — and it runs
// before the region where errors convert to a response, so a throw here would leave the request
// listener as an unhandled rejection and take the process down. Deny instead: a lookup that failed
// has not said yes, and a broken allowlist must never widen into an open one.
try {
return spec(origin);
} catch (error) {
logger?.warn(`cors: the origins predicate threw for ${origin} — treating the origin as not allowed`, {
origin,
err: error instanceof Error ? error.message : String(error),
});
return false;
}
} }
/** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */ /** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */
export function resolveCors( export function resolveCors(
opts: CorsOptions, opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> }, req: { headers: Record<string, string | string[] | undefined> },
logger?: Logger,
): Headers { ): Headers {
const headers: Headers = {}; const headers: Headers = {};
const rawOrigin = req.headers['origin']; const rawOrigin = req.headers['origin'];
const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin; const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin;
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return headers; if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin, logger)) return headers;
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic. // credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
if (opts.credentials) { if (opts.credentials) {
@@ -112,8 +128,13 @@ export function resolveCors(
export function corsPreflightHeaders( export function corsPreflightHeaders(
opts: CorsOptions, opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> }, req: { headers: Record<string, string | string[] | undefined> },
resolved?: Headers,
): Headers { ): Headers {
const headers = resolveCors(opts, req); // The caller has almost always resolved CORS already, one layer up, to seed the headers every
// response carries. Re-deriving here would consult `origins` a second time for the same request —
// and `origins` may be a predicate doing a network lookup. Copied rather than used in place: the
// preflight-only keys below belong to this 204, not to the shared object.
const headers: Headers = { ...resolved };
if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204 if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204
headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join( headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(
', ', ', ',
+29 -2
View File
@@ -1,6 +1,7 @@
import { isHttpError, ValidationError } from './signals'; import { isHttpError, ValidationError } from './signals';
import type { TransformerFn } from './metadata'; import type { TransformerFn } from './metadata';
import { flattenPath } from './standard-schema'; import { flattenPath } from './standard-schema';
import type { Logger } from './logger';
/** A ready-to-send HTTP response. */ /** A ready-to-send HTTP response. */
export interface ErrorResponse { export interface ErrorResponse {
@@ -60,6 +61,32 @@ export function errorToResponse(error: unknown): ErrorResponse {
} }
/** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */ /** Render an error through the optional user {@link ErrorRenderer}, falling back to {@link errorToResponse}. */
export function renderError(error: unknown, req: ErrorRequest, onError?: ErrorRenderer): ErrorResponse { export function renderError(
return onError?.(error, req) ?? errorToResponse(error); error: unknown,
req: ErrorRequest,
onError?: ErrorRenderer,
logger?: Logger,
): ErrorResponse {
if (!onError) return errorToResponse(error);
// `onError` is user code, it runs on the request path, and it runs *after something already went
// wrong* — which makes an unguarded throw here the worst-timed crash in the framework: the error
// occurs, the code written to report it fails, and the process ends instead of degrading.
//
// It is also easy to reach. This renders the 404 too, not just a thrown handler, so an app with a
// custom renderer and no matching route is one request away from exiting.
//
// A renderer that throws falls back to the built-in rendering, which is exactly what the option
// overrides and therefore the honest thing to fall back to: the original error still gets its
// response. The renderer's own failure is reported separately, because it is a different error
// from the request's and a reader chasing the wrong one loses an afternoon.
try {
return onError(error, req) ?? errorToResponse(error);
} catch (rendererError) {
logger?.error('createApp({ onError }) threw while rendering — falling back to the built-in renderer', {
err: rendererError instanceof Error ? rendererError.message : String(rendererError),
rendering: error instanceof Error ? error.message : String(error),
});
return errorToResponse(error);
}
} }
+8 -9
View File
@@ -3,6 +3,7 @@
import type { TransformerFn } from './metadata'; import type { TransformerFn } from './metadata';
import type { HtmlMeta } from './metadata'; import type { HtmlMeta } from './metadata';
import { nodeRequire } from './node-require';
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */ /** Escape the five HTML-significant characters so interpolated data can't inject markup. */
export function escapeHtml(s: string): string { export function escapeHtml(s: string): string {
@@ -58,12 +59,12 @@ export interface ViewsContext {
/** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is. /** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is.
* node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe * node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe
* (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */ * (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes.
* Unguarded on purpose: `@Html('file')` cannot degrade into anything useful, so a runtime with no
* filesystem should hear about it here rather than at the first request. */
function readViewFile(views: string | undefined, path: string): string { function readViewFile(views: string | undefined, path: string): string {
// eslint-disable-next-line @typescript-eslint/no-require-imports const nodePath = nodeRequire<typeof import('node:path')>('node:path');
const nodePath = require('node:path') as typeof import('node:path'); const fs = nodeRequire<typeof import('node:fs')>('node:fs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
const fs = require('node:fs') as typeof import('node:fs');
const base = views ?? process.cwd(); const base = views ?? process.cwd();
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path); const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
@@ -94,10 +95,8 @@ export function buildStaticResolver(root: string | true): StaticResolver {
let nodePath: typeof import('node:path'); let nodePath: typeof import('node:path');
try { try {
// eslint-disable-next-line @typescript-eslint/no-require-imports fs = nodeRequire('node:fs');
fs = require('node:fs'); nodePath = nodeRequire('node:path');
// eslint-disable-next-line @typescript-eslint/no-require-imports
nodePath = require('node:path');
} catch { } catch {
throw new Error( throw new Error(
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.', '`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
+6 -2
View File
@@ -603,7 +603,11 @@ describe('rooms auto-provide', () => {
expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true }); expect(await fetch(`http://127.0.0.1:${port}/api/r/x`).then((r) => r.json())).toEqual({ ok: true });
s.close(); s.close();
}); });
it('a user-declared rooms provider wins (no duplicate-name throw)', () => { // This used to be allowed, and the user's provider silently replaced the framework's. The same
// held for `logger`, where every `@needs('logger')` in the app then got something that was not
// the logger core writes to — a divergence discovered from a log line that never appeared.
// Framework token names are reserved now, and taking one is a boot error.
it('refuses a user-declared rooms provider instead of silently replacing the built-in', () => {
@Provider({ provides: 'rooms' }) @Provider({ provides: 'rooms' })
class MyRooms { class MyRooms {
provide() { provide() {
@@ -618,7 +622,7 @@ describe('rooms auto-provide', () => {
} }
@Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] }) @Module({ mountpoint: '/api', providers: [MyRooms], controllers: [Ctl] })
class M {} class M {}
expect(() => createApp({ modules: [M] })).not.toThrow(); expect(() => createApp({ modules: [M] })).toThrow(/'rooms' is reserved by the framework/);
}); });
}); });
+73
View File
@@ -0,0 +1,73 @@
// The three legitimate ways to reach the bus, exercised together in one app.
//
// `bus` became a reserved name and the `Bus` itself is still not a graph token, so this file's job
// is to prove that what closed is only the wrong door: observation from outside, from a plugin and
// from inside the graph all still work, and only `emit` stays where it was.
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp, Route, Get, Module, needs } from '../src/index';
import type { Events, Plugin } from '../src/index';
@Route('/b')
class Ctl {
@Get('/x') x(@needs('events') events: Events) {
// Reaching it per request is allowed; *subscribing* per request is the thing the docs warn
// about, and nothing here does that.
return { hasOn: typeof events.on === 'function' };
}
}
describe('reaching the bus', () => {
it('works from outside, from a plugin and from the graph, all at once', async () => {
const fromOutside: string[] = [];
const fromPlugin: string[] = [];
const observer: Plugin = (api) => {
api.bus.on('request:end', (e) => fromPlugin.push(e.route ?? ''));
};
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M], plugins: [observer] });
// 1. from outside: the public `app.bus`, which keeps `emit` too.
app.bus.on('request:end', (e) => fromOutside.push(e.route ?? ''));
// 3. from the graph: the handler receives `events` and reports its shape.
const res = await app.fetch(new Request('http://x/b/x'));
expect(await res.json()).toEqual({ hasOn: true });
expect(fromOutside).toEqual(['/b/x']);
expect(fromPlugin).toEqual(['/b/x']);
await app.close();
});
it('keeps emit outside the graph and outside plugins, and only there', async () => {
let injected: Events | undefined;
const seen: string[] = [];
@Route('/e')
class Grab {
@Get('/x') x(@needs('events') events: Events) {
injected = events;
return {};
}
}
@Module({ mountpoint: '/', controllers: [Grab] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/x'));
// The graph's slice cannot forge an event...
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
// ...while the application that owns the app still can, which is what `app.bus` is for.
app.bus.on('plugin:mounted', (e) => seen.push(e.name));
app.bus.emit('plugin:mounted', { name: 'from the owner' });
expect(seen).toEqual(['from the owner']);
await app.close();
});
});
+51
View File
@@ -0,0 +1,51 @@
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
// `scripts/changelog-section.mjs` writes the body of every GitHub release. It is the only place where
// a mistake is invisible until it is already published, so its boundaries are pinned here rather than
// checked by eye at release time.
const SCRIPT = resolve(process.cwd(), 'scripts/changelog-section.mjs');
const section = (version: string, tag?: string): string =>
execFileSync('node', [SCRIPT, version, ...(tag ? [tag] : [])], { encoding: 'utf8' });
const changelog = readFileSync(resolve(process.cwd(), 'CHANGELOG.md'), 'utf8');
const released = [...changelog.matchAll(/^## \[(\d[^\]]*)\]/gm)].map(([, v]) => v);
describe('changelog section extraction', () => {
it('finds every released version', () => {
expect(released.length).toBeGreaterThan(0);
for (const version of released) {
expect(section(version).trim(), version).not.toBe('');
}
});
it('stops at the next version, so a section never carries the one below it', () => {
for (const version of released) {
expect(section(version), version).not.toMatch(/^## \[/m);
}
});
// The oldest section is the one at risk: nothing follows it but the `[label]: url` block that
// defines the compare links, which belongs to no version and once ended up inside it.
it('stops at the link-reference block', () => {
for (const version of released) {
expect(section(version), version).not.toMatch(/^\[[^\]]+\]:\s+\S/m);
}
});
// A release body resolves relative links against the release page, not the repository, so every
// link has to be absolute by the time it is published.
it('rewrites relative links against the tag', () => {
for (const version of released) {
const links = [...section(version, `v${version}`).matchAll(/\]\(([^)\s]+)\)/g)].map(([, url]) => url);
expect(links.filter((url) => !url.startsWith('http')), version).toEqual([]);
}
});
it('fails rather than publishing an empty body for a version it cannot find', () => {
expect(() => section('0.0.0-nonexistent')).toThrow();
});
});
+4 -1
View File
@@ -29,7 +29,10 @@ it('snapshots connection metadata before Deno invalidates the upgraded request',
}); });
const upgrade = vi.fn().mockResolvedValue(undefined); const upgrade = vi.fn().mockResolvedValue(undefined);
serveDeno({ upgrade } as unknown as App); // `handleSignals` is a pass-through here: this test is about upgrade metadata, and the identity
// it returns is exactly what `createApp` returns when `handleSignals` is left off.
const handleSignals = <T,>(closer: T): T => closer;
serveDeno({ upgrade, handleSignals } as unknown as App);
const info = { const info = {
get remoteAddr() { get remoteAddr() {
if (upgraded) throw new TypeError('Request closed'); if (upgraded) throw new TypeError('Request closed');
+53
View File
@@ -0,0 +1,53 @@
// `createApp({ handleSignals: true })` under the real Deno runtime.
//
// Deno is the runtime this option exists for. Node and Bun share `process.on`/`process.exit`; Deno
// has `Deno.addSignalListener`/`Deno.exit`, and its listeners hold the process open until removed —
// so an app that closed itself and forgot to unregister would hang here and nowhere else.
//
// Run with: npm run test:deno
import { assert, assertEquals } from 'jsr:@std/assert';
const HARNESS = 'test/interop/_signal-app-deno.ts';
async function run(): Promise<{ code: number; lines: string[] }> {
const child = new Deno.Command('deno', {
args: ['run', '--allow-all', '--no-check', HARNESS],
stdout: 'piped',
stderr: 'inherit',
}).spawn();
const lines: string[] = [];
let buffered = '';
let signalled = false;
const reader = child.stdout.pipeThrough(new TextDecoderStream()).getReader();
const pump = (async () => {
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffered += value;
const parts = buffered.split('\n');
buffered = parts.pop() ?? '';
for (const line of parts.filter(Boolean)) {
lines.push(line);
if (!signalled && line.includes('"ready"')) {
signalled = true;
child.kill('SIGTERM');
}
}
}
})();
const status = await child.status;
await pump;
return { code: status.code, lines };
}
Deno.test('SIGTERM runs teardown and exits 0 through Deno.addSignalListener', async () => {
const { code, lines } = await run();
assert(
lines.some((l) => l.includes('"disposed"')),
`dispose() never ran — got: ${lines.join(' | ')}`,
);
assertEquals(code, 0);
});
+76
View File
@@ -0,0 +1,76 @@
// `@Html` and `static` under the real Deno runtime, importing `src/` the way JSR serves it.
//
// This is the shape the JSR package actually ships: no bundler ran, so tsup's `createRequire`
// banner (tsup.config.ts) never existed and the lazy `require('node:fs')` in `src/views.ts` has
// nothing to resolve. Every other Deno test here imports `src/` too, but none of them touches a
// path that loads a Node builtin lazily — which is how a package that dies at boot on Deno kept a
// green suite. Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals, assertStringIncludes } from 'jsr:@std/assert';
import { createApp, Route, Get, Html, Module } from '../../src/index.ts';
// Committed fixtures rather than a temp dir, so the suite keeps running without `--allow-write`.
const dir = 'test/fixtures/views';
@Route('/')
class Views {
@Get('/dash') @Html('dash.html') dash() {}
@Get('/user') @Html('user.html', { template: true }) user() {
return { name: 'Deno' };
}
}
@Module({ mountpoint: '/', controllers: [Views] })
class M {}
Deno.test("@Html file mode reads the file — the require path resolves without tsup's banner", async () => {
const app = createApp({ modules: [M], views: dir });
const res = await app.fetch(new Request('http://x/dash'));
assertEquals(res.status, 200);
assertEquals(await res.text(), '<h1>Dash</h1>');
await app.close();
});
Deno.test('@Html template mode renders', async () => {
const app = createApp({ modules: [M], views: dir });
const res = await app.fetch(new Request('http://x/user'));
assertStringIncludes(await res.text(), 'Hi Deno');
await app.close();
});
// Deno has a filesystem, so `static` must not report the runtime as the reason for anything.
Deno.test('static: true builds a resolver instead of blaming the runtime', async () => {
const app = createApp({ modules: [], static: dir });
const res = await app.fetch(new Request('http://x/asset.txt'));
assertEquals(res.status, 200);
assertEquals(await res.text(), 'served');
await app.close();
});
// The other half of the shim: `node:fs` above comes from `process.getBuiltinModule`, but `busboy`
// is an npm package and has to be resolved from the application's own `node_modules`. On JSR that
// failed as a `ReferenceError` under the catch that reports "busboy not installed" — the one
// diagnosis guaranteed to send a reader to reinstall a package they already have.
Deno.test('multipart resolves the busboy peer dependency instead of reporting it missing', async () => {
const { createApp: create, Route: R, Post, Module: Mod, body } = await import('../../src/index.ts');
@R('/')
class Upload {
@Post('/up') up(@body() b: { fields: Record<string, string>; files: Record<string, { filename: string }> }) {
return { name: b.fields.name, filename: b.files.file.filename };
}
}
@Mod({ mountpoint: '/', controllers: [Upload] })
class UploadMod {}
const app = create({ modules: [UploadMod] });
const form = new FormData();
form.set('name', 'joe');
form.set('file', new Blob([new Uint8Array([1, 2, 3])], { type: 'image/png' }), 'p.png');
const res = await app.fetch(new Request('http://x/up', { method: 'POST', body: form }));
assertEquals(res.status, 200);
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
await app.close();
});
+73
View File
@@ -80,3 +80,76 @@ describe('HttpError body', () => {
server.close(); server.close();
}); });
}); });
// `onError` is user code, on the request path, running *after something already went wrong*. An
// unguarded throw here was the worst-timed crash in the framework: the error occurs, the code
// written to report it fails, and the process ends instead of degrading. It was also easy to
// reach — the renderer produces the 404 too, so an app with a custom renderer and no matching
// route was one request away from exiting.
describe('an onError that throws', () => {
const exploding: ErrorRenderer = () => {
throw new Error('renderer exploded');
};
@Route('/x')
class Boom {
@Get('/boom') boom() {
throw new HttpError(503, 'Service Unavailable');
}
}
@Module({ mountpoint: '/', controllers: [Boom] })
class BoomModule {}
it('falls back to the built-in rendering rather than losing the response', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const res = await app.fetch(new Request('http://x/x/boom'));
// The original error still gets its answer: the fallback is the rendering `onError` overrides.
expect(res.status).toBe(503);
expect(await res.json()).toEqual({ error: 'Service Unavailable' });
});
// The path that needed no thrown handler at all.
it('survives a 404, which the renderer also produces', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const res = await app.fetch(new Request('http://x/nothing-here'));
expect(res.status).toBe(404);
expect(await res.json()).toEqual({ error: 'Not Found' });
});
it('reports the renderer as the thing that failed, not the request', async () => {
const logged: Array<{ msg: string; fields?: Record<string, unknown> }> = [];
const logger = {
debug() {},
info() {},
warn() {},
error(msg: string, fields?: Record<string, unknown>) {
logged.push({ msg, fields });
},
};
const app = createApp({ modules: [BoomModule], onError: exploding, logger });
await app.fetch(new Request('http://x/x/boom'));
expect(logged).toHaveLength(1);
expect(logged[0].msg).toMatch(/onError/);
// Both errors named, because a reader chasing the wrong one loses an afternoon.
expect(logged[0].fields?.err).toBe('renderer exploded');
expect(logged[0].fields?.rendering).toBe('Service Unavailable');
});
it('answers over a real Node server instead of exiting the process', async () => {
const app = createApp({ modules: [BoomModule], onError: exploding });
const server = await app.listen(0);
const port = (server.address() as { port: number }).port;
const res = await fetch(`http://127.0.0.1:${port}/x/boom`);
expect(res.status).toBe(503);
// Still serving — the point of the whole test.
expect((await fetch(`http://127.0.0.1:${port}/nope`)).status).toBe(404);
await app.close();
});
});
+1
View File
@@ -0,0 +1 @@
served
+1
View File
@@ -0,0 +1 @@
<h1>Dash</h1>
+1
View File
@@ -0,0 +1 @@
<h1>Hi {{ name }}</h1>
+292 -1
View File
@@ -1,4 +1,8 @@
import { describe, expect, it, test } from 'vitest'; import { describe, expect, it, test, vi } from 'vitest';
import * as net from 'node:net';
import { ServerResponse } from 'node:http';
import { once } from 'node:events';
import { Bus } from '../src/bus';
import { matchRoute, parseQuery, createHttpServer } from '../src/http'; import { matchRoute, parseQuery, createHttpServer } from '../src/http';
const handler = async () => ({ status: 200, headers: {}, body: 'ok' }); const handler = async () => ({ status: 200, headers: {}, body: 'ok' });
@@ -143,6 +147,185 @@ describe('request hardening', () => {
server.close(); server.close();
}); });
it('warns when maxConnections drops a real connection and throttles repeated warnings', async () => {
const logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
};
const server = createHttpServer([], [], undefined, undefined, {
logger,
limits: { maxConnections: 1 },
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('server did not bind to a TCP port');
const first = net.createConnection({ host: '127.0.0.1', port: address.port });
await once(first, 'connect');
const waitForClose = (socket: net.Socket): Promise<void> =>
new Promise((resolve) => {
socket.on('error', () => undefined);
socket.once('close', () => resolve());
});
const second = net.createConnection({ host: '127.0.0.1', port: address.port });
const third = net.createConnection({ host: '127.0.0.1', port: address.port });
const secondClosed = waitForClose(second);
const thirdClosed = waitForClose(third);
try {
await Promise.all([secondClosed, thirdClosed]);
expect(logger.warn).toHaveBeenCalledOnce();
expect(logger.warn).toHaveBeenCalledWith(
expect.stringContaining('maxConnections (1) reached \u2014 dropped connection from'),
expect.objectContaining({
maxConnections: 1,
remoteAddress: '127.0.0.1',
}),
);
} finally {
first.destroy();
second.destroy();
third.destroy();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => {
let release!: () => void;
let started!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const firstStarted = new Promise<void>((resolve) => {
started = resolve;
});
const bus = new Bus();
const ended: Array<{ method?: string; status?: number; requestId?: string }> = [];
bus.on('request:end', (event) => {
ended.push(event);
});
const server = createHttpServer(
[
{
method: 'GET',
pattern: '/slow',
transport: 'buffer',
handler: async () => {
started();
await blocked;
return { status: 200, headers: {}, body: 'ok' };
},
},
],
[],
bus,
undefined,
{
limits: { maxConcurrentRequests: 1 },
cors: { origins: 'https://example.com' },
},
);
await new Promise<void>((resolve) => server.listen(0, resolve));
const first = fetch(`${getUrl(server)}/slow`);
await firstStarted;
const rejected = await fetch(`${getUrl(server)}/slow`, {
headers: { origin: 'https://example.com' },
});
expect(rejected.status).toBe(503);
expect(rejected.headers.get('content-type')).toBe('application/json');
expect(rejected.headers.get('retry-after')).toBe('1');
expect(rejected.headers.get('connection')).toBe('close');
expect(rejected.headers.get('access-control-allow-origin')).toBe('https://example.com');
expect(rejected.headers.get('x-content-type-options')).toBe('nosniff');
expect(rejected.headers.get('x-frame-options')).toBe('SAMEORIGIN');
await expect(rejected.json()).resolves.toEqual({ error: 'Service Unavailable' });
expect(ended).toHaveLength(1);
expect(ended[0]).toMatchObject({
method: 'GET',
status: 503,
});
expect(ended[0].requestId).toBeTruthy();
release();
const firstResponse = await first;
expect(firstResponse.status).toBe(200);
const afterRelease = await fetch(`${getUrl(server)}/slow`);
expect(afterRelease.status).toBe(200);
server.close();
});
it('releases a request slot when the client disconnects before the handler settles', async () => {
let started!: () => void;
const handlerStarted = new Promise<void>((resolve) => {
started = resolve;
});
const server = createHttpServer(
[
{
method: 'GET',
pattern: '/hang',
transport: 'buffer',
handler: async () => {
started();
await new Promise(() => {});
return { status: 200, headers: {}, body: 'never' };
},
},
{
method: 'GET',
pattern: '/ok',
transport: 'buffer',
handler: async () => ({ status: 200, headers: {}, body: 'ok' }),
},
],
[],
undefined,
undefined,
{ limits: { maxConcurrentRequests: 1 } },
);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('server did not bind to a TCP port');
const responseClosed = new Promise<void>((resolve) => {
server.once('request', (_req, res) => {
res.once('close', resolve);
});
});
const client = net.createConnection({ host: '127.0.0.1', port: address.port });
await once(client, 'connect');
client.write('GET /hang HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n');
await handlerStarted;
client.destroy();
await responseClosed;
const afterDisconnect = await fetch(`${getUrl(server)}/ok`);
expect(afterDisconnect.status).toBe(200);
await new Promise<void>((resolve) => server.close(() => resolve()));
});
it('requestTimeout does NOT kill an in-flight SSE stream (streaming regression)', async () => { it('requestTimeout does NOT kill an in-flight SSE stream (streaming regression)', async () => {
async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } } async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } }
const server = createHttpServer( const server = createHttpServer(
@@ -170,4 +353,112 @@ describe('request hardening', () => {
expect(await res.json()).toEqual({ a: '1', b: 'two' }); expect(await res.json()).toEqual({ a: '1', b: 'two' });
server.close(); server.close();
}); });
it('a cors.origins predicate that throws answers the request instead of taking the process down', async () => {
const warn = vi.fn();
const server = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[],
undefined,
undefined,
{
cors: {
origins: () => {
throw new Error('lookup failed');
},
},
logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() } as any,
},
);
await new Promise<void>((r) => server.listen(0, r));
// Only a request carrying an Origin reaches the predicate — which is why a suite that forgets
// the header watches this crash in production instead.
const res = await fetch(`${getUrl(server)}/ping`, { headers: { origin: 'https://a.com' } });
expect(res.status).toBe(200);
expect(res.headers.get('access-control-allow-origin')).toBeNull();
expect(warn).toHaveBeenCalled();
// The security headers still land: one broken predicate must not strip the rest.
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
server.close();
});
// `origins` is a predicate because the shapes it exists for are lookups — an allowlist in Redis, a
// tenant query. Running one twice for a GET and three times for a preflight charges the caller's
// latency budget and their backend for an answer whose inputs did not change in between.
it('consults a cors.origins predicate once per request, not once per header computation', async () => {
let calls = 0;
const server = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[], undefined, undefined,
{ cors: { origins: () => { calls++; return true; } } },
);
await new Promise<void>((r) => server.listen(0, r));
const origin = { origin: 'https://a.com' };
const plain = await fetch(`${getUrl(server)}/ping`, { headers: origin });
expect(plain.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
calls = 0;
const preflight = await fetch(`${getUrl(server)}/ping`, {
method: 'OPTIONS', headers: { ...origin, 'access-control-request-method': 'GET' },
});
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-methods')).toContain('GET');
expect(preflight.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
// No Origin header never reaches the predicate at all — that part was already right.
calls = 0;
await fetch(`${getUrl(server)}/ping`);
expect(calls).toBe(0);
server.close();
});
// `maxConcurrentRequests` is opt-in and unlimited by default, so the overwhelming majority of
// apps used to pay a closure and an EventEmitter registration per request for a feature that is
// off. Small in absolute terms, and on the hot path, which is why it is asserted rather than
// trusted: a `res.once('close')` is exactly the kind of line that comes back.
it('registers no per-request close listener when no request budget is configured', async () => {
const closeListeners: string[] = [];
// Typed loosely on purpose: `once` is an overloaded EventEmitter signature and the spy only
// needs to see the event name before handing the call straight back to the real one.
const proto = ServerResponse.prototype as unknown as {
once(event: string | symbol, listener: (...args: unknown[]) => void): unknown;
};
const realOnce = proto.once;
const spy = vi.spyOn(proto, 'once').mockImplementation(function (this: unknown, event, listener) {
if (event === 'close') closeListeners.push('close');
return realOnce.call(this, event, listener);
});
try {
const unlimited = createHttpServer([{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }]);
await new Promise<void>((r) => unlimited.listen(0, r));
expect((await fetch(`${getUrl(unlimited)}/ping`)).status).toBe(200);
expect(closeListeners).toHaveLength(0);
unlimited.close();
// With a budget set, the listener is what releases the slot on a client disconnect, so it
// has to come back — the guard is about the unset case, not about dropping the feature.
const limited = createHttpServer(
[{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }],
[], undefined, undefined,
{ limits: { maxConcurrentRequests: 4 } },
);
await new Promise<void>((r) => limited.listen(0, r));
expect((await fetch(`${getUrl(limited)}/ping`)).status).toBe(200);
expect(closeListeners.length).toBeGreaterThan(0);
limited.close();
} finally {
spy.mockRestore();
}
});
}); });
+29
View File
@@ -0,0 +1,29 @@
// Not a test — a Deno app with `handleSignals: true`, spawned by test/deno/signals.test.ts.
// Deno's test runner only discovers *.test.ts, so this file is ignored by `deno test`.
//
// It exists because Deno is where the signal API actually differs: `Deno.addSignalListener` and
// `Deno.exit` rather than `process.on`/`process.exit`, and a listener that holds the process open
// until it is removed. Node passing says nothing about any of that.
import 'npm:reflect-metadata';
import { createApp, Module } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Module({ mountpoint: '/', controllers: [] })
class Mod {}
// A hook rather than a provider's `dispose()`: on Deno nothing boots until the first request, so an
// unvisited app has no provider to dispose and the run would pass without proving anything. The
// hook registers at `createApp`, which makes "teardown ran" mean "close() was reached".
const app = createApp({
modules: [Mod],
handleSignals: true,
hooks: [{ onShutdown: () => console.log(JSON.stringify({ disposed: true })) }],
});
// `ready` is printed after `serveDeno` returns, not from `onListen` — Deno calls `onListen`
// synchronously from inside `Deno.serve`, so a parent that signals on that line races the handler
// registration that happens a few statements later and wins.
const server = serveDeno(app, { port: 0, onListen: () => {} });
console.log(JSON.stringify({ ready: true }));
void server;
+41
View File
@@ -0,0 +1,41 @@
// Not a test — a Node app with `handleSignals: true`, spawned by shutdown-signals.test.ts.
//
// Signal handling can only be told apart from doing nothing by a real process that really gets a
// real signal: an in-process test would have to fire the handler by hand, and the handler's whole
// job is to exit the process it is running in.
//
// Prints one JSON line per event on stdout: {"ready":port}, then {"disposed":n} per dispose call.
import 'reflect-metadata';
import { createApp, Provider, Route, Get, Module } from '../../src/index';
const SLOW = Number(process.env.DISPOSE_DELAY_MS ?? 0);
let disposals = 0;
@Provider({ provides: 'db' })
class Db {
provide() {
return { db: { name: 'db' } };
}
async dispose() {
if (SLOW) await new Promise((r) => setTimeout(r, SLOW));
disposals++;
console.log(JSON.stringify({ disposed: disposals }));
}
}
@Route('/')
class Api {
@Get('/ping') ping() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Api], providers: [Db] })
class Mod {}
const app = createApp({ modules: [Mod], handleSignals: process.env.HANDLE_SIGNALS !== 'false' });
void app.listen(0).then((server) => {
console.log(JSON.stringify({ ready: (server.address() as { port: number }).port }));
});
+185
View File
@@ -0,0 +1,185 @@
// The `request:start` / `request:end` pairing, asserted across every terminal path there is.
//
// The guarantee held by accident until `maxConcurrentRequests` arrived: `request:start` had a
// single emitter, so nothing could break it. It has more than one now, and a guarantee upheld by
// there being only one place to get it wrong is not a guarantee — it is a coincidence with good
// timing. This file is what makes the next terminal path fail loudly instead of quietly.
//
// Adding a response shape? Add a row. That is the whole maintenance contract.
import { describe, expect, it } from 'vitest';
import { Bus } from '../src/bus';
import { createHttpServer } from '../src/http';
import { buildFetch } from '../src/http/web';
interface Seen {
starts: string[];
ends: Array<{ requestId?: string; status?: number }>;
}
function watch(bus: Bus): Seen {
const seen: Seen = { starts: [], ends: [] };
bus.on('request:start', (e) => seen.starts.push(e.requestId ?? ''));
bus.on('request:end', (e) => seen.ends.push({ requestId: e.requestId, status: e.status }));
return seen;
}
const ok = async () => ({ status: 200, headers: {}, body: 'ok' });
const boom = async () => {
throw new Error('kaboom');
};
/** Every shape of request the framework can answer, and how to provoke it. */
const SHAPES: Array<{
name: string;
status: number;
routes: Parameters<typeof buildFetch>[0];
opts?: Parameters<typeof buildFetch>[1];
request: () => Request;
}> = [
{
name: 'matched handler',
status: 200,
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
request: () => new Request('http://x/ok'),
},
{
name: 'unmatched route',
status: 404,
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
request: () => new Request('http://x/nope'),
},
{
name: 'handler throws',
status: 500,
routes: [{ method: 'GET', pattern: '/boom', transport: 'buffer', handler: boom }],
request: () => new Request('http://x/boom'),
},
{
name: 'body over maxBodyBytes',
status: 413,
routes: [{ method: 'POST', pattern: '/echo', transport: 'buffer', handler: ok }],
opts: { limits: { maxBodyBytes: 8 } },
request: () => new Request('http://x/echo', { method: 'POST', body: 'x'.repeat(500) }),
},
{
name: 'CORS preflight',
status: 204,
routes: [{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
opts: { cors: { origins: '*' } },
request: () =>
new Request('http://x/ok', {
method: 'OPTIONS',
headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' },
}),
},
];
describe('every terminal path emits request:start before request:end', () => {
for (const shape of SHAPES) {
it(`${shape.name} → ${shape.status}`, async () => {
const bus = new Bus();
const seen = watch(bus);
const fetchHandler = buildFetch(shape.routes, { ...shape.opts, bus });
const res = await fetchHandler(shape.request());
expect(res.status).toBe(shape.status);
expect(seen.starts).toHaveLength(1);
expect(seen.ends).toHaveLength(1);
// Same request, not two that happened to arrive together — the id is what a consumer keys on.
expect(seen.ends[0].requestId).toBe(seen.starts[0]);
});
}
// The path that broke the pairing, and the reason this file exists. It never reaches `handle()`,
// so the emitter every row above goes through never sees it.
it('shed over maxConcurrentRequests → 503', async () => {
const bus = new Bus();
const seen = watch(bus);
let release!: () => void;
const blocked = new Promise<void>((r) => (release = r));
const fetchHandler = buildFetch(
[{ method: 'GET', pattern: '/slow', transport: 'buffer', handler: async () => (await blocked, ok()) }],
{ bus, limits: { maxConcurrentRequests: 1 } },
);
const first = fetchHandler(new Request('http://x/slow'));
const shed = await fetchHandler(new Request('http://x/slow'));
expect(shed.status).toBe(503);
release();
await first;
const shedPair = seen.ends.find((e) => e.status === 503)!;
expect(shedPair).toBeDefined();
expect(seen.starts).toContain(shedPair.requestId);
});
// The Node adapter sheds through its own code path, so passing on `buildFetch` proves nothing
// about it — the two were separate emitters before they shared one.
it('shed over maxConcurrentRequests → 503, on the Node adapter', async () => {
const bus = new Bus();
const seen = watch(bus);
let release!: () => void;
let started!: () => void;
const blocked = new Promise<void>((r) => (release = r));
const firstStarted = new Promise<void>((r) => (started = r));
const server = createHttpServer(
[
{
method: 'GET',
pattern: '/slow',
transport: 'buffer',
handler: async () => {
started();
await blocked;
return { status: 200, headers: {}, body: 'ok' };
},
},
],
[],
bus,
undefined,
{ limits: { maxConcurrentRequests: 1 } },
);
await new Promise<void>((r) => server.listen(0, r));
const url = `http://127.0.0.1:${(server.address() as { port: number }).port}/slow`;
const first = fetch(url);
await firstStarted;
const shed = await fetch(url);
expect(shed.status).toBe(503);
release();
await first;
const shedPair = seen.ends.find((e) => e.status === 503)!;
expect(shedPair).toBeDefined();
expect(seen.starts).toContain(shedPair.requestId);
server.close();
});
// The invariant stated as a count rather than per row. Scoped to the enumerated shapes on
// purpose — the two shed paths have their own tests above, because they are the ones that need
// a blocked handler to provoke and the ones that broke it in the first place.
it('leaves no enumerated shape with an end whose start is missing', async () => {
const bus = new Bus();
const seen = watch(bus);
const fetchHandler = buildFetch(
[{ method: 'GET', pattern: '/ok', transport: 'buffer', handler: ok }],
{ bus, cors: { origins: '*' } },
);
for (const shape of SHAPES) {
const h = buildFetch(shape.routes, { ...shape.opts, bus });
await h(shape.request());
}
await fetchHandler(new Request('http://x/ok'));
expect(seen.ends).not.toHaveLength(0);
for (const end of seen.ends) expect(seen.starts).toContain(end.requestId);
expect(seen.starts).toHaveLength(seen.ends.length);
});
});
+95
View File
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index'; import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
import type { EventPayload } from '../src/bus'; import type { EventPayload } from '../src/bus';
import { UNMATCHED_ROUTE } from '../src/index';
@Provider({ provides: 'db' }) @Provider({ provides: 'db' })
class Db { class Db {
@@ -175,6 +176,100 @@ describe('failure reporting', () => {
expect(requestFailures).toHaveLength(1); expect(requestFailures).toHaveLength(1);
expect(requestFailures[0].route).toBe('/bad/go'); expect(requestFailures[0].route).toBe('/bad/go');
expect(requestFailures[0].requestId).toBe(stepErrors[0].requestId); expect(requestFailures[0].requestId).toBe(stepErrors[0].requestId);
// Carries what was actually sent, so an error counter can break down by status without
// joining back to the `request:end` that follows it.
expect(requestFailures[0].status).toBe(500);
}); });
// The cardinality trap: `name` carries the path that arrived, which is bounded by nothing at all.
// A consumer labelling on `route` gets one bounded series for every path that was never a route;
// one labelling on `name` gets a series per scanner probe.
it('labels an unmatched request with a bounded route, on both events', async () => {
const app = createApp({ modules: [BadModule] });
const unmatched: EventPayload[] = [];
const ends: EventPayload[] = [];
app.bus.on('route:unmatched', (p) => unmatched.push(p));
app.bus.on('request:end', (p) => ends.push(p));
for (const probe of ['/aaa', '/aab', '/aac']) await app.fetch(new Request(`http://x${probe}`));
expect(unmatched).toHaveLength(3);
expect(ends).toHaveLength(3);
// Three distinct paths, one series.
expect(new Set(unmatched.map((e) => e.route))).toEqual(new Set([UNMATCHED_ROUTE]));
expect(new Set(ends.map((e) => e.route))).toEqual(new Set([UNMATCHED_ROUTE]));
// `name` still carries the concrete path, which is what makes it useful in a log and unusable
// as a label.
expect(new Set(unmatched.map((e) => e.name)).size).toBe(3);
// It cannot collide with a pattern a user can declare.
expect(UNMATCHED_ROUTE.startsWith('/')).toBe(false);
});
it('leaves a matched route labelled with its pattern, not the marker', async () => {
const app = createApp({ modules: [BadModule] });
const ends: EventPayload[] = [];
app.bus.on('request:end', (p) => ends.push(p));
await app.fetch(new Request('http://x/bad/go'));
expect(ends[0].route).toBe('/bad/go');
});
// The three-event overlap, asserted rather than described: one failing request, three events,
// one requestId. A consumer that counts `request:failed` and `request:end` as separate outcomes
// counts this request twice — which is the mistake the payload docs now name.
it('emits start, failed and end for one failing request, all sharing a requestId', async () => {
const app = createApp({ modules: [BadModule] });
const seen: Array<{ event: string; payload: EventPayload }> = [];
for (const event of ['request:start', 'request:failed', 'request:end'] as const)
app.bus.on(event, (payload) => seen.push({ event, payload }));
await app.fetch(new Request('http://x/bad/go'));
expect(seen.map((s) => s.event)).toEqual(['request:start', 'request:failed', 'request:end']);
expect(new Set(seen.map((s) => s.payload.requestId)).size).toBe(1);
// `request:end` is the terminal one and the only one that fires for every request shape; it is
// what a request counter counts.
expect(seen[2].payload.status).toBe(500);
});
// `onError` may turn any throw into any status, so a status derived from the error rather than
// from the render would be a guess that a custom renderer makes wrong.
it('reports the status a custom onError produced, not the one the error implied', async () => {
const app = createApp({
modules: [BadModule],
onError: () => ({ status: 418, headers: {}, body: 'teapot' }),
});
const failures: EventPayload[] = [];
app.bus.on('request:failed', (p) => failures.push(p));
const res = await app.fetch(new Request('http://x/bad/go'));
expect(res.status).toBe(418);
expect(failures).toHaveLength(1);
expect(failures[0].status).toBe(418);
});
// A renderer that throws must not swallow the event — the failure still happened, and losing the
// only record of it because the reporting of it broke is the worst possible trade. The status is
// the built-in renderer's, since that is what the request actually got.
it('still reports the failure when onError itself throws', async () => {
const app = createApp({
modules: [BadModule],
onError: () => {
throw new Error('renderer exploded');
},
});
const failures: EventPayload[] = [];
app.bus.on('request:failed', (p) => failures.push(p));
const res = await app.fetch(new Request('http://x/bad/go'));
expect(res.status).toBe(500);
expect(failures).toHaveLength(1);
expect(failures[0].status).toBe(500);
// The request's error, not the renderer's — they are different errors and the event names the
// one the request suffered.
expect((failures[0].error as Error).message).toBe('step exploded');
});
}); });
+141
View File
@@ -0,0 +1,141 @@
// Framework token names, and the read-only slice of the bus that `@needs` can reach.
//
// Two halves of one decision. The bus is not a graph token — a node that could reach it could also
// `emit`, and an observation channel anything can write to is not one — but `@needs('logger')`
// teaches that framework things *are* graph tokens, so reaching for `@needs('bus')` is the natural
// next move. Documenting that it does not work only reaches a reader; the boot error reaches the
// person writing it. And reserving the names stops a user's own `logger` from quietly becoming the
// one the whole app injects.
import 'reflect-metadata';
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
import type { Events } from '../src/index';
@Route('/r')
class Ctl {
@Get('/x') x() {
return { ok: true };
}
}
describe('reserved framework tokens', () => {
for (const token of ['logger', 'rooms', 'events']) {
it(`refuses a provider that declares '${token}'`, () => {
@Provider({ provides: token })
class Shadow {
provide() {
return { [token]: { mine: true } };
}
}
@Module({ mountpoint: '/', providers: [Shadow], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(
new RegExp(`'${token}' is reserved by the framework`),
);
});
}
it("refuses a step that declares 'bus', a name the framework reserves without providing", () => {
@Step({ provides: 'bus' })
class Shadow {
run() {
return { bus: { mine: true } };
}
}
@Module({ mountpoint: '/', steps: [Shadow], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/'bus' is reserved by the framework/);
});
it('leaves every other name alone', () => {
@Provider({ provides: 'buses' })
class Fine {
provide() {
return { buses: 1 };
}
}
@Module({ mountpoint: '/', providers: [Fine], controllers: [Ctl] })
class M {}
expect(() => createApp({ modules: [M] })).not.toThrow();
});
});
describe("@needs('bus')", () => {
it('fails at boot naming the read-only token and the plugin, not a nearest match', () => {
@Route('/b')
class Bad {
@Get('/x') x(@needs('bus') _bus: unknown) {
return {};
}
}
@Module({ mountpoint: '/', controllers: [Bad] })
class M {}
expect(() => createApp({ modules: [M] })).toThrow(/the Bus is not a graph token/);
expect(() => createApp({ modules: [M] })).toThrow(/@needs\('events'\)/);
expect(() => createApp({ modules: [M] })).toThrow(/plugin/);
});
});
describe("@needs('events')", () => {
it('hands over on() and nothing else — no emit to forge events with', async () => {
let injected: Events | undefined;
@Route('/e')
class Observer {
@Get('/x') x(@needs('events') events: Events) {
injected = events;
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Observer] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/x'));
expect(typeof injected?.on).toBe('function');
expect(Object.keys(injected!)).toEqual(['on']);
expect((injected as unknown as { emit?: unknown }).emit).toBeUndefined();
});
it('subscribes to the same bus the framework emits on, and hands back an unsubscribe', async () => {
const seen: string[] = [];
@Provider({ provides: 'watcher', needs: ['events'] })
class Watcher {
#off?: () => void;
provide(ctx: { events: Events }) {
this.#off = ctx.events.on('request:end', (e) => seen.push(e.route ?? ''));
return { watcher: true };
}
dispose() {
this.#off?.();
}
}
@Route('/e')
class Observed {
@Get('/y') y(@needs('watcher') _w: unknown) {
return { ok: true };
}
}
@Module({ mountpoint: '/', providers: [Watcher], controllers: [Observed] })
class M {}
const app = createApp({ modules: [M] });
await app.fetch(new Request('http://x/e/y'));
expect(seen).toEqual(['/e/y']);
// dispose() releases it, which is the half a plugin gets for free with onShutdown. Asserted by
// emitting after close and watching nothing arrive — clearing the array and finding it empty
// would prove only that clearing works.
await app.close();
seen.length = 0;
app.bus.emit('request:end', { name: 'after close', route: '/after' });
expect(seen).toEqual([]);
});
});
+28 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
import { buildSecurityHeaders, resolveCors, mergeVary, isValidOrigin } from '../src/security'; import { buildSecurityHeaders, resolveCors, mergeVary, isValidOrigin } from '../src/security';
describe('buildSecurityHeaders', () => { describe('buildSecurityHeaders', () => {
@@ -51,6 +51,33 @@ describe('resolveCors', () => {
const r = resolveCors({ origins: () => true }, req('https://a.com\r\nX: y') as any); const r = resolveCors({ origins: () => true }, req('https://a.com\r\nX: y') as any);
expect(r['access-control-allow-origin']).toBeUndefined(); expect(r['access-control-allow-origin']).toBeUndefined();
}); });
// An `origins` predicate is the whole reason the option takes a function: an allowlist in Redis, a
// tenant lookup, a regex over a parsed URL. Every one of those has a failure mode, and it runs on
// the request path — so a throw must not leave the boundary.
describe('a predicate that throws', () => {
const boom = () => {
throw new Error('lookup failed');
};
it('denies the origin rather than escaping the request path', () => {
expect(() => resolveCors({ origins: boom }, req('https://a.com') as any)).not.toThrow();
expect(resolveCors({ origins: boom }, req('https://a.com') as any)).toEqual({});
});
it('fails closed even when credentials are on — a broken allowlist is not an open one', () => {
const r = resolveCors({ origins: boom, credentials: true }, req('https://a.com') as any);
expect(r['access-control-allow-origin']).toBeUndefined();
expect(r['access-control-allow-credentials']).toBeUndefined();
});
it('reports the failure through the logger instead of swallowing it', () => {
const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
resolveCors({ origins: boom }, req('https://a.com') as any, logger as any);
expect(logger.warn).toHaveBeenCalledOnce();
expect(logger.warn.mock.calls[0][0]).toMatch(/cors/i);
});
});
}); });
describe('isValidOrigin', () => { describe('isValidOrigin', () => {
+112
View File
@@ -0,0 +1,112 @@
import { describe, it, expect, afterEach } from 'vitest';
import { spawn, type ChildProcess } from 'node:child_process';
import { createApp, Module } from '../src';
@Module({ mountpoint: '/', controllers: [] })
class Empty {}
let app: ReturnType<typeof createApp> | undefined;
let child: ChildProcess | undefined;
afterEach(async () => {
await app?.close();
app = undefined;
child?.kill('SIGKILL');
child = undefined;
});
const disposed = (r: { lines: string[] }) => r.lines.filter((l) => l.includes('"disposed"'));
const handled = (r: { lines: string[] }) => r.lines.some((l) => l.includes('received — closing'));
const listeners = () => process.listenerCount('SIGINT') + process.listenerCount('SIGTERM');
describe('handleSignals registration', () => {
it('registers nothing by default — a library must not own when the process exits', async () => {
const before = listeners();
app = createApp({ modules: [Empty] });
await app.listen(0);
expect(listeners()).toBe(before);
});
it('registers SIGINT and SIGTERM when asked, and takes both back off in close()', async () => {
const before = listeners();
const opted = createApp({ modules: [Empty], handleSignals: true });
await opted.listen(0);
expect(listeners()).toBe(before + 2);
// Not tidiness: on Deno a live signal listener holds the process open, so an app that closed
// itself and expected to exit would hang. Node is where it is observable.
await opted.close();
expect(listeners()).toBe(before);
});
});
/** Boots the harness app, waits for its `ready` line, and resolves once it has exited. */
function runHarness(signal: NodeJS.Signals, env: NodeJS.ProcessEnv = {}, sendTwice = false) {
return new Promise<{ code: number | null; signal: NodeJS.Signals | null; lines: string[] }>((resolve, reject) => {
// `process.execPath -r tsx/cjs`, not `npx tsx`: a wrapper puts the app one process further
// down, and on Linux the signal then lands on the wrapper while the app never hears it — which
// is exactly how this passed locally and failed in CI. `-r` rather than `--import`/`--loader`
// because it is the one form that works on both the Node 18 floor CI builds against and the
// current release.
const proc = spawn(process.execPath, ['-r', 'tsx/cjs', 'test/interop/_signal-app.ts'], {
env: { ...process.env, ...env },
stdio: ['ignore', 'pipe', 'inherit'],
});
child = proc;
const lines: string[] = [];
let ready = false;
let buffered = '';
proc.stdout.on('data', (chunk: Buffer) => {
buffered += chunk.toString();
const parts = buffered.split('\n');
buffered = parts.pop() ?? '';
for (const line of parts.filter(Boolean)) {
lines.push(line);
if (!ready && line.includes('"ready"')) {
ready = true;
proc.kill(signal);
if (sendTwice) setTimeout(() => proc.kill(signal), 20);
}
}
});
proc.on('error', reject);
proc.on('exit', (code, exitSignal) => resolve({ code, signal: exitSignal, lines }));
});
}
// These need a real process because the handler's job is to exit the one it runs in — firing it by
// hand in the test runner would either take the runner down or prove nothing.
describe('handleSignals end to end', () => {
it('SIGTERM runs teardown and exits 0', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGTERM');
expect(disposed(r)).toHaveLength(1);
expect(r.code).toBe(0);
});
it('SIGINT does the same — Ctrl-C is not a different kind of shutdown', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGINT');
expect(disposed(r)).toHaveLength(1);
expect(r.code).toBe(0);
});
// The escape hatch, and the reason `close()` unregisters before it starts draining: a second
// signal finds no handler and gets the platform default. Ctrl-C twice ends a stuck teardown
// rather than waiting out the whole shutdown budget.
it('lets a second signal end a shutdown that is still draining', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGTERM', { DISPOSE_DELAY_MS: '2000' }, true);
expect(handled(r)).toBe(true); // the first signal was ours
expect(disposed(r)).toHaveLength(0); // the second one did not wait for the 2s dispose
expect(r.code).not.toBe(0);
});
it('leaves the process to its default fate when handleSignals is off', { timeout: 20_000 }, async () => {
const r = await runHarness('SIGTERM', { HANDLE_SIGNALS: 'false' });
expect(handled(r)).toBe(false); // nothing of ours ran at all
expect(disposed(r)).toHaveLength(0);
expect(r.code).not.toBe(0);
});
});
+68
View File
@@ -0,0 +1,68 @@
// Every extension point the docs tell a user to write must be *typeable* from the package, not just
// callable. A decorator whose argument type is not exported can be passed a literal and nothing
// else — the shape has to be redeclared inline, or borrowed off a value with
// `typeof JsonTransformer`, which works and reads like a trick because it is one.
//
// This file's job is to fail to compile if one of them stops being exported.
import { test, expect } from 'vitest';
import {
JsonTransformer,
type TransformerFn,
type Plugin,
type PluginApi,
type ScopeApi,
type ScopeNode,
type Hooks,
type TeardownFn,
type ErrorRenderer,
type StreamEncoder,
} from '../../src';
// @Transformer(fn) — the case that started this. Prometheus scrapes text, so a /metrics route
// needs its own transformer, and this is the annotation that was impossible to write.
const prometheusText: TransformerFn = (value) => ({
status: 200,
headers: { 'content-type': 'text/plain; version=0.0.4; charset=utf-8' },
body: String(value),
});
// A plugin split into named functions rather than one inline arrow: `Plugin` alone types the
// arrow, and nothing typed its argument.
function subscribe(api: PluginApi): void {
api.bus.on('request:end', () => {});
api.onShutdown(flush);
}
const flush: TeardownFn = () => {};
function contribute(scope: ScopeApi): void {
const node: ScopeNode = { kind: 'provider', name: 'metrics', needs: [], provides: ['metrics'], run: () => ({}) };
scope.add(node);
}
const metricsPlugin: Plugin = (api) => {
subscribe(api);
contribute(api.scope);
};
// createApp({ hooks }) — declared as a value, which is the point of the option.
const hooks: Hooks[] = [{ onShutdown: flush }];
// The two neighbouring extension points, already exported. Here so a future barrel edit that drops
// one is caught by the same test rather than by a user.
const renderError: ErrorRenderer = () => ({ status: 500, headers: {}, body: 'boom' });
const encoder: StreamEncoder = {
headers: {},
encode: (item) => String(item),
encodeError: (err) => String(err),
};
test('every extension point is typeable from the package barrel', () => {
expect(prometheusText('x').body).toBe('x');
expect(typeof metricsPlugin).toBe('function');
expect(hooks).toHaveLength(1);
expect(renderError(new Error('boom'), {} as never)?.status).toBe(500);
expect(encoder.encode(1)).toBe('1');
// The workaround the missing export forced, kept as a reminder of what it replaced.
expect(typeof JsonTransformer).toBe('function');
});
+18
View File
@@ -19,6 +19,24 @@ class Views {
class M {} class M {}
const app = createApp({ modules: [M], views: dir }); const app = createApp({ modules: [M], views: dir });
// Checked alongside the `onError` guard: `viewEngine` is the other user callback on a render path,
// and whether it had a boundary was not something to assume. It does — the pipeline's own catch
// covers it, so a broken engine is a 500 rather than a dead process. Asserted so it stays that way.
describe('a viewEngine that throws', () => {
it('renders a 500 instead of escaping the request', async () => {
const broken = createApp({
modules: [M],
views: dir,
viewEngine: () => {
throw new Error('engine exploded');
},
});
const res = await broken.fetch(new Request('http://x/user'));
expect(res.status).toBe(500);
expect(await res.json()).toEqual({ error: 'Internal Server Error' });
});
});
describe('@Html modes', () => { describe('@Html modes', () => {
it('string mode sends the handler return as text/html', async () => { it('string mode sends the handler return as text/html', async () => {
const res = await app.fetch(new Request('http://x/str')); const res = await app.fetch(new Request('http://x/str'));
+182 -1
View File
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { asReadableStream, toBodyInit } from '../src/http/web'; import { Bus } from '../src/bus';
import { asReadableStream, buildFetch, toBodyInit } from '../src/http/web';
import { sseEncoder } from '../src/encoders'; import { sseEncoder } from '../src/encoders';
async function* nums() { yield { n: 1 }; yield { n: 2 }; } async function* nums() { yield { n: 1 }; yield { n: 2 }; }
@@ -46,4 +47,184 @@ describe('asReadableStream', () => {
await new Promise((r) => setTimeout(r, 10)); await new Promise((r) => setTimeout(r, 10));
expect(returned).toBe(true); expect(returned).toBe(true);
}); });
});
describe('buildFetch request gate', () => {
it('rides out a transient CORS predicate failure without leaking a gate slot', async () => {
// A flag rather than an attempt counter: `computeInjected` runs both in this adapter and again
// inside `handle()`, so the predicate is consulted more than once per request.
let lookupDown = true;
const fetchHandler = buildFetch(
[
{
method: 'GET',
pattern: '/ok',
transport: 'buffer',
handler: async () => ({ status: 200, headers: {}, body: 'ok' }),
},
],
{
limits: { maxConcurrentRequests: 2 },
cors: {
origins: () => {
if (lookupDown) throw new Error('transient CORS failure');
return true;
},
},
},
);
const request = () =>
new Request('http://localhost/ok', {
headers: { origin: 'https://example.com' },
});
// While the lookup is down the origin is denied — the request is answered, just without the
// header that would let the browser read it. A failed lookup has not said yes.
for (let i = 0; i < 2; i++) {
const denied = await fetchHandler(request());
expect(denied.status).toBe(200);
expect(denied.headers.get('access-control-allow-origin')).toBeNull();
}
// Once the lookup recovers the origin is allowed again, which also proves the two failures
// returned their slots: a budget of 2 that leaked would have shed this one.
lookupDown = false;
const recovered = await fetchHandler(request());
expect(recovered.status).toBe(200);
expect(recovered.headers.get('access-control-allow-origin')).toBe('https://example.com');
});
it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => {
let release!: () => void;
let started!: () => void;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const firstStarted = new Promise<void>((resolve) => {
started = resolve;
});
const bus = new Bus();
const ended: Array<{ method?: string; status?: number; requestId?: string }> = [];
bus.on('request:end', (event) => {
ended.push(event);
});
const fetchHandler = buildFetch(
[
{
method: 'GET',
pattern: '/slow',
transport: 'buffer',
handler: async () => {
started();
await blocked;
return { status: 200, headers: {}, body: 'ok' };
},
},
],
{
bus,
limits: { maxConcurrentRequests: 1 },
cors: { origins: 'https://example.com' },
},
);
const first = fetchHandler(new Request('http://localhost/slow'));
await firstStarted;
const rejected = await fetchHandler(
new Request('http://localhost/slow', {
headers: { origin: 'https://example.com' },
}),
);
expect(rejected.status).toBe(503);
expect(rejected.headers.get('content-type')).toBe('application/json');
expect(rejected.headers.get('retry-after')).toBe('1');
expect(rejected.headers.get('access-control-allow-origin')).toBe('https://example.com');
expect(rejected.headers.get('x-content-type-options')).toBe('nosniff');
expect(rejected.headers.get('x-frame-options')).toBe('SAMEORIGIN');
await expect(rejected.json()).resolves.toEqual({ error: 'Service Unavailable' });
expect(ended).toHaveLength(1);
expect(ended[0]).toMatchObject({
method: 'GET',
status: 503,
});
expect(ended[0].requestId).toBeTruthy();
release();
expect((await first).status).toBe(200);
const afterRelease = await fetchHandler(new Request('http://localhost/slow'));
expect(afterRelease.status).toBe(200);
});
it('consults a cors.origins predicate once per request on the fetch path too', async () => {
let calls = 0;
const fetchHandler = buildFetch(
[{ method: 'GET', pattern: '/ok', transport: 'buffer',
handler: async () => ({ status: 200, headers: {}, body: 'ok' }) }],
{ cors: { origins: () => { calls++; return true; } } },
);
const res = await fetchHandler(new Request('http://localhost/ok', { headers: { origin: 'https://a.com' } }));
expect(res.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
calls = 0;
const preflight = await fetchHandler(new Request('http://localhost/ok', {
method: 'OPTIONS',
headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' },
}));
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-methods')).toContain('GET');
expect(calls).toBe(1);
});
it('releases the slot when a streaming handler returns', async () => {
async function* stream() {
yield { n: 1 };
await new Promise(() => {});
}
const fetchHandler = buildFetch(
[
{
method: 'GET',
pattern: '/stream',
transport: 'sse',
handler: async () => ({ stream: stream() }),
},
],
{ limits: { maxConcurrentRequests: 1 } },
);
const first = await fetchHandler(
new Request('http://localhost/stream', {
headers: { accept: 'text/event-stream' },
}),
);
expect(first.status).toBe(200);
// The first response stream is still open, but its request slot should
// already be released once handle() has returned.
const second = await fetchHandler(
new Request('http://localhost/stream', {
headers: { accept: 'text/event-stream' },
}),
);
expect(second.status).toBe(200);
await first.body?.cancel();
await second.body?.cancel();
});
}); });
+1 -1
View File
@@ -15,5 +15,5 @@
"forceConsistentCasingInFileNames": true "forceConsistentCasingInFileNames": true
}, },
"include": ["src", "test", "example"], "include": ["src", "test", "example"],
"exclude": ["test/deno", "test/bun", "test/edge"] "exclude": ["test/deno", "test/bun", "test/edge", "test/interop/_signal-app-deno.ts"]
} }