Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29f6406c96 | ||
|
|
ea19ee21b7 | ||
|
|
88945b0b1f | ||
|
|
1da6bf2f99 | ||
|
|
f0530b15bb | ||
|
|
09251496c0 | ||
|
|
9977d14605 | ||
|
|
2c00cc3407 | ||
|
|
444910b6f0 | ||
|
|
56f953f0bb | ||
|
|
a9e0555516 | ||
|
|
88cbe41f72 | ||
|
|
89ac955072 | ||
|
|
8bf54ec168 |
No files matched your search
@@ -67,8 +67,60 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
constraints at a later segment of an otherwise unreachable route. The route then boots, as
|
constraints at a later segment of an otherwise unreachable route. The route then boots, as
|
||||||
before.
|
before.
|
||||||
|
|
||||||
|
- **Edge WebSocket upgrades no longer trust `cf-connecting-ip` by default** (#119). `edgeHandler`
|
||||||
|
copied the header into `ctx.ip` on every upgrade, so any client that sent it chose its own
|
||||||
|
address. It now counts only under `trustProxy: true`, the same rule HTTP follows. Without it,
|
||||||
|
`ctx.ip` on an edge WebSocket is `''`, as it already was on edge HTTP: workerd exposes no peer
|
||||||
|
address. An app behind Cloudflare that keys anything on the WebSocket IP needs
|
||||||
|
`createApp({ trustProxy: true })`.
|
||||||
|
- **A token has one producer: a second one fails `createApp`** (GitHub #35). The graph kept the
|
||||||
|
last node registered for a token, and plugin nodes are registered after module nodes, so a
|
||||||
|
plugin whose `scope.add` provided `user` silently replaced the app's own `@Provider({ provides:
|
||||||
|
'user' })` for every route that needed it. Boot now fails instead, naming both nodes and where
|
||||||
|
they came from: `token 'user' is provided twice: by 'user' (module:AppModule) and by 'shadow'
|
||||||
|
(plugin)`. The rule covers the whole graph (modules, plugins, mesh steps spliced at boot, and
|
||||||
|
the built-ins `logger`, `rooms` and `events`), so a plugin node that provides `logger` under
|
||||||
|
another name fails as well, whatever order things are registered in. `overrides` keep working:
|
||||||
|
they replace the runner of an existing token and add no producer. Observer steps that provide
|
||||||
|
nothing are unaffected. The official plugins already follow name = node name = token.
|
||||||
|
- **`/__mesh__/control` is reserved in every app, mesh or not** (#126). A `@Ws`, `@Stream` or HTTP
|
||||||
|
route that claims it — `@Ws('/__mesh__/control')`, `@Get('/__mesh__/control')`,
|
||||||
|
`@Ws('/__mesh__/:x')`, `/__mesh__/:rest*`, or a mountpoint that adds up to one of these — now
|
||||||
|
fails `createApp`, naming the declaration and the reserved path. A route exported by a teapot is
|
||||||
|
checked the same way, and fails the teacup's boot. Before, the Node listener served a user route
|
||||||
|
there whenever no mesh control channel was configured, while `app.upgrade` (Deno, Bun, the edge)
|
||||||
|
always refused it, so the same route worked on one runtime and not the others. A pattern whose
|
||||||
|
first segment is not the literal `__mesh__` (`/:org/:repo`, `/:rest*`) still boots; the reserved
|
||||||
|
path is answered ahead of the route table on every runtime, so such a route never sees it.
|
||||||
|
|
||||||
|
An upgrade to `/__mesh__/control` on an app with no control channel is now refused identically
|
||||||
|
everywhere: the Node listener accepts it and closes `1008` with
|
||||||
|
`mesh control channel not enabled: this app exports nothing, or has no mesh.secret`, as
|
||||||
|
`app.upgrade` already did. An app with no `@Ws`/`@Stream` routes and no mesh attaches no upgrade
|
||||||
|
listener on Node, as before, so there the request still reaches the HTTP route table.
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
- **Health probes: `createApp({ health: true })`** (#115). Off by default. `GET`/`HEAD /__live__`
|
||||||
|
answers `200 {"status":"ok"}` whenever the process answers. `/__ready__` answers
|
||||||
|
`503 {"status":"booting"}` until `boot()` resolves, then `200 {"status":"ok"}` or
|
||||||
|
`200 {"status":"degraded","degraded":[…]}` (from `app.degraded()`), and
|
||||||
|
`503 {"status":"draining"}` from the moment `close()` starts: Node `app.close()`, and the
|
||||||
|
`close()` that `serveDeno()`/`serveBun()` return. Probes are answered by the adapter, ahead of
|
||||||
|
`maxConcurrentRequests` and the route table, so they are never shed and run no step, provider,
|
||||||
|
plugin or `onError`, and emit no lifecycle event (`logRequests` and metrics plugins do not see
|
||||||
|
them). Security headers still apply, plus `cache-control: no-store`; other methods get `405` with
|
||||||
|
`Allow: GET, HEAD`. While `health` is on, a route at either path fails the boot, local or spliced
|
||||||
|
from a teapot. A probe through `app.fetch` before the boot starts the boot without waiting for it.
|
||||||
|
|
||||||
|
`health: { drainDelayMs }` (default 0) keeps the listener open that long after `close()` starts,
|
||||||
|
with `/__ready__` already answering `503`, before connections drain. Without it Node closes idle
|
||||||
|
keep-alive connections at once, so a probe usually sees a refused connection rather than a `503`.
|
||||||
|
The window is spent out of the shutdown budget; `createApp` throws when `drainDelayMs` plus
|
||||||
|
`teardownTimeoutMs` exceeds `shutdownTimeoutMs`, and on any `health` value other than `true`,
|
||||||
|
`false` or `{ drainDelayMs?: number }`. On the edge there is no `close()`, so `/__ready__` never
|
||||||
|
reports `draining` there.
|
||||||
|
|
||||||
- **`createApp({ compression })`** (#112, D13): response compression, off by default. `true`, or
|
- **`createApp({ compression })`** (#112, D13): response compression, off by default. `true`, or
|
||||||
`{ threshold?, encodings? }` (default `1024` bytes and `['br', 'gzip']`, in preference order).
|
`{ threshold?, encodings? }` (default `1024` bytes and `['br', 'gzip']`, in preference order).
|
||||||
`Accept-Encoding` is negotiated with q-values, `identity`, `*` and `q=0`, and ties go to server
|
`Accept-Encoding` is negotiated with q-values, `identity`, `*` and `q=0`, and ties go to server
|
||||||
@@ -140,8 +192,21 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or
|
param hit −88%, method miss −94%, path miss −96%; at 10 routes, every cell is within noise or
|
||||||
faster (late param hit +3.4%, 95% CI −5.0…+12.6%).
|
faster (late param hit +3.4%, 95% CI −5.0…+12.6%).
|
||||||
|
|
||||||
|
- **A query string keeps every `?` after the first** (GitHub #48). `parseQuery` took the text
|
||||||
|
between the first and second `?`, so `/search?q=what?now` gave `q: 'what'` and dropped the rest.
|
||||||
|
RFC 3986 §3.4 allows `?` inside a query, so the query string is now everything after the first
|
||||||
|
`?` and before `#`, if there is one: `q: 'what?now'`, and `/search?a=1&b=?` gives `b: '?'`. URLs
|
||||||
|
with a single `?` parse as before. Path extraction is unchanged.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler`
|
||||||
|
never read the header for HTTP, so IP-keyed plugins such as rate-limit saw `''`, one bucket for
|
||||||
|
every client. Under `trustProxy: true` the header now sets `ctx.ip`, and it wins over
|
||||||
|
`x-forwarded-for`, because Cloudflare sets it itself while XFF can carry hops the client supplied.
|
||||||
|
Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a
|
||||||
|
bare `app.fetch`, ignore it as before.
|
||||||
|
|
||||||
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
|
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
|
||||||
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
|
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
|
||||||
was served. Containment now compares real paths: the requested file, and a directory's
|
was served. Containment now compares real paths: the requested file, and a directory's
|
||||||
|
|||||||
@@ -144,6 +144,7 @@ without growing the runtime dependency tree past `reflect-metadata`:
|
|||||||
- **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. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
|
- **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. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
|
||||||
- **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 })`.
|
||||||
|
- **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers that failed) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`.
|
||||||
- **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.
|
- **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.
|
- **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.
|
||||||
|
|||||||
+116
-10
@@ -7,7 +7,8 @@ import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
|||||||
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
|
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
|
||||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
|
||||||
import type { HttpOptions } from '../http';
|
import type { HttpOptions } from '../http';
|
||||||
import { buildFetch } from '../http/web';
|
import { trustedProxyClient } from '../http/peer';
|
||||||
|
import { answerFetchProbe, buildFetch } from '../http/web';
|
||||||
import { resolveCompression, edgeMarker, MARK_EDGE, type CompressionOptions } from '../http/compression';
|
import { resolveCompression, edgeMarker, MARK_EDGE, type CompressionOptions } from '../http/compression';
|
||||||
import {
|
import {
|
||||||
boundInbound,
|
boundInbound,
|
||||||
@@ -45,13 +46,15 @@ import { connectLink, isPermanentRefusal, type Link } from '../mesh/link';
|
|||||||
import { Rooms } from '../rooms';
|
import { Rooms } from '../rooms';
|
||||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||||
import { buildRemote } from '../mesh/teacup';
|
import { buildRemote } from '../mesh/teacup';
|
||||||
import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot';
|
import { buildManifest, createMeshControl, MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot';
|
||||||
import type { MeshControl } from '../http';
|
import type { MeshControl } from '../http';
|
||||||
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
|
||||||
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
|
||||||
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
import { inspectRoute, buildGraphView, explainRoute } from './introspect';
|
||||||
import { compilePattern, markRemoteRoute, normalizeRequestPath } from '../http/router';
|
import { compilePattern, markRemoteRoute, normalizeRequestPath } from '../http/router';
|
||||||
import { routeConflict, type Precedence, type RouteConflict } from '../http/route-conflicts';
|
import { routeConflict, type Precedence, type RouteConflict } from '../http/route-conflicts';
|
||||||
|
import { assertNotReserved, type ReservedPath } from '../http/reserved-paths';
|
||||||
|
import { HEALTH_DRAIN, HEALTH_RESERVED, resolveHealth, trackHealth, type HealthConfig } from '../http/health';
|
||||||
|
|
||||||
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
|
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
|
||||||
|
|
||||||
@@ -121,6 +124,27 @@ export function createApp(opts: {
|
|||||||
limits?: RequestLimits;
|
limits?: RequestLimits;
|
||||||
devGraph?: boolean;
|
devGraph?: boolean;
|
||||||
devOpenapi?: boolean;
|
devOpenapi?: boolean;
|
||||||
|
/**
|
||||||
|
* Serve `GET`/`HEAD` `/__live__` and `/__ready__` for load balancers and orchestrators (default: off).
|
||||||
|
*
|
||||||
|
* - `/__live__` answers `200 {"status":"ok"}` whenever the process answers.
|
||||||
|
* - `/__ready__` answers `503 {"status":"booting"}` until `boot()` resolves, then
|
||||||
|
* `200 {"status":"ok"}` or `200 {"status":"degraded","degraded":[…]}` (see `app.degraded()`),
|
||||||
|
* and `503 {"status":"draining"}` from the moment `close()` starts.
|
||||||
|
*
|
||||||
|
* Probes skip the pipeline: no step, provider, plugin or `onError` runs and no lifecycle event is
|
||||||
|
* emitted, so `logRequests` and metrics plugins never see them. `maxConcurrentRequests` never sheds
|
||||||
|
* them. Security headers still apply, plus `cache-control: no-store`; other methods get `405`.
|
||||||
|
* While on, a route at either path fails the boot.
|
||||||
|
*
|
||||||
|
* `drainDelayMs` (default 0) keeps the listener open that long after `close()` starts, with
|
||||||
|
* `/__ready__` already answering `503`, before connections drain. Without it Node closes idle
|
||||||
|
* keep-alive connections at once, so a probe usually sees a refused connection rather than a `503`.
|
||||||
|
* The window is spent out of the shutdown budget (`shutdownTimeoutMs`), not added to it.
|
||||||
|
*
|
||||||
|
* On the edge there is no `close()`, so `/__ready__` never reports `draining` there.
|
||||||
|
*/
|
||||||
|
health?: boolean | { drainDelayMs?: number };
|
||||||
overrides?: Record<string, unknown>;
|
overrides?: Record<string, unknown>;
|
||||||
tls?: TlsOptions;
|
tls?: TlsOptions;
|
||||||
trustProxy?: boolean;
|
trustProxy?: boolean;
|
||||||
@@ -253,6 +277,7 @@ export function createApp(opts: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
validateWsLimits(opts.limits);
|
validateWsLimits(opts.limits);
|
||||||
|
const health = resolveHealth(opts.health, opts.shutdownTimeoutMs, opts.teardownTimeoutMs);
|
||||||
assertEtagOption(opts.etag);
|
assertEtagOption(opts.etag);
|
||||||
|
|
||||||
const bus = new Bus();
|
const bus = new Bus();
|
||||||
@@ -267,6 +292,8 @@ export function createApp(opts: {
|
|||||||
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
|
const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine };
|
||||||
const registry = collectModules(opts.modules, viewsCtx);
|
const registry = collectModules(opts.modules, viewsCtx);
|
||||||
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
|
const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry;
|
||||||
|
const reserved = reservedPaths(health);
|
||||||
|
assertNoReservedRoutes(routePlans, reserved);
|
||||||
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, bus);
|
provideBuiltins(registry, logger, bus);
|
||||||
@@ -298,7 +325,7 @@ export function createApp(opts: {
|
|||||||
// can only be built here, after finalize(), and never at construction time.
|
// can only be built here, after finalize(), and never at construction time.
|
||||||
const prepareGraph = async (): Promise<void> => {
|
const prepareGraph = async (): Promise<void> => {
|
||||||
if (opts.mesh && !booted) {
|
if (opts.mesh && !booted) {
|
||||||
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger);
|
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, reserved);
|
||||||
remoteRoutes = spliced.remoteRoutes;
|
remoteRoutes = spliced.remoteRoutes;
|
||||||
meshLinks.push(...spliced.meshLinks);
|
meshLinks.push(...spliced.meshLinks);
|
||||||
// Without this the error is `missing dependency: auth needed by getUser` and says nothing
|
// Without this the error is `missing dependency: auth needed by getUser` and says nothing
|
||||||
@@ -347,7 +374,7 @@ export function createApp(opts: {
|
|||||||
|
|
||||||
// Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling
|
// Boots exactly once, however first triggered (app.fetch, app.upgrade or listen()); calling
|
||||||
// several never double-boots (which would re-run provider factories and their side effects).
|
// several never double-boots (which would re-run provider factories and their side effects).
|
||||||
const bootApp = makeAppBooter(
|
const bootGraph = makeAppBooter(
|
||||||
registry,
|
registry,
|
||||||
opts.overrides,
|
opts.overrides,
|
||||||
() => orderedProviders,
|
() => orderedProviders,
|
||||||
@@ -356,6 +383,8 @@ export function createApp(opts: {
|
|||||||
ready,
|
ready,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const { bootApp, healthProbe, drain } = trackHealth(health, bootGraph, () => [...degradedProviders]);
|
||||||
|
|
||||||
const staticConfig = normalizeStatic(opts.static);
|
const staticConfig = normalizeStatic(opts.static);
|
||||||
const staticResolver = staticConfig ? buildStaticResolver(staticConfig.root, staticConfig.cacheControl) : undefined;
|
const staticResolver = staticConfig ? buildStaticResolver(staticConfig.root, staticConfig.cacheControl) : undefined;
|
||||||
|
|
||||||
@@ -372,6 +401,7 @@ export function createApp(opts: {
|
|||||||
bodyDuplicates: opts.bodyDuplicates,
|
bodyDuplicates: opts.bodyDuplicates,
|
||||||
onError: opts.onError,
|
onError: opts.onError,
|
||||||
static: staticResolver,
|
static: staticResolver,
|
||||||
|
health: healthProbe,
|
||||||
etag: opts.etag,
|
etag: opts.etag,
|
||||||
};
|
};
|
||||||
const fetchFn = buildAppFetch(
|
const fetchFn = buildAppFetch(
|
||||||
@@ -382,7 +412,10 @@ export function createApp(opts: {
|
|||||||
devRoutes,
|
devRoutes,
|
||||||
() => remoteRoutes,
|
() => remoteRoutes,
|
||||||
);
|
);
|
||||||
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits);
|
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
|
||||||
|
limits: opts.limits,
|
||||||
|
trustProxy: opts.trustProxy,
|
||||||
|
});
|
||||||
|
|
||||||
const listen = async (port: number): Promise<http.Server> => {
|
const listen = async (port: number): Promise<http.Server> => {
|
||||||
const deps = pipelineDeps;
|
const deps = pipelineDeps;
|
||||||
@@ -407,6 +440,7 @@ export function createApp(opts: {
|
|||||||
bodyDuplicates: opts.bodyDuplicates,
|
bodyDuplicates: opts.bodyDuplicates,
|
||||||
onError: opts.onError,
|
onError: opts.onError,
|
||||||
static: staticResolver,
|
static: staticResolver,
|
||||||
|
health: healthProbe,
|
||||||
etag: opts.etag,
|
etag: opts.etag,
|
||||||
});
|
});
|
||||||
server.on('close', () => closeLinks(meshLinks));
|
server.on('close', () => closeLinks(meshLinks));
|
||||||
@@ -427,13 +461,16 @@ export function createApp(opts: {
|
|||||||
removeSignalHandlers = undefined;
|
removeSignalHandlers = undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
const close = (options: { timeoutMs?: number } = {}): Promise<void> => {
|
const close = async (options: { timeoutMs?: number } = {}): Promise<void> => {
|
||||||
clearSignalHandlers();
|
clearSignalHandlers();
|
||||||
|
// `/__ready__` flips to draining first, and the listener stays open for the drain window.
|
||||||
|
const budget = await spendDrainWindow(drain, options, opts.shutdownTimeoutMs, server !== undefined);
|
||||||
|
|
||||||
return closeApp(
|
return closeApp(
|
||||||
server,
|
server,
|
||||||
meshLinks,
|
meshLinks,
|
||||||
streams,
|
streams,
|
||||||
options,
|
budget,
|
||||||
opts.shutdownTimeoutMs,
|
opts.shutdownTimeoutMs,
|
||||||
logger,
|
logger,
|
||||||
teardown,
|
teardown,
|
||||||
@@ -474,6 +511,8 @@ export function createApp(opts: {
|
|||||||
|
|
||||||
return Object.assign(app, {
|
return Object.assign(app, {
|
||||||
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
|
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
|
||||||
|
[HEALTH_DRAIN]: drain,
|
||||||
|
|
||||||
// `edgeHandler` calls this: on the edge core never encodes, whatever detection concluded.
|
// `edgeHandler` calls this: on the edge core never encodes, whatever detection concluded.
|
||||||
[MARK_EDGE]: edgeMarker(compression),
|
[MARK_EDGE]: edgeMarker(compression),
|
||||||
});
|
});
|
||||||
@@ -683,6 +722,48 @@ function resolveTransformer(
|
|||||||
return buildHtmlTransformer(html, viewsCtx);
|
return buildHtmlTransformer(html, viewsCtx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs the drain window and returns the options `closeApp` should get for what is left.
|
||||||
|
*
|
||||||
|
* The window comes out of the close budget, so close() still returns within the timeout it was
|
||||||
|
* given. Adjusted only when there is a server: without one closeApp only runs teardown, and an
|
||||||
|
* explicit timeout there earns a warning the caller never asked for.
|
||||||
|
*/
|
||||||
|
async function spendDrainWindow(
|
||||||
|
drain: () => Promise<void>,
|
||||||
|
options: { timeoutMs?: number },
|
||||||
|
shutdownTimeoutMs: number | undefined,
|
||||||
|
hasServer: boolean,
|
||||||
|
): Promise<{ timeoutMs?: number }> {
|
||||||
|
const startedAt = Date.now();
|
||||||
|
await drain();
|
||||||
|
const waited = Date.now() - startedAt;
|
||||||
|
if (!hasServer || waited === 0) return options;
|
||||||
|
|
||||||
|
const budget = options.timeoutMs ?? shutdownTimeoutMs ?? 10_000;
|
||||||
|
return { timeoutMs: Math.max(0, budget - waited) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The paths this app answers itself, ahead of the route table (D17).
|
||||||
|
*
|
||||||
|
* `/__mesh__/control` is reserved in every app, mesh or not: whether a route there is served must not
|
||||||
|
* depend on the runtime or on whether a mesh happens to be configured.
|
||||||
|
*/
|
||||||
|
function reservedPaths(health: HealthConfig | undefined): ReservedPath[] {
|
||||||
|
const mesh: ReservedPath = { path: MESH_CONTROL_PATH, purpose: 'the mesh control channel' };
|
||||||
|
// The probe paths only while health is on: with it off they are ordinary paths (CARD-17 rule 7).
|
||||||
|
return health ? [mesh, ...HEALTH_RESERVED] : [mesh];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fails the boot when a declared route claims a reserved path (see {@link assertNotReserved}). */
|
||||||
|
function assertNoReservedRoutes(routePlans: RoutePlan[], reserved: readonly ReservedPath[]): void {
|
||||||
|
for (const plan of routePlans) {
|
||||||
|
const kind = plan.transport === 'ws' ? '@Ws' : plan.transport === 'negotiate' ? '@Stream' : plan.method;
|
||||||
|
assertNotReserved(plan.pattern, `route ${kind} ${plan.pattern} at ${plan.declaration}`, reserved);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Reads every module's metadata into a fresh {@link Registry} of graph nodes, runners and exports. */
|
/** Reads every module's metadata into a fresh {@link Registry} of graph nodes, runners and exports. */
|
||||||
function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
|
function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry {
|
||||||
const registry = emptyRegistry();
|
const registry = emptyRegistry();
|
||||||
@@ -1037,6 +1118,7 @@ async function spliceRemoteScopes(
|
|||||||
bus: Bus,
|
bus: Bus,
|
||||||
registry: Registry,
|
registry: Registry,
|
||||||
logger: Logger,
|
logger: Logger,
|
||||||
|
reserved: readonly ReservedPath[],
|
||||||
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> {
|
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> {
|
||||||
const remoteRoutes: RouteDef[] = [];
|
const remoteRoutes: RouteDef[] = [];
|
||||||
const meshLinks: Link[] = [];
|
const meshLinks: Link[] = [];
|
||||||
@@ -1076,6 +1158,9 @@ async function spliceRemoteScopes(
|
|||||||
|
|
||||||
for (const route of routes) {
|
for (const route of routes) {
|
||||||
const display = `${route.method} ${route.pattern}`;
|
const display = `${route.method} ${route.pattern}`;
|
||||||
|
// A teapot's own boot refuses such a route, but the manifest is whatever arrives on the wire:
|
||||||
|
// an older or foreign teapot could still advertise one, and the teacup must not splice it.
|
||||||
|
assertNotReserved(route.pattern, `mesh: remote route '${display}' from ${teapot.url}`, reserved);
|
||||||
const key = `${route.method} ${compilePattern(route.pattern).shape}`;
|
const key = `${route.method} ${compilePattern(route.pattern).shape}`;
|
||||||
const owner = routeOwners.get(key);
|
const owner = routeOwners.get(key);
|
||||||
|
|
||||||
@@ -1438,6 +1523,17 @@ function buildAppFetch(
|
|||||||
let handler: ((request: Request) => Promise<Response>) | undefined;
|
let handler: ((request: Request) => Promise<Response>) | undefined;
|
||||||
|
|
||||||
return async (request: Request): Promise<Response> => {
|
return async (request: Request): Promise<Response> => {
|
||||||
|
// Before the boot, or `/__ready__` could never say `booting`: it would wait for the boot to end.
|
||||||
|
// The boot is still started, not awaited: on the edge, or under a bare `Deno.serve(app.fetch)`,
|
||||||
|
// nothing else may boot the app, and an orchestrator that waits for ready before sending traffic
|
||||||
|
// would wait forever. The rejection is dropped here only; the memo keeps it for real requests.
|
||||||
|
const probe = answerFetchProbe(request, fetchOpts);
|
||||||
|
|
||||||
|
if (probe) {
|
||||||
|
ensureBooted().catch(() => {});
|
||||||
|
return probe;
|
||||||
|
}
|
||||||
|
|
||||||
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
|
||||||
|
|
||||||
if (!handler) {
|
if (!handler) {
|
||||||
@@ -1460,7 +1556,7 @@ function buildAppUpgrade(
|
|||||||
streams: Set<() => void>,
|
streams: Set<() => void>,
|
||||||
ensureBooted: () => Promise<void>,
|
ensureBooted: () => Promise<void>,
|
||||||
getMeshControl: () => MeshControl | undefined,
|
getMeshControl: () => MeshControl | undefined,
|
||||||
limits?: RequestLimits,
|
{ limits, trustProxy }: { limits?: RequestLimits; trustProxy?: boolean },
|
||||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||||
let wsRoutes: WsRouteDef[] | undefined;
|
let wsRoutes: WsRouteDef[] | undefined;
|
||||||
|
|
||||||
@@ -1492,7 +1588,7 @@ function buildAppUpgrade(
|
|||||||
// an explicit refusal, not "no matching ws route": the path is reserved either way, and a
|
// an explicit refusal, not "no matching ws route": the path is reserved either way, and a
|
||||||
// peer that reached a teapot with nothing exported deserves to be told which it was
|
// peer that reached a teapot with nothing exported deserves to be told which it was
|
||||||
if (!meshControl) {
|
if (!meshControl) {
|
||||||
ready.close(1008, 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret');
|
ready.close(1008, MESH_CONTROL_DISABLED_REASON);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1509,10 +1605,20 @@ function buildAppUpgrade(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await runWsConnection(ready, request, route, deps.bus, streams);
|
await runWsConnection(ready, withProxyClient(request, trustProxy), route, deps.bus, streams);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `request` with `ip` taken from the proxy header its adapter recorded, when `trustProxy` allows it
|
||||||
|
* (the edge adapter's `cf-connecting-ip`, CARD-23); otherwise `request` unchanged. The same check
|
||||||
|
* `app.fetch` runs, so an edge WebSocket upgrade and an edge HTTP request resolve `ctx.ip` alike.
|
||||||
|
*/
|
||||||
|
function withProxyClient(request: WsRequest, trustProxy: boolean | undefined): WsRequest {
|
||||||
|
const ip = trustedProxyClient(request, trustProxy);
|
||||||
|
return ip ? { ...request, ip } : request;
|
||||||
|
}
|
||||||
|
|
||||||
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
|
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
|
||||||
function devGraphRoute(graph: () => GraphView): RouteDef {
|
function devGraphRoute(graph: () => GraphView): RouteDef {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -37,6 +37,15 @@ export interface Explain {
|
|||||||
/** A running application instance with lifecycle, introspection and graph-export methods. */
|
/** A running application instance with lifecycle, introspection and graph-export methods. */
|
||||||
export interface App {
|
export interface App {
|
||||||
listen(port: number): Promise<http.Server>;
|
listen(port: number): Promise<http.Server>;
|
||||||
|
/**
|
||||||
|
* Drains in-flight work, closes the server and mesh links, then runs teardown, all within
|
||||||
|
* `timeoutMs` (default `shutdownTimeoutMs`, else 10s).
|
||||||
|
*
|
||||||
|
* With `createApp({ health })` on, `/__ready__` answers `503 {"status":"draining"}` from the first
|
||||||
|
* line of this call, and the listener stays open for `health.drainDelayMs` before draining starts.
|
||||||
|
* That window is part of `timeoutMs`. On Deno and Bun the same happens in the `close()` that
|
||||||
|
* `serveDeno()`/`serveBun()` return.
|
||||||
|
*/
|
||||||
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
|
* Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or
|
||||||
|
|||||||
+6
-1
@@ -2,6 +2,7 @@ import { channel } from './channel';
|
|||||||
import type { Channel } from './channel';
|
import type { Channel } from './channel';
|
||||||
import type { App } from './app/types';
|
import type { App } from './app/types';
|
||||||
import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core';
|
import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core';
|
||||||
|
import { beginDrain } from './http/health';
|
||||||
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
|
||||||
import { closeWithDeadline } from './http/shutdown';
|
import { closeWithDeadline } from './http/shutdown';
|
||||||
import { setPeer } from './http/peer';
|
import { setPeer } from './http/peer';
|
||||||
@@ -149,7 +150,11 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
|||||||
// registry, which is what makes one `close()` enough here instead of two. Called without
|
// registry, which is what makes one `close()` enough here instead of two. Called without
|
||||||
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
|
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
|
||||||
// and the deadline below already bounds the whole call.
|
// and the deadline below already bounds the whole call.
|
||||||
() => server.stop(false).then(() => app.close()),
|
// The drain window first: `/__ready__` answers 503 while the listener is still open (D14).
|
||||||
|
() =>
|
||||||
|
beginDrain(app)
|
||||||
|
.then(() => server.stop(false))
|
||||||
|
.then(() => app.close()),
|
||||||
() => void server.stop(true),
|
() => void server.stop(true),
|
||||||
closeOptions.timeoutMs ?? 10_000,
|
closeOptions.timeoutMs ?? 10_000,
|
||||||
(ms) =>
|
(ms) =>
|
||||||
|
|||||||
+6
-1
@@ -1,4 +1,5 @@
|
|||||||
import type { App } from './app/types';
|
import type { App } from './app/types';
|
||||||
|
import { beginDrain } from './http/health';
|
||||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||||
import { closeWithDeadline } from './http/shutdown';
|
import { closeWithDeadline } from './http/shutdown';
|
||||||
import { setPeer } from './http/peer';
|
import { setPeer } from './http/peer';
|
||||||
@@ -102,7 +103,11 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
|
|||||||
// registry, which is what makes one `close()` enough here instead of two. Called without
|
// registry, which is what makes one `close()` enough here instead of two. Called without
|
||||||
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
|
// options on purpose: passing a timeout it cannot use to drain would only earn its warning,
|
||||||
// and the deadline below already bounds the whole call.
|
// and the deadline below already bounds the whole call.
|
||||||
() => server.shutdown().then(() => app.close()),
|
// The drain window first: `/__ready__` answers 503 while the listener is still open (D14).
|
||||||
|
() =>
|
||||||
|
beginDrain(app)
|
||||||
|
.then(() => server.shutdown())
|
||||||
|
.then(() => app.close()),
|
||||||
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
|
// Nothing to force, and that is Deno's constraint rather than an omission here. Its two
|
||||||
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
|
// levers are mutually exclusive: aborting the serve signal after `shutdown()` is already
|
||||||
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
|
// pending throws `BadResource: Bad resource ID` from Deno's own abort listener, which
|
||||||
|
|||||||
+16
-1
@@ -1,5 +1,6 @@
|
|||||||
import type { App } from './app/types';
|
import type { App } from './app/types';
|
||||||
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
|
||||||
|
import { setProxyClient } from './http/peer';
|
||||||
import { MARK_EDGE } from './http/compression';
|
import { MARK_EDGE } from './http/compression';
|
||||||
|
|
||||||
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
|
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
|
||||||
@@ -36,7 +37,9 @@ export function edgeHandler(
|
|||||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||||
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
|
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
|
||||||
server.accept();
|
server.accept();
|
||||||
const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? '');
|
// No peer address on the edge, so `ip` starts empty; the header only fills it under `trustProxy`.
|
||||||
|
const wsReq = toWsRequest(request, '');
|
||||||
|
recordClient(wsReq, request);
|
||||||
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
|
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
|
||||||
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
|
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
|
||||||
else void lifecycle;
|
else void lifecycle;
|
||||||
@@ -44,6 +47,18 @@ export function edgeHandler(
|
|||||||
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
|
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
recordClient(request, request);
|
||||||
return app.fetch(request);
|
return app.fetch(request);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hands the app the `cf-connecting-ip` header for `source`, the object the app will be given for this
|
||||||
|
* request. The app — not this adapter — decides whether it counts, since `trustProxy` is an app
|
||||||
|
* option; HTTP and WebSocket both go through here and through the same check on the app side.
|
||||||
|
* Without `trustProxy` the header is ignored and `ctx.ip` stays `''`: workerd exposes no peer address,
|
||||||
|
* and an untrusted header is whatever the client chose to send.
|
||||||
|
*/
|
||||||
|
function recordClient(source: object, request: Request): void {
|
||||||
|
setProxyClient(source, request.headers.get('cf-connecting-ip') ?? '');
|
||||||
|
}
|
||||||
+36
-3
@@ -42,10 +42,43 @@ export interface GraphNode {
|
|||||||
origin: string;
|
origin: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Orders nodes so every dependency precedes its dependents; throws on missing keys or cycles. */
|
/**
|
||||||
export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] {
|
* Maps every token to the one node that produces it; throws when a second node provides a token.
|
||||||
|
*
|
||||||
|
* One producer per token, across modules, plugins, mesh steps and built-ins alike (GitHub #35, D9).
|
||||||
|
* This used to be `producedBy.set(key, node)`, last one wins: plugin nodes are registered after
|
||||||
|
* module nodes, so a plugin's `scope.add` that provided `user` silently replaced the app's own `user`
|
||||||
|
* for every route that needed it. Checking here, on the whole graph, rather than at each place a node
|
||||||
|
* is registered, is what covers every path — current and future — and makes the built-in tokens
|
||||||
|
* (`logger`, `rooms`, `events`) safe by rule instead of by registration order.
|
||||||
|
*/
|
||||||
|
function producers(nodes: GraphNode[]): Map<string, GraphNode> {
|
||||||
const producedBy = new Map<string, GraphNode>();
|
const producedBy = new Map<string, GraphNode>();
|
||||||
for (const node of nodes) for (const key of node.provides) producedBy.set(key, node);
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
for (const key of node.provides) {
|
||||||
|
const prior = producedBy.get(key);
|
||||||
|
|
||||||
|
if (prior && prior !== node) {
|
||||||
|
throw new Error(
|
||||||
|
`token '${key}' is provided twice: by '${prior.name}' (${prior.origin}) and by '${node.name}' (${node.origin}) — ` +
|
||||||
|
'a token has exactly one producer; rename one of them, or use `overrides` to replace a runner',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
producedBy.set(key, node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return producedBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Orders nodes so every dependency precedes its dependents; throws on a token with two producers,
|
||||||
|
* missing keys or cycles.
|
||||||
|
*/
|
||||||
|
export function topoSort(nodes: GraphNode[], seedKeys: string[], note = ''): GraphNode[] {
|
||||||
|
const producedBy = producers(nodes);
|
||||||
|
|
||||||
// validate dependencies exist
|
// validate dependencies exist
|
||||||
for (const node of nodes) {
|
for (const node of nodes) {
|
||||||
|
|||||||
@@ -0,0 +1,170 @@
|
|||||||
|
import type { ReservedPath } from './reserved-paths';
|
||||||
|
|
||||||
|
/** Liveness probe path: `200` whenever the process answers. */
|
||||||
|
export const LIVE_PATH = '/__live__';
|
||||||
|
/** Readiness probe path: `503` while booting or draining, `200` otherwise. */
|
||||||
|
export const READY_PATH = '/__ready__';
|
||||||
|
|
||||||
|
/** The probe paths, as reserved-path entries for the boot check (only while `health` is on). */
|
||||||
|
export const HEALTH_RESERVED: readonly ReservedPath[] = [
|
||||||
|
{ path: LIVE_PATH, purpose: 'the liveness probe, health: true' },
|
||||||
|
{ path: READY_PATH, purpose: 'the readiness probe, health: true' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where an app is in its life, as `/__ready__` reports it.
|
||||||
|
*
|
||||||
|
* `booting` until `boot()` resolves, `ready` after, `draining` from the moment `close()` starts.
|
||||||
|
* Moves forward only: a boot that finishes while draining does not make the app ready again.
|
||||||
|
*/
|
||||||
|
export type HealthPhase = 'booting' | 'ready' | 'draining';
|
||||||
|
|
||||||
|
/** What the adapters read to answer a probe. Lives on {@link HttpOptions}; absent when `health` is off. */
|
||||||
|
export interface HealthProbe {
|
||||||
|
phase(): HealthPhase;
|
||||||
|
/** Optional providers that failed to boot, as `app.degraded()` reports them. */
|
||||||
|
degraded(): string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Close-time hook on the app object for the adapters that own the server (`serveDeno`, `serveBun`):
|
||||||
|
* marks the app draining and resolves after `drainDelayMs`, so the listener stays open while
|
||||||
|
* `/__ready__` answers `503`. Idempotent — later calls share the first window. Symbol-keyed because it
|
||||||
|
* is adapter plumbing, not public API.
|
||||||
|
*/
|
||||||
|
export const HEALTH_DRAIN: unique symbol = Symbol.for('green-tea.health-drain');
|
||||||
|
|
||||||
|
/** Starts the drain window on `app` (see {@link HEALTH_DRAIN}); resolves at once when health is off. */
|
||||||
|
export function beginDrain(app: object): Promise<void> {
|
||||||
|
return (app as { [HEALTH_DRAIN]?: () => Promise<void> })[HEALTH_DRAIN]?.() ?? Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A probe response, before the adapter merges in the injected security headers. */
|
||||||
|
export interface ProbeAnswer {
|
||||||
|
status: number;
|
||||||
|
headers: Record<string, string>;
|
||||||
|
body: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const JSON_NO_STORE = { 'content-type': 'application/json', 'cache-control': 'no-store' };
|
||||||
|
|
||||||
|
/** The readiness body and status for the current phase. */
|
||||||
|
function readiness(probe: HealthProbe): { status: number; body: object } {
|
||||||
|
const phase = probe.phase();
|
||||||
|
if (phase === 'booting') return { status: 503, body: { status: 'booting' } };
|
||||||
|
if (phase === 'draining') return { status: 503, body: { status: 'draining' } };
|
||||||
|
|
||||||
|
const degraded = probe.degraded();
|
||||||
|
return degraded.length
|
||||||
|
? { status: 200, body: { status: 'degraded', degraded } }
|
||||||
|
: { status: 200, body: { status: 'ok' } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Answers `/__live__` or `/__ready__`, or returns `undefined` for any other path.
|
||||||
|
*
|
||||||
|
* Called by each adapter before the request gate and before `handle()`, so a probe runs no step,
|
||||||
|
* provider, plugin or `onError`, emits no lifecycle event, and is never shed by
|
||||||
|
* `maxConcurrentRequests`. `url` may carry a query string; only the exact path is a probe.
|
||||||
|
*/
|
||||||
|
export function answerProbe(method: string, url: string, probe: HealthProbe): ProbeAnswer | undefined {
|
||||||
|
const query = url.indexOf('?');
|
||||||
|
const path = query === -1 ? url : url.slice(0, query);
|
||||||
|
if (path !== LIVE_PATH && path !== READY_PATH) return undefined;
|
||||||
|
|
||||||
|
if (method !== 'GET' && method !== 'HEAD') {
|
||||||
|
return {
|
||||||
|
status: 405,
|
||||||
|
headers: { ...JSON_NO_STORE, allow: 'GET, HEAD' },
|
||||||
|
body: JSON.stringify({ error: 'Method Not Allowed' }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const { status, body } = path === LIVE_PATH ? { status: 200, body: { status: 'ok' } } : readiness(probe);
|
||||||
|
return { status, headers: { ...JSON_NO_STORE }, body: method === 'HEAD' ? '' : JSON.stringify(body) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `createApp({ health })`, normalised. `undefined` when health is off. */
|
||||||
|
export interface HealthConfig {
|
||||||
|
drainDelayMs: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates `createApp({ health })` and normalises it. Throws on anything but `true`, `false`,
|
||||||
|
* `undefined` or `{ drainDelayMs?: number }`, and on a `drainDelayMs` that does not fit in the shutdown
|
||||||
|
* budget next to the teardown reservation.
|
||||||
|
*/
|
||||||
|
export function resolveHealth(
|
||||||
|
health: unknown,
|
||||||
|
shutdownTimeoutMs: number | undefined,
|
||||||
|
teardownTimeoutMs: number | undefined,
|
||||||
|
): HealthConfig | undefined {
|
||||||
|
if (health === undefined || health === false) return undefined;
|
||||||
|
if (health === true) return { drainDelayMs: 0 };
|
||||||
|
|
||||||
|
if (typeof health !== 'object' || health === null || Array.isArray(health)) {
|
||||||
|
throw new Error(`health must be true, false or { drainDelayMs?: number } — got ${JSON.stringify(health)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const unknown = Object.keys(health).filter((key) => key !== 'drainDelayMs');
|
||||||
|
|
||||||
|
if (unknown.length) {
|
||||||
|
throw new Error(
|
||||||
|
`health: unknown option ${unknown.map((key) => `'${key}'`).join(', ')} — only drainDelayMs is supported`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const drainDelayMs = (health as { drainDelayMs?: unknown }).drainDelayMs ?? 0;
|
||||||
|
|
||||||
|
if (typeof drainDelayMs !== 'number' || !Number.isFinite(drainDelayMs) || drainDelayMs < 0) {
|
||||||
|
throw new Error(`health.drainDelayMs must be a non-negative number of milliseconds — got ${String(drainDelayMs)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const budget = shutdownTimeoutMs ?? 10_000;
|
||||||
|
const reserved = teardownTimeoutMs ?? 0;
|
||||||
|
|
||||||
|
if (drainDelayMs + reserved > budget) {
|
||||||
|
throw new Error(
|
||||||
|
`health.drainDelayMs (${drainDelayMs}) plus teardownTimeoutMs (${reserved}) cannot exceed ` +
|
||||||
|
`shutdownTimeoutMs (${budget}) — the drain window is spent out of the shutdown budget, ` +
|
||||||
|
'so close() would have no time left to drain connections or run teardown.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { drainDelayMs };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The health state machine for one app: wraps `bootGraph` so a resolved boot marks it ready, and
|
||||||
|
* offers the drain that `close()` (and `serveDeno`/`serveBun` through {@link HEALTH_DRAIN}) starts.
|
||||||
|
* With health off the probe is absent and the drain resolves at once.
|
||||||
|
*/
|
||||||
|
export function trackHealth(
|
||||||
|
health: HealthConfig | undefined,
|
||||||
|
bootGraph: () => Promise<void>,
|
||||||
|
degraded: () => string[],
|
||||||
|
): { bootApp: () => Promise<void>; healthProbe: HealthProbe | undefined; drain: () => Promise<void> } {
|
||||||
|
// Forward only: a boot that resolves after close() started stays draining.
|
||||||
|
let phase: HealthPhase = 'booting';
|
||||||
|
// Shared by every drain call. Left referenced on purpose: the process must stay up for the window.
|
||||||
|
let drainWindow: Promise<void> | undefined;
|
||||||
|
|
||||||
|
const bootApp = async (): Promise<void> => {
|
||||||
|
await bootGraph();
|
||||||
|
if (phase === 'booting') phase = 'ready';
|
||||||
|
};
|
||||||
|
|
||||||
|
const drain = (): Promise<void> => {
|
||||||
|
if (!health) return Promise.resolve();
|
||||||
|
|
||||||
|
if (!drainWindow) {
|
||||||
|
phase = 'draining';
|
||||||
|
const ms = health.drainDelayMs;
|
||||||
|
drainWindow = ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
return drainWindow;
|
||||||
|
};
|
||||||
|
|
||||||
|
return { bootApp, healthProbe: health ? { phase: () => phase, degraded } : undefined, drain };
|
||||||
|
}
|
||||||
@@ -25,3 +25,28 @@ export function setPeer(request: Request, ip: string): void {
|
|||||||
export function peerOf(request: Request): string {
|
export function peerOf(request: Request): string {
|
||||||
return peers.get(request) ?? '';
|
return peers.get(request) ?? '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The client address a runtime adapter read from a header its platform's proxy sets — today only the
|
||||||
|
// edge adapter, from `cf-connecting-ip`. Unlike the socket peer above, a header is client-supplied
|
||||||
|
// unless a proxy in front overwrites it, so it only counts under `trustProxy`; the adapter cannot
|
||||||
|
// decide that, because the option lives on the app, so it records the value and the app decides.
|
||||||
|
// Keyed by the `Request` (HTTP) or the `WsRequest` (WebSocket upgrade) the adapter hands the app, for
|
||||||
|
// the same reasons as the peer: no handler-visible header, no extra public parameter. Same
|
||||||
|
// `globalThis` registration, because `@green-tea/core/edge` is a separate bundle too.
|
||||||
|
const PROXY_KEY = Symbol.for('@green-tea/core:proxy-client');
|
||||||
|
const proxyRegistry = globalThis as { [PROXY_KEY]?: WeakMap<object, string> };
|
||||||
|
const proxyClients = (proxyRegistry[PROXY_KEY] ??= new WeakMap<object, string>());
|
||||||
|
|
||||||
|
/** Records `ip` as the client address a proxy header named for `source`. An empty value is not recorded. */
|
||||||
|
export function setProxyClient(source: object, ip: string): void {
|
||||||
|
if (ip) proxyClients.set(source, ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The client address an adapter recorded for `source` from a proxy header, when `trustProxy` is on;
|
||||||
|
* `''` otherwise. The one check both `app.fetch` and `app.upgrade` run, so HTTP and WebSocket cannot
|
||||||
|
* disagree about whether the header counts.
|
||||||
|
*/
|
||||||
|
export function trustedProxyClient(source: object, trustProxy: boolean | undefined): string {
|
||||||
|
return trustProxy ? (proxyClients.get(source) ?? '') : '';
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { compilePattern, matchPattern } from './router';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A path the framework answers itself, ahead of the route table, so no declared route may claim it.
|
||||||
|
*
|
||||||
|
* Each adapter intercepts these before route matching. A user route that could also match one would
|
||||||
|
* be served on some code paths and shadowed on others, which is exactly the "works on Node, refused
|
||||||
|
* on Deno" split a reserved path exists to prevent, so the boot refuses it instead.
|
||||||
|
*/
|
||||||
|
export interface ReservedPath {
|
||||||
|
/** The concrete request path, e.g. `/__mesh__/control`. */
|
||||||
|
path: string;
|
||||||
|
/** What the framework serves there, for the error message (e.g. `the mesh control channel`). */
|
||||||
|
purpose: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the reserved path `pattern` would claim, or `undefined` when it claims none.
|
||||||
|
*
|
||||||
|
* A pattern claims a reserved path when it matches it *and* its first segment is the reserved path's
|
||||||
|
* own first segment, spelled literally. The literal-prefix half is deliberate: `/:org/:repo` or a
|
||||||
|
* `/:rest*` fallback also match `/__mesh__/control`, but they never ask for it — the adapter intercepts
|
||||||
|
* the reserved path before matching, so such a route simply never sees that one path, the same way
|
||||||
|
* on every runtime. Refusing them would fail the boot of ordinary apps for a path they never named.
|
||||||
|
* A literal pattern is therefore checked by equality and a parameterised one (`/__mesh__/:x`,
|
||||||
|
* `/__mesh__/:rest*`) by matching the reserved path against it.
|
||||||
|
*/
|
||||||
|
export function claimedReservedPath(pattern: string, reserved: readonly ReservedPath[]): ReservedPath | undefined {
|
||||||
|
const first = compilePattern(pattern).segments[0];
|
||||||
|
if (first?.kind !== 'static') return undefined;
|
||||||
|
|
||||||
|
return reserved.find(
|
||||||
|
(entry) => entry.path.split('/')[1] === first.value && matchPattern(pattern, entry.path) !== undefined,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Throws when `pattern` claims a reserved path. `subject` names the declaration for the message,
|
||||||
|
* e.g. `route GET /__mesh__/control at Chat.control`.
|
||||||
|
*/
|
||||||
|
export function assertNotReserved(pattern: string, subject: string, reserved: readonly ReservedPath[]): void {
|
||||||
|
const claimed = claimedReservedPath(pattern, reserved);
|
||||||
|
if (!claimed) return;
|
||||||
|
|
||||||
|
throw new Error(
|
||||||
|
`${subject} uses the reserved path ${claimed.path} (${claimed.purpose}) — ` +
|
||||||
|
'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.',
|
||||||
|
);
|
||||||
|
}
|
||||||
+15
-10
@@ -743,18 +743,23 @@ export function allowedMethods(routes: RouteDef[], path: string): string[] {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Parses a URL's query string into a flat string map (last value wins for repeated keys). */
|
/**
|
||||||
|
* Parses a URL's query string into a flat string map (last value wins for repeated keys).
|
||||||
|
*
|
||||||
|
* The query string is everything after the **first** `?` and before a `#`, if one is present.
|
||||||
|
* A `?` inside the query is a legal character (RFC 3986 §3.4), so `/search?q=what?now` gives
|
||||||
|
* `{ q: 'what?now' }`.
|
||||||
|
*/
|
||||||
export function parseQuery(url: string): Record<string, string> {
|
export function parseQuery(url: string): Record<string, string> {
|
||||||
// Most requests carry no query string, and the work below is not free for them: `split` builds
|
// Most requests carry no query string, and the work below is not free for them:
|
||||||
// an array, `new URLSearchParams('')` builds an object, and the loop runs zero times — three
|
// `new URLSearchParams('')` builds an object and the loop runs zero times, to arrive at `{}`.
|
||||||
// allocations to arrive at `{}`. Measured at 92.3 ns against 18.6 ns for this check.
|
// Measured at 92.3 ns against 18.6 ns for this check.
|
||||||
//
|
const start = url.indexOf('?');
|
||||||
// Only the guard is new; the parse below is untouched on purpose. Reaching for `indexOf` +
|
if (start < 0) return {};
|
||||||
// `slice` instead of `split` would also drop an allocation, but it changes what a second `?`
|
|
||||||
// means, and that is a behaviour question rather than a performance one.
|
|
||||||
if (!url.includes('?')) return {};
|
|
||||||
|
|
||||||
const queryString = url.split('?')[1] ?? '';
|
// `split('?')[1]` used to stop at a second `?` and drop the rest of the value (GitHub #48).
|
||||||
|
const hash = url.indexOf('#', start + 1);
|
||||||
|
const queryString = hash < 0 ? url.slice(start + 1) : url.slice(start + 1, hash);
|
||||||
const out: Record<string, string> = {};
|
const out: Record<string, string> = {};
|
||||||
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
|
for (const [key, value] of new URLSearchParams(queryString)) out[key] = value;
|
||||||
return out;
|
return out;
|
||||||
|
|||||||
+55
-23
@@ -2,7 +2,7 @@ import type http from 'http';
|
|||||||
import type https from 'https';
|
import type https from 'https';
|
||||||
import { createRequestGate } from './request-gate';
|
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, Correlation } from '../bus';
|
||||||
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';
|
||||||
@@ -20,6 +20,7 @@ import type { BodyFailure, BodyReader } from './body';
|
|||||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||||
import type { Logger } from '../logger';
|
import type { Logger } from '../logger';
|
||||||
import { nodeRequire } from '../node-require';
|
import { nodeRequire } from '../node-require';
|
||||||
|
import { answerProbe } from './health';
|
||||||
import { compressOutcome } from './compression';
|
import { compressOutcome } from './compression';
|
||||||
|
|
||||||
interface HandlerConfig {
|
interface HandlerConfig {
|
||||||
@@ -117,6 +118,8 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
const injected = computeInjected(opts, { secure, headers: req.headers });
|
const injected = computeInjected(opts, { secure, headers: req.headers });
|
||||||
patchResponseHeaders(res, injected);
|
patchResponseHeaders(res, injected);
|
||||||
|
|
||||||
|
if (writeProbe(req, res, opts)) return;
|
||||||
|
|
||||||
let result: HandleResult | Preflight;
|
let result: HandleResult | Preflight;
|
||||||
let acquired = false;
|
let acquired = false;
|
||||||
const watching = watchingRequests(bus);
|
const watching = watchingRequests(bus);
|
||||||
@@ -180,31 +183,60 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ('preflight' in result) {
|
await writeResult(req, res, result, { opts, bus, correlation });
|
||||||
res.writeHead(204, result.preflight);
|
|
||||||
res.end();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Not awaited unless compression actually returned a promise: an app without it keeps the
|
|
||||||
// synchronous write it had.
|
|
||||||
const decided = compressOutcome(
|
|
||||||
opts?.compression,
|
|
||||||
{ method: req.method ?? 'GET', headers: req.headers },
|
|
||||||
result.outcome,
|
|
||||||
);
|
|
||||||
const outcome = decided instanceof Promise ? await decided : decided;
|
|
||||||
|
|
||||||
if (outcome.kind === 'stream') {
|
|
||||||
await pipeStream(res, outcome, bus, opts?.streams, correlation);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
res.writeHead(outcome.status, outcome.headers);
|
|
||||||
res.end(outcome.body);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes what `handle()` produced: a preflight, or an outcome after `compressOutcome` (CARD-16).
|
||||||
|
* Module scope rather than inside `serve`, whose closure would charge every branch here again.
|
||||||
|
*/
|
||||||
|
async function writeResult(
|
||||||
|
req: http.IncomingMessage,
|
||||||
|
res: http.ServerResponse,
|
||||||
|
result: HandleResult | Preflight,
|
||||||
|
ctx: { opts: HttpOptions | undefined; bus: Bus | undefined; correlation: Correlation },
|
||||||
|
): Promise<void> {
|
||||||
|
const { opts, bus, correlation } = ctx;
|
||||||
|
|
||||||
|
if ('preflight' in result) {
|
||||||
|
res.writeHead(204, result.preflight);
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not awaited unless compression actually returned a promise: an app without it keeps the
|
||||||
|
// synchronous write it had.
|
||||||
|
const decided = compressOutcome(
|
||||||
|
opts?.compression,
|
||||||
|
{ method: req.method ?? 'GET', headers: req.headers },
|
||||||
|
result.outcome,
|
||||||
|
);
|
||||||
|
const outcome = decided instanceof Promise ? await decided : decided;
|
||||||
|
|
||||||
|
if (outcome.kind === 'stream') {
|
||||||
|
await pipeStream(res, outcome, bus, opts?.streams, correlation);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.writeHead(outcome.status, outcome.headers);
|
||||||
|
res.end(outcome.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Answers a health probe and returns true, or returns false for any other request. Runs before the
|
||||||
|
* gate, so shedding never refuses a probe, and before `handle()`, so no step, plugin or lifecycle
|
||||||
|
* event sees one. Written through the patched writeHead, so the security headers still land.
|
||||||
|
*/
|
||||||
|
function writeProbe(req: http.IncomingMessage, res: http.ServerResponse, opts: HttpOptions | undefined): boolean {
|
||||||
|
const probe = opts?.health && answerProbe(req.method ?? 'GET', req.url ?? '/', opts.health);
|
||||||
|
if (!probe) return false;
|
||||||
|
|
||||||
|
res.writeHead(probe.status, probe.headers);
|
||||||
|
res.end(probe.body);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The last resort for a request whose handling rejected. Deliberately does not call `onError`: this
|
* The last resort for a request whose handling rejected. Deliberately does not call `onError`: this
|
||||||
* runs because something already failed past the point where errors convert to a response, and user
|
* runs because something already failed past the point where errors convert to a response, and user
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { Transport } from '../metadata';
|
import type { Transport } from '../metadata';
|
||||||
|
import type { HealthProbe } from './health';
|
||||||
import type { PipelineResult } from '../pipeline';
|
import type { PipelineResult } from '../pipeline';
|
||||||
import type { ErrorRenderer } from '../transformers';
|
import type { ErrorRenderer } from '../transformers';
|
||||||
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
import type { TlsOptions, SecurityOptions, CorsOptions } from '../security';
|
||||||
@@ -63,6 +64,11 @@ export interface HttpOptions {
|
|||||||
bodyDuplicates?: 'array' | 'last';
|
bodyDuplicates?: 'array' | 'last';
|
||||||
onError?: ErrorRenderer;
|
onError?: ErrorRenderer;
|
||||||
static?: StaticResolver;
|
static?: StaticResolver;
|
||||||
|
/**
|
||||||
|
* Answers `/__live__` and `/__ready__` ahead of the gate and the route table (`createApp({ health })`).
|
||||||
|
* Absent when health is off, so no path is intercepted.
|
||||||
|
*/
|
||||||
|
health?: HealthProbe;
|
||||||
/** Weak ETags + `304` for buffered `200` GET/HEAD handler responses (`createApp({ etag })`). */
|
/** Weak ETags + `304` for buffered `200` GET/HEAD handler responses (`createApp({ etag })`). */
|
||||||
etag?: boolean;
|
etag?: boolean;
|
||||||
/** Resolved `createApp({ compression })`; absent when compression is off. */
|
/** Resolved `createApp({ compression })`; absent when compression is off. */
|
||||||
|
|||||||
+28
-2
@@ -11,11 +11,12 @@ import {
|
|||||||
type Preflight,
|
type Preflight,
|
||||||
} from './core';
|
} from './core';
|
||||||
import { mergeInjectedHeaders, toWebHeaders } from './headers';
|
import { mergeInjectedHeaders, toWebHeaders } from './headers';
|
||||||
import { peerOf } from './peer';
|
import { peerOf, trustedProxyClient } from './peer';
|
||||||
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
|
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
|
||||||
import { HttpError } from '../signals';
|
import { HttpError } from '../signals';
|
||||||
import { renderError, type ErrorRequest } from '../transformers';
|
import { renderError, type ErrorRequest } from '../transformers';
|
||||||
import type { RouteDef, HttpOptions } from './types';
|
import type { RouteDef, HttpOptions } from './types';
|
||||||
|
import { answerProbe } from './health';
|
||||||
import { compressOutcome, compressWebStream } from './compression';
|
import { compressOutcome, compressWebStream } from './compression';
|
||||||
import type { NeutralOutcome } from './core';
|
import type { NeutralOutcome } from './core';
|
||||||
|
|
||||||
@@ -302,7 +303,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
|
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
|
||||||
// Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
|
// Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
|
||||||
// `app.fetch` has none, so there the answer is still ''.
|
// `app.fetch` has none, so there the answer is still ''.
|
||||||
ip: forwardedFor(headers, opts) || peerOf(request),
|
// Ahead of both, under `trustProxy` only: the address the edge adapter read from
|
||||||
|
// `cf-connecting-ip`. Cloudflare sets that header itself, while XFF can carry hops the
|
||||||
|
// client supplied, so on the edge it wins (CARD-23).
|
||||||
|
ip: trustedProxyClient(request, opts?.trustProxy) || forwardedFor(headers, opts) || peerOf(request),
|
||||||
},
|
},
|
||||||
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
|
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
|
||||||
// one call per request.
|
// one call per request.
|
||||||
@@ -329,3 +333,25 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
: outcomeToResponse(decided, injected, opts?.bus, correlation);
|
: outcomeToResponse(decided, injected, opts?.bus, correlation);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Answers a health probe through the Fetch API, or returns `undefined` for any other request (or when
|
||||||
|
* `health` is off). `app.fetch` calls this before awaiting the boot, which is what lets `/__ready__`
|
||||||
|
* report `booting` at all, and before the gate and `handle()`, for the same reasons as the Node adapter.
|
||||||
|
*/
|
||||||
|
export function answerFetchProbe(request: Request, opts: HttpOptions | undefined): Response | undefined {
|
||||||
|
if (!opts?.health) return undefined;
|
||||||
|
|
||||||
|
const url = new URL(request.url);
|
||||||
|
const probe = answerProbe(request.method, url.pathname + url.search, opts.health);
|
||||||
|
if (!probe) return undefined;
|
||||||
|
|
||||||
|
const injected = computeInjected(opts, {
|
||||||
|
secure: url.protocol === 'https:',
|
||||||
|
headers: headersToRecord(request.headers),
|
||||||
|
});
|
||||||
|
return new Response(probe.body || null, {
|
||||||
|
status: probe.status,
|
||||||
|
headers: mergeInjectedHeaders(probe.headers, injected) as Record<string, string>,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
import type { WsRouteDef, MeshControl, RequestLimits } from './types';
|
import type { WsRouteDef, MeshControl, RequestLimits } from './types';
|
||||||
import { normalizeRequestPath } from './router';
|
import { normalizeRequestPath } from './router';
|
||||||
import { nodeRequire } from '../node-require';
|
import { nodeRequire } from '../node-require';
|
||||||
|
import { MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot';
|
||||||
|
|
||||||
/** 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 {
|
||||||
@@ -62,6 +63,18 @@ function handleMeshUpgrade(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Accepts an upgrade to the reserved mesh path on an app without a control channel, then closes it 1008. */
|
||||||
|
function refuseMeshUpgrade(wss: any, req: http.IncomingMessage, socket: any, head: Buffer): void {
|
||||||
|
if (!wss) {
|
||||||
|
rejectUpgrade(socket, 501, 'Not Implemented');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
wss.handleUpgrade(req, socket, head, (ws: { close(code: number, reason: string): void }) =>
|
||||||
|
ws.close(1008, MESH_CONTROL_DISABLED_REASON),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */
|
/** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */
|
||||||
function nodeWsRequest(req: http.IncomingMessage): WsRequest {
|
function nodeWsRequest(req: http.IncomingMessage): WsRequest {
|
||||||
return {
|
return {
|
||||||
@@ -157,6 +170,14 @@ function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, h
|
|||||||
|
|
||||||
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams, limits)) return;
|
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams, limits)) return;
|
||||||
|
|
||||||
|
// The reserved path with no control channel: refused exactly as `app.upgrade` refuses it on Deno,
|
||||||
|
// Bun and the edge — accept, then close 1008 with the same reason (D17). Never falls through to the
|
||||||
|
// ws route table: the boot already refuses any route that claims this path.
|
||||||
|
if (path === MESH_CONTROL_PATH) {
|
||||||
|
refuseMeshUpgrade(wss, req, socket, head);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const route = matchWsRoute(wsRoutes, path);
|
const route = matchWsRoute(wsRoutes, path);
|
||||||
|
|
||||||
if (!route) {
|
if (!route) {
|
||||||
|
|||||||
+13
-1
@@ -17,9 +17,21 @@ import {
|
|||||||
type Frame,
|
type Frame,
|
||||||
} from './protocol';
|
} from './protocol';
|
||||||
|
|
||||||
/** WebSocket path where a teapot exposes its mesh control channel. */
|
/**
|
||||||
|
* WebSocket path where a teapot exposes its mesh control channel.
|
||||||
|
*
|
||||||
|
* Reserved in every app, mesh or not (D17): `createApp` refuses a route that claims it, and an upgrade
|
||||||
|
* to it on an app without a control channel closes `1008` on every adapter.
|
||||||
|
*/
|
||||||
export const MESH_CONTROL_PATH = '/__mesh__/control';
|
export const MESH_CONTROL_PATH = '/__mesh__/control';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Close reason for an upgrade to {@link MESH_CONTROL_PATH} on an app with no control channel. One
|
||||||
|
* string shared by `app.upgrade` and the Node listener, so every adapter refuses it identically (D17).
|
||||||
|
*/
|
||||||
|
export const MESH_CONTROL_DISABLED_REASON =
|
||||||
|
'mesh control channel not enabled: this app exports nothing, or has no mesh.secret';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* How long an unauthenticated peer may hold the control channel open before it is hung up on.
|
* How long an unauthenticated peer may hold the control channel open before it is hung up on.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -82,3 +82,33 @@ test('mesh on Bun: a teapot refuses a bad secret over its control channel', asyn
|
|||||||
tServer.stop(true);
|
tServer.stop(true);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// CARD-18 T6 (GitHub #35, D9): a remote step whose token a local node already provides fails the
|
||||||
|
// splice, on Bun as on Node. Today that is the duplicate-name check in `setRunner`, which runs
|
||||||
|
// before the graph-wide one-producer check; this pins that the splice still refuses it.
|
||||||
|
@Step({ provides: 'auth', needs: [] })
|
||||||
|
class LocalAuth {
|
||||||
|
run() {
|
||||||
|
return { auth: { token: 'local' } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', steps: [LocalAuth], controllers: [LocalCtl] })
|
||||||
|
class ShadowingTeacupModule {}
|
||||||
|
|
||||||
|
test('mesh on Bun: a remote step colliding with a local token fails the splice', async () => {
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
|
const tServer = await serveBun(teapot, { port: 0 });
|
||||||
|
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [ShadowingTeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }], timeoutMs: 1000 },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(teacup.ready()).rejects.toThrow("duplicate provider/step name 'auth'");
|
||||||
|
} finally {
|
||||||
|
await teacup.close().catch(() => {});
|
||||||
|
tServer.stop(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -97,3 +97,24 @@ test('serveBun rejects when a provider fails, instead of binding a port that 500
|
|||||||
|
|
||||||
await expect(serveBun(app, { port: 0 })).rejects.toThrow(/no such key file/);
|
await expect(serveBun(app, { port: 0 })).rejects.toThrow(/no such key file/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// CARD-17 T5 (D14): close() marks the app draining before the server stops, and the drain window
|
||||||
|
// keeps the listener open long enough for a probe to read the 503.
|
||||||
|
test('serveBun close() with health.drainDelayMs: /__ready__ 503 draining, in-flight request 200', async () => {
|
||||||
|
const app = createApp({ modules: [M], health: { drainDelayMs: 300 } });
|
||||||
|
const server = await serveBun(app, { port: 0 });
|
||||||
|
const base = `http://127.0.0.1:${server.port}`;
|
||||||
|
|
||||||
|
expect((await fetch(`${base}/__ready__`)).status).toBe(200);
|
||||||
|
|
||||||
|
const inFlight = fetch(`${base}/slow`).then((r) => r.json());
|
||||||
|
await Bun.sleep(50);
|
||||||
|
|
||||||
|
const closing = server.close({ timeoutMs: 5000 });
|
||||||
|
const probe = await fetch(`${base}/__ready__`);
|
||||||
|
expect(probe.status).toBe(503);
|
||||||
|
expect(await probe.json()).toEqual({ status: 'draining' });
|
||||||
|
|
||||||
|
expect(await inFlight).toEqual({ ok: true });
|
||||||
|
await closing;
|
||||||
|
});
|
||||||
@@ -139,3 +139,31 @@ test('serveBun: ws message size default is 1 MiB', async () => {
|
|||||||
server.stop(true);
|
server.stop(true);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// CARD-21 (D17): the reserved mesh path is refused the way the Node listener refuses it, and a route
|
||||||
|
// that claims it fails createApp here too.
|
||||||
|
test('serveBun: /__mesh__/control without a control channel closes 1008; a route there fails createApp', async () => {
|
||||||
|
@Route('/')
|
||||||
|
class Claims {
|
||||||
|
@Ws('/__mesh__/control')
|
||||||
|
control() {
|
||||||
|
return (async function* () {})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Claims] })
|
||||||
|
class ClaimsModule {}
|
||||||
|
expect(() => createApp({ modules: [ClaimsModule] })).toThrow(
|
||||||
|
/^route @Ws \/__mesh__\/control at Claims\.control uses the reserved path/,
|
||||||
|
);
|
||||||
|
|
||||||
|
const app = createApp({ modules: [M] });
|
||||||
|
const server = await serveBun(app, { port: 0 });
|
||||||
|
try {
|
||||||
|
expect((await exchange(server.port, '/__mesh__/control', [])).close).toEqual({
|
||||||
|
code: 1008,
|
||||||
|
reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
server.stop(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -106,3 +106,39 @@ Deno.test('mesh on Deno: a teapot refuses a bad secret over its control channel'
|
|||||||
await t.server.shutdown();
|
await t.server.shutdown();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// CARD-18 T6 (GitHub #35, D9): a remote step whose token a local node already provides fails the
|
||||||
|
// splice, on Deno as on Node. Today that is the duplicate-name check in `setRunner`, which runs
|
||||||
|
// before the graph-wide one-producer check; this pins that the splice still refuses it.
|
||||||
|
@Step({ provides: 'auth', needs: [] })
|
||||||
|
class LocalAuth {
|
||||||
|
run() {
|
||||||
|
return { auth: { token: 'local' } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', steps: [LocalAuth], controllers: [LocalCtl] })
|
||||||
|
class ShadowingTeacupModule {}
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: a remote step colliding with a local token fails the splice', async () => {
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
|
const t = await serve(teapot);
|
||||||
|
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [ShadowingTeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }], timeoutMs: 1000 },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
let message = '';
|
||||||
|
try {
|
||||||
|
await teacup.ready();
|
||||||
|
} catch (err) {
|
||||||
|
message = String((err as Error).message);
|
||||||
|
}
|
||||||
|
assertStringIncludes(message, "duplicate provider/step name 'auth'");
|
||||||
|
} finally {
|
||||||
|
await teacup.close().catch(() => {});
|
||||||
|
await t.server.shutdown();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -121,3 +121,29 @@ Deno.test('serveDeno rejects when a provider fails, instead of binding a port th
|
|||||||
throw new Error(`expected serveDeno to reject with the provider's error, got: ${message || '<resolved>'}`);
|
throw new Error(`expected serveDeno to reject with the provider's error, got: ${message || '<resolved>'}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// CARD-17 T5 (D14): close() marks the app draining before the server shuts down, and the drain window
|
||||||
|
// keeps the listener open long enough for a probe to read the 503.
|
||||||
|
Deno.test('serveDeno close() with health.drainDelayMs: /__ready__ 503 draining, in-flight request 200', async () => {
|
||||||
|
const app = createApp({ modules: [M], health: { drainDelayMs: 300 } });
|
||||||
|
const server = await serveDeno(app, { port: 0, onListen: () => {} });
|
||||||
|
const base = `http://127.0.0.1:${portOf(server)}`;
|
||||||
|
|
||||||
|
const ready = await fetch(`${base}/__ready__`);
|
||||||
|
if (ready.status !== 200) throw new Error(`ready before close: ${ready.status}`);
|
||||||
|
await ready.body?.cancel();
|
||||||
|
|
||||||
|
const inFlight = fetch(`${base}/slow`).then((r) => r.json());
|
||||||
|
await new Promise((r) => setTimeout(r, 50));
|
||||||
|
|
||||||
|
const closing = server.close({ timeoutMs: 5000 });
|
||||||
|
const probe = await fetch(`${base}/__ready__`);
|
||||||
|
const body = await probe.json();
|
||||||
|
if (probe.status !== 503 || body.status !== 'draining') {
|
||||||
|
throw new Error(`probe during close: ${probe.status} ${JSON.stringify(body)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const done = await inFlight;
|
||||||
|
if (done.ok !== true) throw new Error(`in-flight request was cut: ${JSON.stringify(done)}`);
|
||||||
|
await closing;
|
||||||
|
});
|
||||||
@@ -181,3 +181,43 @@ Deno.test('serveDeno: ws message size default is 1 MiB', async () => {
|
|||||||
await server.shutdown();
|
await server.shutdown();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// CARD-21 (D17): the reserved mesh path is refused the way the Node listener refuses it, and a route
|
||||||
|
// that claims it fails createApp here too.
|
||||||
|
Deno.test('serveDeno: /__mesh__/control without a control channel closes 1008; a route there fails createApp', async () => {
|
||||||
|
@Route('/')
|
||||||
|
class Claims {
|
||||||
|
@Ws('/__mesh__/control')
|
||||||
|
control() {
|
||||||
|
return (async function* () {})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Claims] })
|
||||||
|
class ClaimsModule {}
|
||||||
|
let message = '';
|
||||||
|
try {
|
||||||
|
createApp({ modules: [ClaimsModule] });
|
||||||
|
} catch (error) {
|
||||||
|
message = (error as Error).message;
|
||||||
|
}
|
||||||
|
assertEquals(message.startsWith('route @Ws /__mesh__/control at Claims.control uses the reserved path'), true);
|
||||||
|
|
||||||
|
const app = createApp({ modules: [M] });
|
||||||
|
let port = 0;
|
||||||
|
const server = await serveDeno(app, {
|
||||||
|
port: 0,
|
||||||
|
onListen: (addr) => {
|
||||||
|
port = addr.port;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||||
|
|
||||||
|
try {
|
||||||
|
assertEquals((await exchange(port, '/__mesh__/control', [])).close, {
|
||||||
|
code: 1008,
|
||||||
|
reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await server.shutdown();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
// CARD-23 (#119, D21): on the edge, `cf-connecting-ip` sets `ctx.ip` only under `trustProxy`, for HTTP
|
||||||
|
// and WebSocket alike, and wins over `x-forwarded-for`. The full WebSocket path through workerd
|
||||||
|
// (`WebSocketPair`, a 101 response) cannot run under Node, so it is covered in `test/edge/run.ts`;
|
||||||
|
// here the edge HTTP path runs through `edgeHandler` itself, and the WebSocket side through
|
||||||
|
// `app.upgrade` with the value recorded the way `edgeHandler` records it.
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { AddressInfo } from 'node:net';
|
||||||
|
import { createApp, Route, Get, Ws, Module, ctx } from '../src/index';
|
||||||
|
import { edgeHandler } from '../src/edge';
|
||||||
|
import { channel } from '../src/channel';
|
||||||
|
import { setProxyClient } from '../src/http/peer';
|
||||||
|
import type { WsSocket, WsRequest } from '../src/http/ws-core';
|
||||||
|
|
||||||
|
@Route('/ip')
|
||||||
|
class IpCtl {
|
||||||
|
@Get('/whoami') whoami(@ctx() c: any) {
|
||||||
|
return { ip: c.ip };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Ws('/ws')
|
||||||
|
ws(@ctx() c: any) {
|
||||||
|
return (async function* () {
|
||||||
|
yield String(c.ip);
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [IpCtl] })
|
||||||
|
class IpModule {}
|
||||||
|
|
||||||
|
const trusting = createApp({ modules: [IpModule], trustProxy: true });
|
||||||
|
const untrusting = createApp({ modules: [IpModule] });
|
||||||
|
|
||||||
|
const whoami = async (handler: (r: Request) => Response | Promise<Response>, headers: Record<string, string>) =>
|
||||||
|
((await (await handler(new Request('http://x/ip/whoami', { headers }))).json()) as { ip: string }).ip;
|
||||||
|
|
||||||
|
describe('edge HTTP: cf-connecting-ip', () => {
|
||||||
|
it('T1: under trustProxy it sets ctx.ip', async () => {
|
||||||
|
expect(await whoami(edgeHandler(trusting), { 'cf-connecting-ip': '1.2.3.4' })).toBe('1.2.3.4');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T2: under trustProxy it wins over x-forwarded-for', async () => {
|
||||||
|
const headers = { 'cf-connecting-ip': '1.2.3.4', 'x-forwarded-for': '9.9.9.9' };
|
||||||
|
expect(await whoami(edgeHandler(trusting), headers)).toBe('1.2.3.4');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('under trustProxy without the header, x-forwarded-for still applies', async () => {
|
||||||
|
expect(await whoami(edgeHandler(trusting), { 'x-forwarded-for': '9.9.9.9' })).toBe('9.9.9.9');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T3: without trustProxy it is ignored and ctx.ip stays empty', async () => {
|
||||||
|
expect(await whoami(edgeHandler(untrusting), { 'cf-connecting-ip': '1.2.3.4' })).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function fakeSocket() {
|
||||||
|
const ac = new AbortController();
|
||||||
|
const sent: string[] = [];
|
||||||
|
const socket: WsSocket = {
|
||||||
|
inbound: channel<unknown>(),
|
||||||
|
abort: ac.signal,
|
||||||
|
isOpen: true,
|
||||||
|
send: (d) => sent.push(d),
|
||||||
|
close: () => ac.abort(),
|
||||||
|
terminate: () => ac.abort(),
|
||||||
|
};
|
||||||
|
return { socket, sent };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Upgrades the way `edgeHandler` does: `ip` empty, the header recorded on the `WsRequest`. */
|
||||||
|
async function edgeWsIp(app: typeof trusting, cfConnectingIp: string): Promise<string> {
|
||||||
|
const headers = { 'cf-connecting-ip': cfConnectingIp };
|
||||||
|
const req: WsRequest = { url: '/ip/ws', headers, protocol: 'http', ip: '' };
|
||||||
|
setProxyClient(req, cfConnectingIp);
|
||||||
|
const { socket, sent } = fakeSocket();
|
||||||
|
await app.upgrade(req, socket);
|
||||||
|
return sent[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('edge WebSocket: cf-connecting-ip', () => {
|
||||||
|
it('T4: without trustProxy it is ignored and ctx.ip stays empty', async () => {
|
||||||
|
expect(await edgeWsIp(untrusting, '1.2.3.4')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T5: under trustProxy it sets ctx.ip', async () => {
|
||||||
|
expect(await edgeWsIp(trusting, '1.2.3.4')).toBe('1.2.3.4');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('an adapter-supplied ip with nothing recorded is passed through unchanged', async () => {
|
||||||
|
const { socket, sent } = fakeSocket();
|
||||||
|
await trusting.upgrade({ url: '/ip/ws', headers: {}, protocol: 'http', ip: '203.0.113.7' }, socket);
|
||||||
|
expect(sent).toEqual(['203.0.113.7']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('outside the edge adapter the header means nothing', () => {
|
||||||
|
it('T6: the Node listener under trustProxy ignores cf-connecting-ip', async () => {
|
||||||
|
const server = await createApp({ modules: [IpModule], trustProxy: true }).listen(0);
|
||||||
|
try {
|
||||||
|
const { port } = server.address() as AddressInfo;
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/ip/whoami`, { headers: { 'cf-connecting-ip': '1.2.3.4' } });
|
||||||
|
const { ip } = (await res.json()) as { ip: string };
|
||||||
|
expect(ip).not.toBe('1.2.3.4');
|
||||||
|
expect(ip).toMatch(/127\.0\.0\.1|::1/);
|
||||||
|
} finally {
|
||||||
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a bare app.fetch under trustProxy ignores cf-connecting-ip', async () => {
|
||||||
|
expect(await whoami((r) => trusting.fetch(r), { 'cf-connecting-ip': '1.2.3.4' })).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a bare app.upgrade under trustProxy ignores the header in WsRequest.headers', async () => {
|
||||||
|
const { socket, sent } = fakeSocket();
|
||||||
|
await trusting.upgrade({ url: '/ip/ws', headers: { 'cf-connecting-ip': '1.2.3.4' }, protocol: 'http', ip: '' }, socket);
|
||||||
|
expect(sent).toEqual(['']);
|
||||||
|
});
|
||||||
|
});
|
||||||
+55
-1
@@ -164,7 +164,61 @@ async function main() {
|
|||||||
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
|
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
|
||||||
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
|
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
|
||||||
|
|
||||||
console.log('edge (workerd via miniflare): HTTP 200 + cookies + etag/304 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS');
|
// CARD-23 (#119): `cf-connecting-ip` sets ctx.ip only under trustProxy, for HTTP and WS alike,
|
||||||
|
// and wins over x-forwarded-for.
|
||||||
|
const cf = { 'cf-connecting-ip': '1.2.3.4' };
|
||||||
|
const httpIp = async (host: string, headers: Record<string, string>) =>
|
||||||
|
((await (await mf.dispatchFetch(`http://${host}/rt/ip`, { headers })).json()) as { ip: string }).ip;
|
||||||
|
const wsIp = async (host: string, headers: Record<string, string>) => {
|
||||||
|
const res = await mf.dispatchFetch(`http://${host}/rt/ws-ip`, { headers: { Upgrade: 'websocket', ...headers } });
|
||||||
|
const socket = res.webSocket;
|
||||||
|
assert.ok(socket, 'expected a client webSocket on the 101 response');
|
||||||
|
const reply = new Promise<string>((resolve) =>
|
||||||
|
socket.addEventListener('message', (e: { data: unknown }) => resolve(String(e.data))),
|
||||||
|
);
|
||||||
|
socket.accept();
|
||||||
|
const got = await reply;
|
||||||
|
socket.close();
|
||||||
|
return got;
|
||||||
|
};
|
||||||
|
assert.equal(await httpIp('trusted', cf), '1.2.3.4', 'T1 edge HTTP under trustProxy');
|
||||||
|
assert.equal(await httpIp('trusted', { ...cf, 'x-forwarded-for': '9.9.9.9' }), '1.2.3.4', 'T2 cf wins over XFF');
|
||||||
|
assert.equal(await httpIp('localhost', cf), '', 'T3 edge HTTP without trustProxy');
|
||||||
|
assert.equal(await wsIp('localhost', cf), 'ip:', 'T4 edge WS without trustProxy');
|
||||||
|
assert.equal(await wsIp('trusted', cf), 'ip:1.2.3.4', 'T5 edge WS under trustProxy');
|
||||||
|
|
||||||
|
// CARD-21 (D17): the reserved mesh path closes 1008 with the Node listener's reason, and a route
|
||||||
|
// that claims it fails createApp.
|
||||||
|
assert.deepEqual((await exchange(mf, 'http://localhost/__mesh__/control', [])).close, {
|
||||||
|
code: 1008,
|
||||||
|
reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret',
|
||||||
|
});
|
||||||
|
const reservedRes = await mf.dispatchFetch('http://reserved/');
|
||||||
|
assert.equal(reservedRes.status, 500);
|
||||||
|
assert.match(await reservedRes.text(), /^route @Ws \/__mesh__\/control at Claims\.control uses the reserved path/);
|
||||||
|
|
||||||
|
// CARD-17 T10: live 200; ready booting → ok, with only probes reaching the isolate. There is no
|
||||||
|
// close() on workerd, so draining is never reported here (documented, not tested for). Any probe
|
||||||
|
// starts the boot, so ready is asked first to see `booting`.
|
||||||
|
const first = await mf.dispatchFetch('http://health/__ready__');
|
||||||
|
assert.equal(first.status, 503);
|
||||||
|
assert.deepEqual(await first.json(), { status: 'booting' });
|
||||||
|
const live = await mf.dispatchFetch('http://health/__live__');
|
||||||
|
assert.equal(live.status, 200);
|
||||||
|
assert.deepEqual(await live.json(), { status: 'ok' });
|
||||||
|
let ready = await mf.dispatchFetch('http://health/__ready__');
|
||||||
|
for (let i = 0; i < 20 && ready.status !== 200; i++) {
|
||||||
|
await ready.arrayBuffer();
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||||
|
ready = await mf.dispatchFetch('http://health/__ready__');
|
||||||
|
}
|
||||||
|
assert.equal(ready.status, 200);
|
||||||
|
assert.deepEqual(await ready.json(), { status: 'ok' });
|
||||||
|
assert.equal(ready.headers.get('cache-control'), 'no-store');
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
'edge (workerd via miniflare): HTTP 200 + cookies + etag/304 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + health — PASS',
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
await mf.dispose();
|
await mf.dispose();
|
||||||
}
|
}
|
||||||
|
|||||||
+50
-6
@@ -52,6 +52,19 @@ class Rt {
|
|||||||
})();
|
})();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CARD-23: what `ctx.ip` resolved to, over HTTP and over a WebSocket upgrade.
|
||||||
|
@Get('/ip')
|
||||||
|
ip(@ctx() c: any) {
|
||||||
|
return { ip: c.ip };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Ws('/ws-ip')
|
||||||
|
wsIp(@ctx() c: any) {
|
||||||
|
return (async function* () {
|
||||||
|
yield `ip:${c.ip}`;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
@Ws('/room/:name')
|
@Ws('/room/:name')
|
||||||
room(@ctx() { inbound }: any) {
|
room(@ctx() { inbound }: any) {
|
||||||
return (async function* () {
|
return (async function* () {
|
||||||
@@ -66,12 +79,43 @@ class M {}
|
|||||||
const app = createApp({ modules: [M] });
|
const app = createApp({ modules: [M] });
|
||||||
// #107: the same graph with tight ws limits, reached through the `limited` host.
|
// #107: the same graph with tight ws limits, reached through the `limited` host.
|
||||||
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
||||||
// CARD-15 (#114): the same graph with handler ETags on, reached through the `etag` host.
|
// CARD-23: the same graph under `trustProxy`, reached through the `trusted` host.
|
||||||
const tagged = createApp({ modules: [M], etag: true });
|
const trusted = createApp({ modules: [M], trustProxy: true });
|
||||||
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited), etag: edgeHandler(tagged) };
|
const handlers: Record<string, ReturnType<typeof edgeHandler>> = {
|
||||||
const hosts: Record<string, typeof handlers.default> = { limited: handlers.limited, etag: handlers.etag };
|
default: edgeHandler(app),
|
||||||
|
limited: edgeHandler(limited),
|
||||||
|
trusted: edgeHandler(trusted),
|
||||||
|
// CARD-17 T10: health probes, reached through the `health` host. Never booted by anything but probes.
|
||||||
|
health: edgeHandler(createApp({ modules: [M], health: true })),
|
||||||
|
// CARD-15 (#114): the same graph with handler ETags on, reached through the `etag` host.
|
||||||
|
etag: edgeHandler(createApp({ modules: [M], etag: true })),
|
||||||
|
};
|
||||||
|
|
||||||
|
// CARD-21 (D17): a route on the reserved mesh path must fail createApp inside workerd too. Built per
|
||||||
|
// request on the `reserved` host so a regression answers with a status instead of breaking the worker.
|
||||||
|
@Route('/')
|
||||||
|
class Claims {
|
||||||
|
@Ws('/__mesh__/control')
|
||||||
|
control() {
|
||||||
|
return (async function* () {})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Claims] })
|
||||||
|
class ClaimsModule {}
|
||||||
|
|
||||||
|
function reservedBoot(): Response {
|
||||||
|
try {
|
||||||
|
createApp({ modules: [ClaimsModule] });
|
||||||
|
} catch (error) {
|
||||||
|
return new Response((error as Error).message, { status: 500 });
|
||||||
|
}
|
||||||
|
return new Response('booted', { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
|
fetch: (request: Request, env?: unknown, ctx?: Parameters<ReturnType<typeof edgeHandler>>[2]) => {
|
||||||
(hosts[new URL(request.url).hostname] ?? handlers.default)(request, env, ctx),
|
const host = new URL(request.url).hostname;
|
||||||
|
if (host === 'reserved') return reservedBoot();
|
||||||
|
return (handlers[host] ?? handlers.default)(request, env, ctx);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
@@ -24,6 +24,34 @@ test('throws on cycle', () => {
|
|||||||
expect(() => topoSort(nodes, [])).toThrow(/cycle detected/);
|
expect(() => topoSort(nodes, [])).toThrow(/cycle detected/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// CARD-18 (GitHub #35, D9): the check is a rule over the whole node set, not an artefact of the
|
||||||
|
// order nodes were registered in — so swapping `provideBuiltins` and `mountPlugins` cannot reopen it.
|
||||||
|
describe('one producer per token', () => {
|
||||||
|
const builtin: GraphNode = { name: 'logger', needs: [], provides: ['logger'], origin: 'builtin' };
|
||||||
|
const plugin: GraphNode = { name: 'fake', needs: [], provides: ['logger'], origin: 'plugin' };
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['built-in first', [builtin, plugin]],
|
||||||
|
['plugin first', [plugin, builtin]],
|
||||||
|
])('throws naming both producers and origins (%s)', (_, nodes) => {
|
||||||
|
expect(() => topoSort(nodes, [])).toThrow(/token 'logger' is provided twice/);
|
||||||
|
expect(() => topoSort(nodes, [])).toThrow(/'logger' \(builtin\)/);
|
||||||
|
expect(() => topoSort(nodes, [])).toThrow(/'fake' \(plugin\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('names a mesh origin like any other', () => {
|
||||||
|
const local: GraphNode = { name: 'auth', needs: [], provides: ['auth'], origin: 'module:App' };
|
||||||
|
const remote: GraphNode = { name: 'auth-remote', needs: [], provides: ['auth'], origin: 'mesh:ws://t' };
|
||||||
|
expect(() => topoSort([local, remote], [])).toThrow(
|
||||||
|
"token 'auth' is provided twice: by 'auth' (module:App) and by 'auth-remote' (mesh:ws://t)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows a node to list its own token twice', () => {
|
||||||
|
expect(topoSort([node('a', [], ['a', 'a'])], []).map((n) => n.name)).toEqual(['a']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const N = (name: string, needs: string[] = []) => ({ name, needs, provides: [name], origin: 'm' });
|
const N = (name: string, needs: string[] = []) => ({ name, needs, provides: [name], origin: 'm' });
|
||||||
|
|
||||||
describe('subgraphFor', () => {
|
describe('subgraphFor', () => {
|
||||||
|
|||||||
@@ -0,0 +1,389 @@
|
|||||||
|
/**
|
||||||
|
* CARD-17 (#115, D14): `createApp({ health })` serves `/__live__` and `/__ready__` outside the pipeline,
|
||||||
|
* with booting / ok / degraded / draining states and a drain window on close(). Deno and Bun repeat
|
||||||
|
* the drain case (T5) in their own suites; workerd covers T10 in `test/edge/run.ts`.
|
||||||
|
*/
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||||
|
import http from 'http';
|
||||||
|
import type { AddressInfo } from 'net';
|
||||||
|
import { WebSocketServer } from 'ws';
|
||||||
|
import { createApp, Route, Get, Ws, Module, Provider } from '../src/index';
|
||||||
|
import type { Logger } from '../src/logger';
|
||||||
|
import type { Plugin } from '../src/plugin';
|
||||||
|
import { encode, decode, MESH_PROTOCOL_VERSION } from '../src/mesh/protocol';
|
||||||
|
|
||||||
|
const silentLogger = (): Logger => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() });
|
||||||
|
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
|
||||||
|
let releaseSlow: () => void = () => {};
|
||||||
|
|
||||||
|
@Route('/')
|
||||||
|
class Ctl {
|
||||||
|
@Get('/ping') ping() {
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Held open until the test releases it: an in-flight request across close().
|
||||||
|
@Get('/slow') async slow() {
|
||||||
|
await new Promise<void>((resolve) => (releaseSlow = resolve));
|
||||||
|
return { slow: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/', controllers: [Ctl] })
|
||||||
|
class M {}
|
||||||
|
|
||||||
|
type AppOpts = Parameters<typeof createApp>[0];
|
||||||
|
const make = (extra: Partial<AppOpts> = {}) => createApp({ modules: [M], logger: silentLogger(), ...extra });
|
||||||
|
|
||||||
|
async function probe(app: ReturnType<typeof createApp>, path: string, method = 'GET') {
|
||||||
|
const res = await app.fetch(new Request(`http://x${path}`, { method }));
|
||||||
|
const text = await res.text();
|
||||||
|
return { status: res.status, body: text ? JSON.parse(text) : undefined, headers: res.headers };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('CARD-17: health probes through app.fetch', () => {
|
||||||
|
it('T1: /__ready__ is 503 booting while a slow provider boots, /__live__ is 200', async () => {
|
||||||
|
let finish: () => void = () => {};
|
||||||
|
|
||||||
|
@Provider({ provides: 'slowDb' })
|
||||||
|
class SlowDb {
|
||||||
|
async provide() {
|
||||||
|
await new Promise<void>((resolve) => (finish = resolve));
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Ctl], providers: [SlowDb] })
|
||||||
|
class Slow {}
|
||||||
|
|
||||||
|
const app = createApp({ modules: [Slow], health: true, logger: silentLogger() });
|
||||||
|
const booting = app.boot();
|
||||||
|
await sleep(10);
|
||||||
|
|
||||||
|
expect(await probe(app, '/__ready__')).toMatchObject({ status: 503, body: { status: 'booting' } });
|
||||||
|
expect(await probe(app, '/__live__')).toMatchObject({ status: 200, body: { status: 'ok' } });
|
||||||
|
|
||||||
|
finish();
|
||||||
|
await booting;
|
||||||
|
expect(await probe(app, '/__ready__')).toMatchObject({ status: 200, body: { status: 'ok' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T1: a probe before any boot starts the boot without waiting for it', async () => {
|
||||||
|
let started = false;
|
||||||
|
|
||||||
|
@Provider({ provides: 'watched' })
|
||||||
|
class Watched {
|
||||||
|
provide() {
|
||||||
|
started = true;
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Watched] })
|
||||||
|
class W {}
|
||||||
|
|
||||||
|
const app = createApp({ modules: [W], health: true, logger: silentLogger() });
|
||||||
|
expect((await probe(app, '/__ready__')).body).toEqual({ status: 'booting' });
|
||||||
|
await sleep(10);
|
||||||
|
expect(started).toBe(true);
|
||||||
|
expect((await probe(app, '/__ready__')).body).toEqual({ status: 'ok' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a failed boot keeps /__ready__ at 503 booting and still fails real requests', async () => {
|
||||||
|
@Provider({ provides: 'broken' })
|
||||||
|
class Broken {
|
||||||
|
provide(): never {
|
||||||
|
throw new Error('no pool');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Ctl], providers: [Broken] })
|
||||||
|
class B {}
|
||||||
|
|
||||||
|
const app = createApp({ modules: [B], health: true, logger: silentLogger() });
|
||||||
|
await probe(app, '/__ready__');
|
||||||
|
await sleep(10);
|
||||||
|
expect(await probe(app, '/__ready__')).toMatchObject({ status: 503, body: { status: 'booting' } });
|
||||||
|
await expect(app.fetch(new Request('http://x/ping'))).rejects.toThrow("provider 'broken' failed: no pool");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T2: booted with nothing degraded → 200 ok', async () => {
|
||||||
|
const app = make({ health: true });
|
||||||
|
await app.boot();
|
||||||
|
expect(await probe(app, '/__ready__')).toMatchObject({ status: 200, body: { status: 'ok' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T3: an optional provider failed → 200 degraded with its name', async () => {
|
||||||
|
@Provider({ provides: 'x', optional: true })
|
||||||
|
class X {
|
||||||
|
provide(): never {
|
||||||
|
throw new Error('down');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Ctl], providers: [X] })
|
||||||
|
class D {}
|
||||||
|
|
||||||
|
const app = createApp({ modules: [D], health: true, logger: silentLogger() });
|
||||||
|
await app.boot();
|
||||||
|
expect(await probe(app, '/__ready__')).toMatchObject({
|
||||||
|
status: 200,
|
||||||
|
body: { status: 'degraded', degraded: ['x'] },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T7: POST /__ready__ → 405 with Allow: GET, HEAD; HEAD answers with no body', async () => {
|
||||||
|
const app = make({ health: true });
|
||||||
|
await app.boot();
|
||||||
|
|
||||||
|
const post = await probe(app, '/__ready__', 'POST');
|
||||||
|
expect(post.status).toBe(405);
|
||||||
|
expect(post.headers.get('allow')).toBe('GET, HEAD');
|
||||||
|
|
||||||
|
const head = await probe(app, '/__live__', 'HEAD');
|
||||||
|
expect(head.status).toBe(200);
|
||||||
|
expect(head.body).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('security headers are injected, cache-control is no-store, a query string is ignored', async () => {
|
||||||
|
const app = make({ health: true });
|
||||||
|
await app.boot();
|
||||||
|
const res = await probe(app, '/__ready__?verbose=1');
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.headers.get('cache-control')).toBe('no-store');
|
||||||
|
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T9 + rule 5: no lifecycle event, no plugin step, no log line for a probe', async () => {
|
||||||
|
const step = vi.fn(() => ({}));
|
||||||
|
const plugin: Plugin = {
|
||||||
|
name: 'global-step',
|
||||||
|
mount(api) {
|
||||||
|
api.scope.add({ kind: 'step', name: 'everywhere', needs: [], provides: [], run: step });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const logger = silentLogger();
|
||||||
|
const app = createApp({ modules: [M], plugins: [plugin], health: true, logRequests: true, logger });
|
||||||
|
await app.boot();
|
||||||
|
const emit = vi.spyOn(app.bus, 'emit');
|
||||||
|
|
||||||
|
for (let i = 0; i < 10; i++) await probe(app, i % 2 ? '/__live__' : '/__ready__');
|
||||||
|
|
||||||
|
expect(emit).not.toHaveBeenCalled();
|
||||||
|
expect(step).not.toHaveBeenCalled();
|
||||||
|
expect(logger.info).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// the control: an ordinary request does run the step and log
|
||||||
|
await app.fetch(new Request('http://x/ping'));
|
||||||
|
expect(step).toHaveBeenCalled();
|
||||||
|
expect(logger.info).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T6: probes answer while maxConcurrentRequests sheds everything else', async () => {
|
||||||
|
const app = make({ health: true, limits: { maxConcurrentRequests: 1 } });
|
||||||
|
await app.boot();
|
||||||
|
const held = app.fetch(new Request('http://x/slow'));
|
||||||
|
await sleep(10);
|
||||||
|
|
||||||
|
expect((await app.fetch(new Request('http://x/ping'))).status).toBe(503);
|
||||||
|
expect((await probe(app, '/__ready__')).status).toBe(200);
|
||||||
|
expect((await probe(app, '/__live__')).status).toBe(200);
|
||||||
|
|
||||||
|
releaseSlow();
|
||||||
|
expect((await held).status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('health off: the probe paths are ordinary paths (404)', async () => {
|
||||||
|
const app = make();
|
||||||
|
expect((await app.fetch(new Request('http://x/__ready__'))).status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('draining after close() on an app served through app.fetch', async () => {
|
||||||
|
const app = make({ health: true });
|
||||||
|
await app.boot();
|
||||||
|
await app.close();
|
||||||
|
expect(await probe(app, '/__ready__')).toMatchObject({ status: 503, body: { status: 'draining' } });
|
||||||
|
expect((await probe(app, '/__live__')).status).toBe(200);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('CARD-17: health option validation and reserved paths', () => {
|
||||||
|
it('invalid health values throw at createApp', () => {
|
||||||
|
expect(() => make({ health: 'yes' as never })).toThrow(/health must be true, false or \{ drainDelayMs/);
|
||||||
|
expect(() => make({ health: { drainDelayMs: -1 } })).toThrow(/drainDelayMs must be a non-negative number/);
|
||||||
|
expect(() => make({ health: { drainDelayMs: Number.NaN } })).toThrow(/non-negative number/);
|
||||||
|
expect(() => make({ health: { checks: [] } as never })).toThrow(/unknown option 'checks'/);
|
||||||
|
expect(() => make({ health: { drainDelayMs: 20_000 } })).toThrow(/cannot exceed shutdownTimeoutMs \(10000\)/);
|
||||||
|
expect(() => make({ health: { drainDelayMs: 600 }, shutdownTimeoutMs: 1000, teardownTimeoutMs: 500 })).toThrow(
|
||||||
|
/plus teardownTimeoutMs \(500\)/,
|
||||||
|
);
|
||||||
|
expect(() => make({ health: { drainDelayMs: 500 } })).not.toThrow();
|
||||||
|
expect(() => make({ health: false })).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T8: @Get(/__live__) with health on fails createApp, naming the route', () => {
|
||||||
|
@Route('/')
|
||||||
|
class Own {
|
||||||
|
@Get('/__live__') live() {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Own] })
|
||||||
|
class O {}
|
||||||
|
|
||||||
|
expect(() => createApp({ modules: [O], health: true })).toThrow(
|
||||||
|
'route GET /__live__ at Own.live uses the reserved path /__live__ (the liveness probe, health: true) — ' +
|
||||||
|
'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a route at /__ready__ (HTTP or WS) fails with health on and serves with it off', async () => {
|
||||||
|
@Route('/')
|
||||||
|
class Own {
|
||||||
|
@Get('/__ready__') ready() {
|
||||||
|
return { mine: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [Own] })
|
||||||
|
class O {}
|
||||||
|
@Route('/')
|
||||||
|
class OwnWs {
|
||||||
|
@Ws('/__ready__') ready() {
|
||||||
|
return (async function* () {})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [OwnWs] })
|
||||||
|
class OW {}
|
||||||
|
|
||||||
|
expect(() => createApp({ modules: [O], health: true })).toThrow(/^route GET \/__ready__ at Own\.ready uses/);
|
||||||
|
expect(() => createApp({ modules: [OW], health: true })).toThrow(/^route @Ws \/__ready__ at OwnWs\.ready uses/);
|
||||||
|
|
||||||
|
const off = createApp({ modules: [O] });
|
||||||
|
expect(await (await off.fetch(new Request('http://x/__ready__'))).json()).toEqual({ mine: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a teapot route at /__ready__ fails the teacup splice while health is on', async () => {
|
||||||
|
const wss = new WebSocketServer({ port: 0 });
|
||||||
|
wss.on('connection', (ws) => {
|
||||||
|
ws.on('message', (data) => {
|
||||||
|
if (decode(data.toString()).type === 'hello') {
|
||||||
|
ws.send(
|
||||||
|
encode({
|
||||||
|
type: 'manifest',
|
||||||
|
v: MESH_PROTOCOL_VERSION,
|
||||||
|
steps: [],
|
||||||
|
routes: [{ method: 'GET', pattern: '/__ready__' }],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const url = `ws://127.0.0.1:${(wss.address() as AddressInfo).port}/__mesh__/control`;
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [M],
|
||||||
|
health: true,
|
||||||
|
experimental: true,
|
||||||
|
mesh: { teapots: [{ url, secret: 's' }] },
|
||||||
|
logger: silentLogger(),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(teacup.ready()).rejects.toThrow(
|
||||||
|
`mesh: remote route 'GET /__ready__' from ${url} uses the reserved path /__ready__`,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
wss.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/** One request on `agent` (kept alive), resolving with status and body. */
|
||||||
|
function request(port: number, path: string, agent: http.Agent) {
|
||||||
|
return new Promise<{ status: number; body: string }>((resolve, reject) => {
|
||||||
|
const req = http.get({ host: '127.0.0.1', port, path, agent }, (res) => {
|
||||||
|
let body = '';
|
||||||
|
res.on('data', (chunk) => (body += chunk));
|
||||||
|
res.on('end', () => resolve({ status: res.statusCode ?? 0, body }));
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('CARD-17: the Node listener', () => {
|
||||||
|
const agents: http.Agent[] = [];
|
||||||
|
|
||||||
|
afterEach(() => agents.splice(0).forEach((agent) => agent.destroy()));
|
||||||
|
|
||||||
|
it('serves the probes before the gate; listen() boots first, so the listener never says booting', async () => {
|
||||||
|
const app = make({ health: true });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const agent = new http.Agent({ keepAlive: true });
|
||||||
|
agents.push(agent);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const port = (server.address() as AddressInfo).port;
|
||||||
|
expect(await request(port, '/__ready__', agent)).toEqual({ status: 200, body: '{"status":"ok"}' });
|
||||||
|
expect(await request(port, '/__live__', agent)).toEqual({ status: 200, body: '{"status":"ok"}' });
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T4: close() flips /__ready__ to 503 on a kept-alive connection while a slow request completes', async () => {
|
||||||
|
const app = make({ health: { drainDelayMs: 300 } });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
const port = (server.address() as AddressInfo).port;
|
||||||
|
const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
|
||||||
|
const slowAgent = new http.Agent({ keepAlive: true });
|
||||||
|
agents.push(agent, slowAgent);
|
||||||
|
|
||||||
|
// Warm the probe connection so the next probe reuses it.
|
||||||
|
expect((await request(port, '/__ready__', agent)).status).toBe(200);
|
||||||
|
const slow = request(port, '/slow', slowAgent);
|
||||||
|
await sleep(20);
|
||||||
|
|
||||||
|
const closing = app.close();
|
||||||
|
const drained = await request(port, '/__ready__', agent);
|
||||||
|
expect(drained).toEqual({ status: 503, body: '{"status":"draining"}' });
|
||||||
|
|
||||||
|
releaseSlow();
|
||||||
|
expect(await slow).toEqual({ status: 200, body: '{"slow":true}' });
|
||||||
|
await closing;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T4 without drainDelayMs: close() still marks the app draining before it drains', async () => {
|
||||||
|
const app = make({ health: true });
|
||||||
|
await app.listen(0);
|
||||||
|
await app.close();
|
||||||
|
expect((await probe(app, '/__ready__')).body).toEqual({ status: 'draining' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('the drain window comes out of the close() budget', async () => {
|
||||||
|
const app = make({ health: { drainDelayMs: 200 } });
|
||||||
|
await app.listen(0);
|
||||||
|
const started = Date.now();
|
||||||
|
await app.close({ timeoutMs: 1000 });
|
||||||
|
const took = Date.now() - started;
|
||||||
|
expect(took).toBeGreaterThanOrEqual(190);
|
||||||
|
expect(took).toBeLessThan(1000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a POST probe on the listener answers 405 with Allow', async () => {
|
||||||
|
const app = make({ health: true });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const port = (server.address() as AddressInfo).port;
|
||||||
|
const res = await new Promise<http.IncomingMessage>((resolve) => {
|
||||||
|
const req = http.request({ host: '127.0.0.1', port, path: '/__ready__', method: 'POST' }, resolve);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
res.resume();
|
||||||
|
expect(res.statusCode).toBe(405);
|
||||||
|
expect(res.headers.allow).toBe('GET, HEAD');
|
||||||
|
expect(res.headers['cache-control']).toBe('no-store');
|
||||||
|
} finally {
|
||||||
|
await app.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
// CARD-18 (GitHub #35, D9): every token has at most one producer across modules, plugins, mesh steps
|
||||||
|
// and built-ins. A second producer fails `createApp`, naming both nodes and their origins.
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { createApp, Provider, Step, Route, Get, Module, needs } from '../src/index';
|
||||||
|
import type { Plugin, ScopeNode } from '../src/index';
|
||||||
|
|
||||||
|
@Provider({ provides: 'user' })
|
||||||
|
class User {
|
||||||
|
provide() {
|
||||||
|
return { user: { id: 'real' } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Route('/u')
|
||||||
|
class UserCtl {
|
||||||
|
@Get('/me') me(@needs('user') user: unknown) {
|
||||||
|
return { user };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/', providers: [User], controllers: [UserCtl] })
|
||||||
|
class AppModule {}
|
||||||
|
|
||||||
|
/** A plugin that adds one scope node, the way an official plugin would. */
|
||||||
|
const adds = (name: string, node: Omit<ScopeNode, 'run'> & Partial<Pick<ScopeNode, 'run'>>): Plugin => ({
|
||||||
|
name,
|
||||||
|
mount({ scope }) {
|
||||||
|
scope.add({ run: () => Object.fromEntries(node.provides.map((key) => [key, `from ${name}`])), ...node });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('one producer per token', () => {
|
||||||
|
it('T1: a plugin node providing a module-provided token fails boot, naming both nodes and origins', () => {
|
||||||
|
const shadow = adds('shadow', { kind: 'provider', name: 'shadow', needs: [], provides: ['user'] });
|
||||||
|
expect(() => createApp({ modules: [AppModule], plugins: [shadow] })).toThrow(
|
||||||
|
"token 'user' is provided twice: by 'user' (module:AppModule) and by 'shadow' (plugin)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T1: a plugin step providing it fails the same way', () => {
|
||||||
|
const shadow = adds('shadow', { kind: 'step', name: 'shadow', needs: [], provides: ['user'] });
|
||||||
|
expect(() => createApp({ modules: [AppModule], plugins: [shadow] })).toThrow(/'user' \(module:AppModule\).*'shadow' \(plugin\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T2: a plugin node providing a built-in token fails boot instead of losing silently', () => {
|
||||||
|
const fake = adds('fake-logger', { kind: 'provider', name: 'fake-logger', needs: [], provides: ['logger'] });
|
||||||
|
// Plugins mount before the built-ins are registered, so the plugin is the one seen first. The
|
||||||
|
// order the two are reported in is not the point; that both are, with their origins, is.
|
||||||
|
expect(() => createApp({ modules: [AppModule], plugins: [fake] })).toThrow(
|
||||||
|
"token 'logger' is provided twice: by 'fake-logger' (plugin) and by 'logger' (builtin)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(['rooms', 'events'])('T2: the same holds for the built-in %s', (token) => {
|
||||||
|
const fake = adds('fake', { kind: 'provider', name: 'fake', needs: [], provides: [token] });
|
||||||
|
expect(() => createApp({ modules: [AppModule], plugins: [fake] })).toThrow(`token '${token}' is provided twice`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T3: a plugin node providing two tokens, one of them taken, fails naming the taken one', () => {
|
||||||
|
const both = adds('both', { kind: 'provider', name: 'both', needs: [], provides: ['a', 'user'] });
|
||||||
|
expect(() => createApp({ modules: [AppModule], plugins: [both] })).toThrow(/^token 'user' is provided twice/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T4: two plugins providing distinct tokens boot', async () => {
|
||||||
|
const a = adds('a', { kind: 'provider', name: 'a', needs: [], provides: ['a'] });
|
||||||
|
const b = adds('b', { kind: 'provider', name: 'b', needs: [], provides: ['b'] });
|
||||||
|
const app = createApp({ modules: [AppModule], plugins: [a, b] });
|
||||||
|
await expect(app.boot()).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('two plugin nodes providing the same token fail, naming both', () => {
|
||||||
|
const a = adds('a', { kind: 'step', name: 'a', needs: [], provides: ['shared'] });
|
||||||
|
const b = adds('b', { kind: 'step', name: 'b', needs: [], provides: ['shared'] });
|
||||||
|
expect(() => createApp({ modules: [AppModule], plugins: [a, b] })).toThrow(
|
||||||
|
"token 'shared' is provided twice: by 'a' (plugin) and by 'b' (plugin)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('observer steps that provide nothing do not count as producers', async () => {
|
||||||
|
const one = adds('one', { kind: 'step', name: 'one', needs: [], provides: [] });
|
||||||
|
const two = adds('two', { kind: 'step', name: 'two', needs: [], provides: [] });
|
||||||
|
await expect(createApp({ modules: [AppModule], plugins: [one, two] }).boot()).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T5: overrides replace the runner of an existing token, not add a producer', async () => {
|
||||||
|
const app = createApp({ modules: [AppModule], overrides: { user: { id: 1 } } });
|
||||||
|
const res = await app.fetch(new Request('http://x/u/me'));
|
||||||
|
expect(await res.json()).toEqual({ user: { id: 1 } });
|
||||||
|
});
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('one producer per token: mesh', () => {
|
||||||
|
const SECRET = 's3cr3t';
|
||||||
|
|
||||||
|
@Step({ provides: 'auth', needs: [], export: true })
|
||||||
|
class RemoteAuth {
|
||||||
|
run() {
|
||||||
|
return { auth: 'remote' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', steps: [RemoteAuth] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
@Step({ provides: 'auth', needs: [] })
|
||||||
|
class LocalAuth {
|
||||||
|
run() {
|
||||||
|
return { auth: 'local' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Route('/a')
|
||||||
|
class AuthCtl {
|
||||||
|
@Get('/who') who(@needs('auth') auth: unknown) {
|
||||||
|
return { auth };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', steps: [LocalAuth], controllers: [AuthCtl] })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
it('T6: a remote step whose token a local node provides still fails at splice', async () => {
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
|
const server = await teapot.listen(0);
|
||||||
|
const url = `ws://127.0.0.1:${(server.address() as any).port}/__mesh__/control`;
|
||||||
|
const teacup = createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] } });
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(teacup.ready()).rejects.toThrow("duplicate provider/step name 'auth'");
|
||||||
|
} finally {
|
||||||
|
await teacup.close().catch(() => {});
|
||||||
|
await teapot.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import 'reflect-metadata';
|
||||||
|
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
|
||||||
|
import type { AddressInfo } from 'node:net';
|
||||||
|
import type { Server } from 'node:http';
|
||||||
|
import { Get, Module, Route, Transformer } from '../src/metadata';
|
||||||
|
import { JsonTransformer } from '../src/transformers';
|
||||||
|
import { createApp } from '../src/app';
|
||||||
|
import { parseQuery } from '../src/http';
|
||||||
|
import { query } from '../src/params';
|
||||||
|
|
||||||
|
// CARD-25 / GitHub #48: the query string is everything after the FIRST `?` (and before `#`).
|
||||||
|
const CASES: Array<[string, Record<string, string>]> = [
|
||||||
|
['/search?q=what?now', { q: 'what?now' }], // T1
|
||||||
|
['/search?a=1&b=?', { a: '1', b: '?' }], // T2
|
||||||
|
['/search?', {}], // T3
|
||||||
|
['/search', {}], // T4
|
||||||
|
];
|
||||||
|
|
||||||
|
describe('parseQuery', () => {
|
||||||
|
test.each(CASES)('%s', (url, expected) => {
|
||||||
|
expect(parseQuery(url)).toEqual(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stops at a fragment', () => {
|
||||||
|
expect(parseQuery('/search?q=a?b#frag?x=1')).toEqual({ q: 'a?b' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
@Route('/search')
|
||||||
|
class SearchCtl {
|
||||||
|
@Get('/')
|
||||||
|
@Transformer(JsonTransformer)
|
||||||
|
search(@query() q: Record<string, string>) {
|
||||||
|
return q;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Module({ mountpoint: '/', controllers: [SearchCtl] })
|
||||||
|
class SearchModule {}
|
||||||
|
|
||||||
|
describe('query string with more than one `?`', () => {
|
||||||
|
const app = createApp({ modules: [SearchModule] });
|
||||||
|
let server: Server;
|
||||||
|
let base: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
server = await app.listen(0);
|
||||||
|
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||||
|
});
|
||||||
|
afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())));
|
||||||
|
|
||||||
|
test.each(CASES)('app.fetch %s', async (url, expected) => {
|
||||||
|
const res = await app.fetch(new Request(`http://x${url}`));
|
||||||
|
expect(await res.json()).toEqual(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each(CASES)('Node listener %s', async (url, expected) => {
|
||||||
|
const res = await fetch(`${base}${url}`);
|
||||||
|
expect(await res.json()).toEqual(expected);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
/**
|
||||||
|
* CARD-21 (#126, D17): `/__mesh__/control` is reserved in every app, mesh or not. Boot refuses a route
|
||||||
|
* that claims it, and an upgrade to it on an app without a control channel is refused the same way
|
||||||
|
* by the Node listener and by `app.upgrade`. Deno, Bun and workerd repeat T1/T5 in their own suites.
|
||||||
|
*/
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { describe, it, expect, afterEach } from 'vitest';
|
||||||
|
import type { AddressInfo } from 'net';
|
||||||
|
import type http from 'http';
|
||||||
|
import WebSocket, { WebSocketServer } from 'ws';
|
||||||
|
import { createApp, Route, Get, Post, Ws, Stream, Module, param, MESH_CONTROL_PATH } from '../src/index';
|
||||||
|
import type { RouteDecorator } from '../src/metadata';
|
||||||
|
import { channel } from '../src/channel';
|
||||||
|
import type { WsRequest, WsSocket } from '../src/http/ws-core';
|
||||||
|
import { claimedReservedPath } from '../src/http/reserved-paths';
|
||||||
|
import { encode, decode, MESH_PROTOCOL_VERSION } from '../src/mesh/protocol';
|
||||||
|
|
||||||
|
const REASON = 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret';
|
||||||
|
const RESERVED = [{ path: MESH_CONTROL_PATH, purpose: 'the mesh control channel' }];
|
||||||
|
|
||||||
|
type Decl = [RouteDecorator, string];
|
||||||
|
|
||||||
|
/** One controller under `mountpoint`, a handler per declaration (`h0`, `h1`, …). */
|
||||||
|
function moduleWith(decls: Decl[], mountpoint = '/', name = 'Routes') {
|
||||||
|
const Routes = { [name]: class {} }[name];
|
||||||
|
|
||||||
|
decls.forEach(([decorator, path], index) => {
|
||||||
|
const handler = `h${index}`;
|
||||||
|
Object.defineProperty(Routes.prototype, handler, {
|
||||||
|
value: (p: Record<string, string>) =>
|
||||||
|
(async function* () {
|
||||||
|
yield { route: handler, params: p };
|
||||||
|
})(),
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
param()(Routes.prototype, handler, 0);
|
||||||
|
decorator(path)(Routes.prototype, handler, Object.getOwnPropertyDescriptor(Routes.prototype, handler)!);
|
||||||
|
});
|
||||||
|
|
||||||
|
Route('/')(Routes);
|
||||||
|
class RoutesModule {}
|
||||||
|
Module({ mountpoint, controllers: [Routes] })(RoutesModule);
|
||||||
|
return RoutesModule;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bootError = (decls: Decl[], mountpoint?: string): string => {
|
||||||
|
try {
|
||||||
|
createApp({ modules: [moduleWith(decls, mountpoint)] });
|
||||||
|
} catch (error) {
|
||||||
|
return (error as Error).message;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('expected the app to refuse to boot');
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('CARD-21: a route on the reserved mesh path fails createApp', () => {
|
||||||
|
it('T1: @Ws(/__mesh__/control) on a non-mesh app', () => {
|
||||||
|
expect(bootError([[Ws, '/__mesh__/control']])).toBe(
|
||||||
|
'route @Ws /__mesh__/control at Routes.h0 uses the reserved path /__mesh__/control (the mesh control channel) — ' +
|
||||||
|
'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T2: @Get(/__mesh__/control)', () => {
|
||||||
|
expect(bootError([[Get, '/__mesh__/control']])).toMatch(
|
||||||
|
/^route GET \/__mesh__\/control at Routes\.h0 uses the reserved path \/__mesh__\/control/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T3: @Ws(/__mesh__/:x) — a parameterised pattern is checked by matching', () => {
|
||||||
|
expect(bootError([[Ws, '/__mesh__/:x']])).toMatch(/^route @Ws \/__mesh__\/:x at Routes\.h0 uses the reserved path/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('@Stream, other methods, catch-alls, a trailing slash and a mountpoint are caught too', () => {
|
||||||
|
expect(bootError([[Stream, '/__mesh__/control']])).toMatch(/^route @Stream \/__mesh__\/control at/);
|
||||||
|
expect(bootError([[Post, '/__mesh__/control']])).toMatch(/^route POST /);
|
||||||
|
expect(bootError([[Get, '/__mesh__/:rest*']])).toMatch(/uses the reserved path/);
|
||||||
|
expect(bootError([[Get, '/__mesh__/control/']])).toMatch(/uses the reserved path/);
|
||||||
|
expect(bootError([[Get, '/control']], '/__mesh__')).toMatch(/^route GET \/__mesh__\/control at/);
|
||||||
|
expect(bootError([[Get, '/__mesh__/:x(c.*)']])).toMatch(/uses the reserved path/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a mesh-enabled app gets the same refusal: the reservation does not depend on the mesh', () => {
|
||||||
|
expect(() =>
|
||||||
|
createApp({
|
||||||
|
modules: [moduleWith([[Ws, '/__mesh__/control']])],
|
||||||
|
experimental: true,
|
||||||
|
mesh: { secret: 's' },
|
||||||
|
}),
|
||||||
|
).toThrow(/uses the reserved path \/__mesh__\/control/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('patterns that do not name the reserved prefix still boot (the path is carved out of them)', () => {
|
||||||
|
expect(() =>
|
||||||
|
createApp({
|
||||||
|
modules: [
|
||||||
|
moduleWith([
|
||||||
|
[Get, '/:org/:repo'],
|
||||||
|
[Get, '/__mesh__/other'],
|
||||||
|
[Get, '/__mesh__/:x(\\d+)'],
|
||||||
|
[Get, '/__mesh__'],
|
||||||
|
[Get, '/__mesh__/control/deeper'],
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
).not.toThrow();
|
||||||
|
expect(() => createApp({ modules: [moduleWith([[Ws, '/:a/:b']])] })).not.toThrow();
|
||||||
|
expect(() => createApp({ modules: [moduleWith([[Get, '/:rest*']])] })).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('claimedReservedPath: literal by equality, parameterised by matching, prefix spelled literally', () => {
|
||||||
|
expect(claimedReservedPath('/__mesh__/control', RESERVED)).toEqual(RESERVED[0]);
|
||||||
|
expect(claimedReservedPath('/__mesh__/:x', RESERVED)).toEqual(RESERVED[0]);
|
||||||
|
expect(claimedReservedPath('/__mesh__/:rest*', RESERVED)).toEqual(RESERVED[0]);
|
||||||
|
expect(claimedReservedPath('/:a/control', RESERVED)).toBeUndefined();
|
||||||
|
expect(claimedReservedPath('/:rest*', RESERVED)).toBeUndefined();
|
||||||
|
expect(claimedReservedPath('/', RESERVED)).toBeUndefined();
|
||||||
|
expect(claimedReservedPath('/__mesh__/:x(\\d+)', RESERVED)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Drives `app.upgrade` with an in-memory socket and records what it sent and how it closed. */
|
||||||
|
async function viaAppUpgrade(app: ReturnType<typeof createApp>, path: string) {
|
||||||
|
const sent: unknown[] = [];
|
||||||
|
const closes: Array<{ code?: number; reason?: string }> = [];
|
||||||
|
const ac = new AbortController();
|
||||||
|
let open = true;
|
||||||
|
const socket: WsSocket = {
|
||||||
|
inbound: channel<unknown>(),
|
||||||
|
abort: ac.signal,
|
||||||
|
get isOpen() {
|
||||||
|
return open;
|
||||||
|
},
|
||||||
|
send: (data) => sent.push(data),
|
||||||
|
close: (code, reason) => {
|
||||||
|
open = false;
|
||||||
|
closes.push({ code, reason });
|
||||||
|
ac.abort();
|
||||||
|
},
|
||||||
|
terminate: () => {
|
||||||
|
open = false;
|
||||||
|
ac.abort();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const request: WsRequest = { url: path, headers: {}, protocol: 'http', ip: '127.0.0.1' };
|
||||||
|
await app.upgrade(request, socket);
|
||||||
|
return { sent, closes };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opens a `ws` client on the Node listener and resolves with the HTTP status or the close frame. */
|
||||||
|
function viaNodeUpgrade(port: number, path: string) {
|
||||||
|
return new Promise<{ status: number; close?: { code: number; reason: string } }>((resolve) => {
|
||||||
|
const client = new WebSocket(`ws://127.0.0.1:${port}${path}`);
|
||||||
|
client.on('unexpected-response', (_req, res) => {
|
||||||
|
resolve({ status: res.statusCode ?? 0 });
|
||||||
|
res.resume();
|
||||||
|
client.terminate();
|
||||||
|
});
|
||||||
|
client.on('close', (code, reason) => resolve({ status: 101, close: { code, reason: String(reason) } }));
|
||||||
|
client.on('error', () => {});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('CARD-21: an upgrade to the reserved path on an app with no control channel', () => {
|
||||||
|
const servers: http.Server[] = [];
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))));
|
||||||
|
});
|
||||||
|
|
||||||
|
const ordinary = () => moduleWith([[Ws, '/echo']], '/', 'Ordinary');
|
||||||
|
|
||||||
|
it('T4: the Node listener accepts and closes 1008 with the app.upgrade reason', async () => {
|
||||||
|
const app = createApp({ modules: [ordinary()] });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
servers.push(server);
|
||||||
|
|
||||||
|
expect(await viaNodeUpgrade((server.address() as AddressInfo).port, '/__mesh__/control')).toEqual({
|
||||||
|
status: 101,
|
||||||
|
close: { code: 1008, reason: REASON },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T4: a teapot with no exports (mesh configured, no control channel) refuses the same way on Node', async () => {
|
||||||
|
const app = createApp({ modules: [ordinary()], experimental: true, mesh: {} });
|
||||||
|
const server = await app.listen(0);
|
||||||
|
servers.push(server);
|
||||||
|
|
||||||
|
expect(await viaNodeUpgrade((server.address() as AddressInfo).port, '/__mesh__/control')).toEqual({
|
||||||
|
status: 101,
|
||||||
|
close: { code: 1008, reason: REASON },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T5: app.upgrade closes 1008 with the same reason', async () => {
|
||||||
|
const app = createApp({ modules: [ordinary()] });
|
||||||
|
expect(await viaAppUpgrade(app, '/__mesh__/control')).toEqual({
|
||||||
|
sent: [],
|
||||||
|
closes: [{ code: 1008, reason: REASON }],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('CARD-21 T7: a teapot that advertises a route on the reserved path', () => {
|
||||||
|
let wss: WebSocketServer | undefined;
|
||||||
|
|
||||||
|
afterEach(() => wss?.close());
|
||||||
|
|
||||||
|
/** A hand-rolled teapot: a real one refuses such a route at its own boot, so only the wire can carry it. */
|
||||||
|
function foreignTeapot(pattern: string): string {
|
||||||
|
wss = new WebSocketServer({ port: 0 });
|
||||||
|
wss.on('connection', (ws) => {
|
||||||
|
ws.on('message', (data) => {
|
||||||
|
const frame = decode(data.toString());
|
||||||
|
if (frame.type === 'hello') {
|
||||||
|
ws.send(
|
||||||
|
encode({
|
||||||
|
type: 'manifest',
|
||||||
|
v: MESH_PROTOCOL_VERSION,
|
||||||
|
steps: [],
|
||||||
|
routes: [{ method: 'GET', pattern }],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return `ws://127.0.0.1:${(wss.address() as AddressInfo).port}/__mesh__/control`;
|
||||||
|
}
|
||||||
|
|
||||||
|
it('the teacup splice fails and names the teapot', async () => {
|
||||||
|
const url = foreignTeapot('/__mesh__/:x');
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [moduleWith([[Get, '/ok']])],
|
||||||
|
experimental: true,
|
||||||
|
mesh: { teapots: [{ url, secret: 's' }] },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(teacup.ready()).rejects.toThrow(
|
||||||
|
`mesh: remote route 'GET /__mesh__/:x' from ${url} uses the reserved path /__mesh__/control ` +
|
||||||
|
'(the mesh control channel)',
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -134,15 +134,10 @@
|
|||||||
{
|
{
|
||||||
"path": "/__mesh__/control",
|
"path": "/__mesh__/control",
|
||||||
"status": 101,
|
"status": 101,
|
||||||
"sent": [
|
"sent": [],
|
||||||
{
|
|
||||||
"id": "reserved",
|
|
||||||
"params": {}
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"close": {
|
"close": {
|
||||||
"code": 1005,
|
"code": 1008,
|
||||||
"reason": ""
|
"reason": "mesh control channel not enabled: this app exports nothing, or has no mesh.secret"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
* with no specificity ranking, an HTTP route at the same path never takes the upgrade, and the mesh
|
* with no specificity ranking, an HTTP route at the same path never takes the upgrade, and the mesh
|
||||||
* control path is checked before WS route matching. Captured through both upgrade entry points —
|
* control path is checked before WS route matching. Captured through both upgrade entry points —
|
||||||
* `app.upgrade` (Deno/Bun/edge) and the Node `server.on('upgrade')` listener — because they are
|
* `app.upgrade` (Deno/Bun/edge) and the Node `server.on('upgrade')` listener — because they are
|
||||||
* separate code paths and do not agree on everything (see the reserved-path rows in the fixture).
|
* separate code paths. They used to disagree on the reserved mesh path; since CARD-21 (D17) both refuse
|
||||||
|
* it with the same 1008 close.
|
||||||
*/
|
*/
|
||||||
import 'reflect-metadata';
|
import 'reflect-metadata';
|
||||||
import type { AddressInfo } from 'net';
|
import type { AddressInfo } from 'net';
|
||||||
@@ -40,10 +41,8 @@ class ParityWs {
|
|||||||
@Stream('/feed') feed() {
|
@Stream('/feed') feed() {
|
||||||
return announce('feed', {});
|
return announce('feed', {});
|
||||||
}
|
}
|
||||||
// A user route on the reserved mesh path, on an app with no mesh: the two adapters disagree here.
|
// No route on the reserved mesh path: since CARD-21 (D17) the boot refuses one. The path stays in
|
||||||
@Ws('/__mesh__/control') reserved(@param() p: Record<string, string>) {
|
// UPGRADE_PATHS so both adapters' refusal on an app with no mesh is captured; they now agree.
|
||||||
return announce('reserved', p);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Module({ mountpoint: '/', controllers: [ParityWs] })
|
@Module({ mountpoint: '/', controllers: [ParityWs] })
|
||||||
|
|||||||
Reference in new issue
Block a user