7 Commits
Author SHA1 Message Date
chrnx 7f9a0eef0f feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
Reading a cookie meant parsing the Cookie header by hand, and a response
could not carry more than one Set-Cookie: response header values were
Record<string, string>, and the fetch adapters would have stringified an
array into one broken "a,b" cookie anyway.

- @cookie('name') / @cookies() sit next to @header/@headers as a new
  'cookies' arg source. The header is parsed on first use per request and
  cached on the context, so a route without a cookie argument never parses
  it. RFC 6265: first value wins, %-sequences decoded, malformed pairs
  skipped (never a 400), undecodable values kept raw. Several cookie lines
  are joined with "; ". The map has no prototype. @needs('cookies') reads
  the same map, and 'cookies' joins the seed-key allow-list.
- setCookie(name, value, options) serialises one Set-Cookie value with
  HttpOnly, SameSite=Lax, Path=/ and Secure by default (D10), and throws,
  naming the field, on anything that could inject a header or that browsers
  reject (sameSite none / partitioned without secure).
- Response header values widen to string | string[] (D11) across
  TransformerFn, ErrorResponse, HttpError(Like).headers, ResponseShape and
  the neutral outcome. Node writes a set-cookie array as one line per
  element and joins every other array with ", " before writeHead; the
  fetch adapters build a Headers and append each set-cookie element.
  mergeInjectedHeaders keeps arrays by reference and joins a vary array
  before merging it.
- OpenAPI maps a cookie argument to an in: cookie parameter.

BREAKING CHANGE: code that reads a header value from TransformerFn,
ErrorResponse, HttpError or ResponseShape as a string must handle string[].

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:08:24 -05:00
chrnx 037e695a31 Merge pull request 'feat(mesh): remote routes follow teapot membership (CARD-19, #124)' (#146) from feature/fprd-001c-mesh-membership into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 28s
CI / runtimes (deno) (push) Successful in 20s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-23 06:08:09 +00:00
chrnx 9ea1365b66 test(router-parity): a late teapot is served after it connects for CARD-19 (owner approval required)
CI / runtimes (bun) (pull_request) Successful in 16s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
owner-mesh-lifetime.json froze phase B2 (teapot absent at boot, then up)
at 404 for GET and POST /api/remote/ping. The table was built once at
boot, so a late teapot was never spliced in. CARD-19 (#124, D15) changes
that. B2 now answers GET 200 {"from":"teapot"} and POST 405 with
Allow: GET, HEAD, OPTIONS, the same as A1.

Only those two entries change. A1, A2 and B1 are identical.

The fixture's teacup goes from reconnect: false to reconnect with a fast
backoff (20-60ms). Under D15, reconnect: false makes a dropped teapot
"gone" (404), and an absent one is not retried. The card's phases
describe the reconnecting teacup: A2 stays 503 and B2 becomes 200. B2
now waits for the mesh:routes event before probing. The fixture comment
and the corpus README line describing "built once at boot" are updated.

Owner approval required (CARD-08 rule): this edits a frozen file and the
fixture under test/router-parity/.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:04:40 -05:00
chrnx 6bbd78fc8e feat(mesh): remote routes follow teapot membership (CARD-19, #124)
The teacup built its route table once at boot. A teapot that started
late was never served, and one that was gone for good stayed advertised.
Implement D15 (accepted 2026-10-18):

- A teapot that missed bootTimeoutMs is retried in the background with
  the reconnect backoff (not with reconnect: false). On connect its
  routes join the remote table. Its steps do not, because the graph
  was validated at boot without them.
- While a link is reconnecting, its routes stay and answer 503, now
  with retry-after (seconds until the next attempt).
- A link that gives up for good (dropped with reconnect: false, or a
  permanent refusal while reconnecting) has its routes removed: 404,
  and Allow drops its methods. A refused reconnect no longer retries
  forever.
- A returning manifest replaces the teapot's routes. missingFromManifest
  now checks steps only, so a dropped route is removed instead of
  refusing the reconnect.
- A late route that conflicts with another teapot's is refused and
  logged. The table keeps serving. At boot the same conflict still
  fails boot.
- Each change emits mesh:routes with { url, added, removed }.
- The reserved-path check from CARD-21/CARD-17 (#141, #145) runs in
  the table for every remote route: at boot a route on /__mesh__/control
  (or /__live__ and /__ready__ with health on) fails boot as before. A
  late or returning one is refused and logged, and the teapot's other
  routes are served.

Mechanics: the remote table publishes a new array per change
(copy-on-write). app.fetch and listen() share one table through a
getter, and buildFetch/createHttpServer read it once per request, so a
request sees the old table or the new one, never a mix. The router
reuses local trees when the local entries are identical, so a
membership change rebuilds only the remote trees. Dev routes now sit
before remote ones in the table to keep the local positions stable.

Tests cover T1-T8 on Node (test/mesh/membership.test.ts), plus the
local-tree build counter and late reserved-path routes, and T1/T2 on
Deno and Bun.

The frozen owner-mesh-lifetime.json capture changes in the next commit.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:04:39 -05:00
chrnx c9e76fde2d Merge pull request 'fix(mesh): answer HEAD on a remote GET route (CARD-20, #125)' (#137) from feature/fprd-001c-mesh-remote-head into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 16s
CI / build (push) Successful in 27s
CI / runtimes (deno) (push) Successful in 21s
CI / runtimes (edge) (push) Successful in 14s
Promote → GitHub / push-github (push) Successful in 6s
2026-10-23 06:04:35 +00:00
chrnx ae9e5529e8 test(router-parity): HEAD on a remote GET answers 200 for CARD-20 (owner approval required)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 20s
owner-mesh-allow.json froze HEAD /api/x at 404 on both adapters: the
teacup forwarded HEAD to the teapot, which has no HEAD plan for the
route. CARD-20 (#125, D16) fixes that, so HEAD now answers 200 with the
GET's headers and an empty body, like a local route.

Only those two entries change (fetch and node), status 404 -> 200.
Headers and the empty body are identical. The fixture comment in
owner.test.ts that described the old behaviour is updated to match.

Owner approval required (CARD-08 rule): this edits a frozen file under
test/router-parity/.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:59:56 -05:00
chrnx 5783212377 fix(mesh): answer HEAD on a remote GET route (CARD-20, #125)
The teacup's router resolves HEAD to a remote buffered GET through the
implicit-HEAD fallback, and OPTIONS advertises HEAD. But the remote
route handler forwarded req.method, so the teapot got a HEAD envelope,
found no HEAD plan in resolveRoute, and answered 404.

Forward a HEAD that matched a remote GET as GET. dispatch already drops
the body for HEAD, so the client gets the GET's status and headers and
no body, the same as a local route. An explicit remote HEAD route is
matched first and is still forwarded as HEAD.

The fix is teacup-side (D16, accepted 2026-10-22): the teapot and the
wire protocol are unchanged, so a new teacup works against an older
teapot during a rolling deploy.

Tests cover app.fetch and the Node listener (200 + GET headers + empty
body, OPTIONS, explicit HEAD precedence, 404/500 kept with no body, the
teapot handler called once as GET) and Deno and Bun.

The frozen owner-mesh-allow.json capture changes in the next commit.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:59:56 -05:00
40 changed files with 2228 additions and 216 deletions

No files matched your search

+55
View File
@@ -10,6 +10,15 @@ npm treats versions as semver and semver forbids leading zeros.
### Breaking ### Breaking
- **Response header values are `string | string[]`** (#113, D11). `TransformerFn`, `ErrorResponse.headers`,
`HttpError.headers` / `HttpErrorLike.headers` and the pipeline's `ResponseShape.headers` widen from
`Record<string, string>`, so a response can carry several `Set-Cookie` lines. Code that *produces*
headers is unaffected; code that *reads* `headers[k]` from one of these types as a `string` stops
compiling and must handle the array. A `set-cookie` array is sent as one header line per element
on Node, Deno, Bun and the edge — before, the fetch adapters stringified it into one broken
`a,b` cookie. Any other array is sent as one line joined with `, `. Injected security and CORS
headers stay authoritative, and a handler's `vary` array is merged with the injected one.
- **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life - **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life
and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the
build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback
@@ -112,6 +121,17 @@ npm treats versions as semver and semver forbids leading zeros.
`false` or `{ drainDelayMs?: number }`. On the edge there is no `close()`, so `/__ready__` never `false` or `{ drainDelayMs?: number }`. On the edge there is no `close()`, so `/__ready__` never
reports `draining` there. reports `draining` there.
- **`@cookie('name')` / `@cookies()` argument decorators and `setCookie()`** (#113). Cookies are
parsed from the request's `Cookie` header on first use per request (RFC 6265: first value wins,
`%`-sequences decoded, malformed pairs skipped rather than answered with a 400), on HTTP and
WebSocket routes; `@needs('cookies')` gives the same map. OpenAPI lists a cookie argument as an
`in: cookie` parameter. `setCookie(name, value, options?)` returns a `Set-Cookie` value with
`HttpOnly`, `SameSite=Lax`, `Path=/` and `Secure` by default (D10; `secure: false` opts out), and
throws, naming the field, on a name outside the token set, a value with CR, LF, `;`, `,`,
whitespace or a control character, an attribute with CR/LF, `;` or a control character, and on
`sameSite: 'none'` or `partitioned` without `secure`. `parseCookies()` and `CookieOptions` are
exported too. No dependency: signing and sessions stay out of core.
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound - **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp` WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp`
throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message
@@ -139,6 +159,33 @@ npm treats versions as semver and semver forbids leading zeros.
`?` and before `#`, if there is one: `q: 'what?now'`, and `/search?a=1&b=?` gives `b: '?'`. URLs `?` 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. with a single `?` parse as before. Path extraction is unchanged.
- **Mesh (alpha): a teacup's remote routes follow which teapots are connected** (#124, D15). The
route table used to be built once at boot: a teapot that started late was never served, and a
teapot that was gone for good stayed advertised. Now:
- A teapot that missed `bootTimeoutMs` is retried in the background with the `reconnect` backoff.
When it connects, its routes are served, with no restart. Its steps are not added, because the
graph was validated at boot without them. With `reconnect: false` it is not retried.
- While a link is reconnecting, its routes stay and answer `503`, now with `retry-after` (the
seconds until the next attempt). `Allow` keeps them.
- A link that gives up for good has its routes removed: they answer `404` and leave `Allow`. That
is a link dropped with `reconnect: false`, or one refused permanently (a wrong secret, a protocol
mismatch) while reconnecting. A refused reconnect used to retry forever. It now stops.
- A returning teapot's routes replace its old ones: a route it added is served, one it dropped
answers `404`. A returning manifest is still refused for a missing **step**
(`onManifestChange: 'refuse'`), but no longer for a missing route.
- A late route that conflicts with another teapot's (same shape, or a CARD-13 sibling conflict)
is refused and logged, and the rest keep serving. At boot the same conflict still fails boot.
- A late or returning route on a reserved path (`/__mesh__/control`, and `/__live__`/`/__ready__`
with `health` on) is refused and logged the same way. At boot it still fails boot.
- Every change emits `mesh:routes` with `{ url, added, removed }` (new `EventPayload` fields).
Membership changes publish a new table. A request in flight routes against the old one or the
new one, never a mix. Only the remote route trees are rebuilt. `listen()` now reads the same
table as `app.fetch`, and `createHttpServer` accepts a getter as well as an array. Dev
introspection routes (`devGraph`, `devOpenapi`) now sit before remote routes in that table, so
in the one case where a teapot exports the same path at the same specificity, the dev route wins.
### Fixed ### Fixed
- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler` - **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler`
@@ -148,6 +195,14 @@ npm treats versions as semver and semver forbids leading zeros.
Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a
bare `app.fetch`, ignore it as before. bare `app.fetch`, ignore it as before.
- **Mesh (alpha): `HEAD` on a remote `GET` route now works** (#125). The teacup resolved `HEAD` to
the remote `GET` and `OPTIONS` advertised `HEAD`, but the request went to the teapot as `HEAD`,
which has no `HEAD` plan, so it answered `404`. The teacup now forwards it as a `GET` and drops
the body, so it answers like a local route: the `GET`'s status and headers, no body, and a
`404`/`500` from the route keeps its status. An explicit remote `HEAD` route still takes
precedence. The teapot is unchanged, so a new teacup works against an older teapot during a
rolling deploy.
- **`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
+4
View File
@@ -244,6 +244,10 @@ The handler signature declares exactly what it wants — in any order, nothing m
| `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` | | `@body(...)` | parsed body (JSON / urlencoded / multipart) | `()` · `('field')` · `(schema)` |
| `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` | | `@headers(...)` | request headers (whole bag or picked) | `()` · `('authorization')` · `(['a','b'])` · `(schema)` |
| `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` | | `@header('name')` | one request header (singular alias of `@headers`) | `('x-trace')` · `('x-count', schema)` |
| `@cookies(...)` | request cookies, parsed from `Cookie` (whole map or picked) | `()` · `('sid')` · `(['a','b'])` · `(schema)` |
| `@cookie('name')` | one request cookie (singular alias of `@cookies`) | `('sid')` · `('sid', schema)` |
To send cookies, `setCookie(name, value, options?)` returns a `Set-Cookie` value with safe defaults (`HttpOnly`, `SameSite=Lax`, `Path=/`, `Secure`) and throws on anything that could inject a header. Response header values are `string | string[]`: a `set-cookie` array is sent as one line per cookie on every runtime, any other array as one line joined with `, `. Pass `secure: false` where the browser will not keep a `Secure` cookie over plain HTTP (Safari, a LAN IP). Signing and sessions are not in core.
`@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it. `@needs` keys are validated at boot: nothing provides the key → `createApp` throws with a clear error instead of serving `undefined`. Pass a Standard Schema (`@body(User)`) and the value is validated, coerced, and typed before your handler sees it.
+334 -111
View File
@@ -44,7 +44,7 @@ import { buildOpenApi, type OpenApiInfo } from '../openapi';
import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; 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, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup';
import { buildManifest, createMeshControl, MESH_CONTROL_DISABLED_REASON, 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';
@@ -59,6 +59,9 @@ export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from '
type Runner = (ctx: any) => any; type Runner = (ctx: any) => any;
/** Something shutdown closes: a mesh link, or the retry loop of a teapot that missed boot. */
type Closable = Pick<Link, 'close'>;
/** Mutable graph state assembled from modules/plugins and later spliced with remote mesh scopes. */ /** Mutable graph state assembled from modules/plugins and later spliced with remote mesh scopes. */
interface Registry { interface Registry {
providerNodes: GraphNode[]; providerNodes: GraphNode[];
@@ -258,8 +261,7 @@ export function createApp(opts: {
let orderedProviders: GraphNode[] = []; let orderedProviders: GraphNode[] = [];
let orderedSteps: GraphNode[] = []; let orderedSteps: GraphNode[] = [];
let booted = false; let booted = false;
let remoteRoutes: RouteDef[] = []; const meshLinks: Closable[] = [];
const meshLinks: Link[] = [];
const finalize = (missingNote?: string): void => { const finalize = (missingNote?: string): void => {
({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote)); ({ orderedProviders, orderedSteps } = finalizeGraph(registry, logger, opts.warnGraphDepth, missingNote));
@@ -278,8 +280,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, reserved); const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, reserved, publishRemote);
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
// about the teapot that was away — which is the actual cause every time it is the cause. // about the teapot that was away — which is the actual cause every time it is the cause.
@@ -325,6 +326,11 @@ export function createApp(opts: {
return routes; return routes;
}; };
// The one HTTP route table, shared by app.fetch and listen() — see createRouteTable.
const table = createRouteTable(() => [...buildHttpRoutes(routePlans, pipelineDeps), ...devRoutes()]);
const currentTable = table.current;
const publishRemote = table.publish;
// 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 bootGraph = makeAppBooter( const bootGraph = makeAppBooter(
@@ -353,14 +359,7 @@ export function createApp(opts: {
static: staticResolver, static: staticResolver,
health: healthProbe, health: healthProbe,
}; };
const fetchFn = buildAppFetch( const fetchFn = buildAppFetch(fetchOpts, bootApp, currentTable);
routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError, logger },
fetchOpts,
bootApp,
devRoutes,
() => remoteRoutes,
);
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, { const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
limits: opts.limits, limits: opts.limits,
trustProxy: opts.trustProxy, trustProxy: opts.trustProxy,
@@ -373,10 +372,10 @@ export function createApp(opts: {
// and builds the mesh control channel — so Node and Deno/Bun serve an identical graph // and builds the mesh control channel — so Node and Deno/Bun serve an identical graph
await bootApp(); await bootApp();
const httpRoutes = [...buildHttpRoutes(routePlans, remoteRoutes, deps), ...devRoutes()];
const wsRoutes = buildWsRoutes(routePlans, deps); const wsRoutes = buildWsRoutes(routePlans, deps);
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { // A getter, not an array: mesh membership can change the table after this server starts.
server = createHttpServer(currentTable, wsRoutes, bus, meshControl, {
bus, bus,
logger, logger,
limits: opts.limits, limits: opts.limits,
@@ -884,7 +883,17 @@ function assertNeedsSatisfiable(
...providerNodes.flatMap((node) => node.provides), ...providerNodes.flatMap((node) => node.provides),
...stepNodes.flatMap((node) => node.provides), ...stepNodes.flatMap((node) => node.provides),
]); ]);
const allowed = new Set<string>([...producedKeys, 'req', 'params', 'query', 'body', 'headers', 'inbound', 'abort']); const allowed = new Set<string>([
...producedKeys,
'req',
'params',
'query',
'body',
'headers',
'cookies',
'inbound',
'abort',
]);
for (const plan of routePlans) { for (const plan of routePlans) {
for (const need of plan.needs) { for (const need of plan.needs) {
@@ -1046,25 +1055,173 @@ function assertNoRemoteSiblingConflict(accepted: RemoteRoute[], route: RemoteRou
} }
} }
/** Connects the configured teapots, splices their remote steps into the registry, and returns their routes. */ /** A teapot route the remote table serves: its export, its owner, and the def the router files. */
async function spliceRemoteScopes( interface ServedRemote extends RemoteRoute {
mesh: MeshConfig, def: RouteDef;
bus: Bus, }
/**
* The teacup's remote routes, by teapot, published as a fresh array on every change (D15).
*
* Never mutated in place: the router caches an index by array identity, and a request that is
* already routing keeps the array it read, so it sees the whole old table or the whole new one.
*/
interface RemoteTable {
/**
* Replaces one teapot's routes and publishes the table. With `strict` (boot) a conflicting route
* fails the boot; after boot it is refused and logged, and everything else keeps serving.
*/
set(url: string, routes: TeacupRemoteRoute[], strict: boolean): { added: string[]; removed: string[] };
}
const showRoute = (route: { method: string; pattern: string }): string => `${route.method} ${route.pattern}`;
/**
* Throws when `route` cannot join the remote routes already accepted: the same effective shape and
* method as one of them, or a sibling conflict (CARD-13). Route matching keeps the first of two
* identical patterns, so the loser would be silently dead — and callers could come to depend on
* "first teapot wins", which would make adding balancing later a breaking change.
*/
function assertRemoteRouteFits(accepted: RemoteRoute[], route: RemoteRoute): void {
const shape = compilePattern(route.pattern).shape;
const owner = accepted.find(
(prior) => prior.method === route.method && compilePattern(prior.pattern).shape === shape,
);
if (owner) {
throw new Error(
`mesh: ambiguous remote route '${showRoute(route)}' from ${route.url} conflicts with ` +
`'${showRoute(owner)}' from ${owner.url} — ` +
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
'Export it from a single teapot.',
);
}
assertNoRemoteSiblingConflict(accepted, route);
}
/**
* Local routes are merged ahead of remote ones (see the route table), so a local twin wins. That
* precedence is deliberate — your own code beats an imported one, and it is how you override a
* teapot — but silently shadowing an export looks exactly like a broken teapot from the outside.
* Warn and let the developer decide.
*/
function warnIfShadowed(registry: Registry, route: RemoteRoute, logger: Logger): void {
const shape = compilePattern(route.pattern).shape;
if (!registry.routePlans.some((plan) => plan.method === route.method && compilePattern(plan.pattern).shape === shape))
return;
logger.warn(
`mesh: route '${showRoute(route)}' is exported by teapot ${route.url} but also declared locally — ` +
'the local route takes precedence and the remote one will not be reached. ' +
'Remove one if that is not what you meant.',
);
}
/** The route the router files for a teapot's export: marked remote, and forwarding a built envelope. */
function remoteRouteDef(route: TeacupRemoteRoute): RouteDef {
// Marked so the router files it in the remote tree; precedence is unchanged by the split.
return markRemoteRoute({
method: route.method,
pattern: route.pattern,
transport: 'buffer',
// Built explicitly rather than cast from the handler argument. The cast put the whole
// internal request on the wire — `ip` and `protocol` included — and sent fields the
// protocol never declared, so a teapot could come to rely on something we never promised.
handler: async (req) =>
route.handler({
// HEAD reaches a remote GET through the implicit-HEAD fallback, and the teapot looks
// its plan up by method, so a forwarded HEAD finds none and answers 404. Send it as the
// GET it resolved to; dispatch drops the body for HEAD. Fixed teacup-side (D16) so an
// unchanged, older teapot still answers it during a rolling deploy.
method: req.method === 'HEAD' && route.method === 'GET' ? 'GET' : req.method,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId },
}),
});
}
/** Builds the remote table over the configured teapots, in configuration order. */
function createRemoteTable(
urls: string[],
registry: Registry, registry: Registry,
logger: Logger, logger: Logger,
reserved: readonly ReservedPath[], reserved: readonly ReservedPath[],
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> { publish: (routes: RouteDef[]) => void,
const remoteRoutes: RouteDef[] = []; ): RemoteTable {
const meshLinks: Link[] = []; const byUrl = new Map<string, ServedRemote[]>();
const absent: string[] = []; // urls of teapots that never connected within the boot budget
const routeOwners = new Map<string, { url: string; pattern: string }>(); // "METHOD effective-shape" -> owner return {
const remoteAccepted: RemoteRoute[] = []; // every remote route spliced so far, in teapot order set(url, routes, strict) {
const others = urls.filter((other) => other !== url).flatMap((other) => byUrl.get(other) ?? []);
const before = new Set((byUrl.get(url) ?? []).map(showRoute));
const next: ServedRemote[] = [];
for (const route of routes) {
const candidate: RemoteRoute = { method: route.method, pattern: route.pattern, url };
try { try {
for (const teapot of mesh.teapots ?? []) { // A teapot's own boot refuses a reserved path, but the manifest is whatever arrives on the
warnIfCleartext(teapot.url, logger); // wire: an older or foreign teapot could still advertise one, at boot or later, and the
const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => // teacup must not splice it (CARD-21/CARD-17).
connectLink({ assertNotReserved(route.pattern, `mesh: remote route '${showRoute(route)}' from ${url}`, reserved);
assertRemoteRouteFits([...others, ...next], candidate);
} catch (error) {
if (strict) throw error;
// Refused for this teapot only; the table that is serving stays as it was (D15, rule 5).
// The same goes for a reserved path: that one route is skipped, the rest are served.
logger.warn(`mesh: not serving a route from ${url} — ${(error as Error).message}`);
continue;
}
if (!before.has(showRoute(candidate))) warnIfShadowed(registry, candidate, logger);
next.push({ ...candidate, def: remoteRouteDef(route) });
}
byUrl.set(url, next);
publish(urls.flatMap((other) => (byUrl.get(other) ?? []).map((served) => served.def)));
const after = new Set(next.map(showRoute));
return {
added: [...after].filter((key) => !before.has(key)),
removed: [...before].filter((key) => !after.has(key)),
};
},
};
}
/** What a teapot's link needs to report membership back to the remote table after boot. */
interface MembershipContext {
mesh: MeshConfig;
bus: Bus;
logger: Logger;
table: RemoteTable;
}
/** Applies one teapot's routes after boot and emits `mesh:routes` when the table actually changed. */
function applyMembership(ctx: MembershipContext, url: string, routes: TeacupRemoteRoute[]): void {
const { added, removed } = ctx.table.set(url, routes, false);
if (!added.length && !removed.length) return;
ctx.bus.emit('mesh:routes', { name: url, url, added, removed });
}
/**
* Opens a link to one teapot, wired so a returning manifest updates its routes and a link that
* gives up for good removes them (D15). `holder.link` is filled in once the link exists, because
* the callbacks need the link to rebuild its route proxies.
*/
function connectTeapot(
ctx: MembershipContext,
teapot: { url: string; secret: string },
holder: { link?: Link },
): Promise<Link> {
const { mesh, bus, logger } = ctx;
return connectLink({
url: teapot.url, url: teapot.url,
secret: teapot.secret, secret: teapot.secret,
timeoutMs: mesh.timeoutMs, timeoutMs: mesh.timeoutMs,
@@ -1073,14 +1230,120 @@ async function spliceRemoteScopes(
onManifestChange: mesh.onManifestChange, onManifestChange: mesh.onManifestChange,
logger, logger,
bus, bus,
}), onReconnect: () => {
if (holder.link) applyMembership(ctx, teapot.url, buildRemote(holder.link).routes);
},
onGone: () => {
logger.warn(`mesh: teapot ${teapot.url} is gone for good — its routes are removed and now answer 404.`);
applyMembership(ctx, teapot.url, []);
},
});
}
/** Backoff bounds for retrying a late teapot: the reconnect ones, or nothing when reconnect is off. */
function lateBounds(mesh: MeshConfig): { initial: number; max: number } | undefined {
if (mesh.reconnect === false) return undefined;
const opts = typeof mesh.reconnect === 'object' ? mesh.reconnect : {};
return { initial: opts.initialDelayMs ?? 500, max: opts.maxDelayMs ?? 30_000 };
}
/**
* Keeps trying a teapot that missed the boot budget, with the reconnect backoff (D15, rule 1). When
* it connects, its routes join the remote table; its steps do not, because the graph was validated
* at boot without them. A permanent refusal stops the retries. The handle's `close()` stops them too,
* and closes the link if one came up, so shutdown never leaves a retry behind.
*/
function retryLateTeapot(
ctx: MembershipContext,
teapot: { url: string; secret: string },
bounds: { initial: number; max: number },
): { close: () => void } {
const holder: { link?: Link } = {};
let stopped = false;
let attempt = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
const schedule = (): void => {
const capped = Math.min(bounds.initial * 2 ** attempt++, bounds.max);
timer = setTimeout(() => void tryOnce(), Math.round(capped / 2 + Math.random() * (capped / 2)));
timer.unref?.();
};
const tryOnce = async (): Promise<void> => {
try {
const link = await connectTeapot(ctx, teapot, holder);
if (stopped) return link.close();
holder.link = link;
const { steps, routes } = buildRemote(link);
if (steps.length)
ctx.logger.warn(
`mesh: teapot ${teapot.url} connected after boot — its routes are served now, but its steps ` +
`(${steps.map((step) => step.name).join(', ')}) are not: the graph was fixed at boot without them.`,
); );
applyMembership(ctx, teapot.url, routes);
} catch (error) {
if (stopped) return;
if (isPermanentRefusal(error)) {
ctx.logger.error(
`mesh: teapot ${teapot.url} refused this peer — no longer retrying it (${(error as Error).message})`,
);
return;
}
schedule();
}
};
schedule();
return {
close: () => {
stopped = true;
clearTimeout(timer);
holder.link?.close();
},
};
}
/**
* Connects the configured teapots, splices their remote steps into the registry, and publishes their
* routes through `publish`, now and whenever membership changes after boot (D15).
*/
async function spliceRemoteScopes(
mesh: MeshConfig,
bus: Bus,
registry: Registry,
logger: Logger,
reserved: readonly ReservedPath[],
publish: (routes: RouteDef[]) => void,
): Promise<{ meshLinks: Closable[]; absent: string[] }> {
const meshLinks: Closable[] = [];
const absent: string[] = []; // urls of teapots that never connected within the boot budget
const teapots = mesh.teapots ?? [];
const table = createRemoteTable(
teapots.map((teapot) => teapot.url),
registry,
logger,
reserved,
publish,
);
const ctx: MembershipContext = { mesh, bus, logger, table };
try {
for (const teapot of teapots) {
warnIfCleartext(teapot.url, logger);
const holder: { link?: Link } = {};
const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => connectTeapot(ctx, teapot, holder));
if (!link) { if (!link) {
absent.push(teapot.url); absent.push(teapot.url);
const bounds = lateBounds(mesh);
if (bounds) meshLinks.push(retryLateTeapot(ctx, teapot, bounds));
continue; continue;
} }
holder.link = link;
meshLinks.push(link); meshLinks.push(link);
const { steps, routes } = buildRemote(link); const { steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`; const origin = `mesh:${teapot.url}`;
@@ -1090,82 +1353,14 @@ async function spliceRemoteScopes(
registry.setRunner(step.name, step.run); registry.setRunner(step.name, step.run);
} }
for (const route of routes) { table.set(teapot.url, routes, true);
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 owner = routeOwners.get(key);
// Fail the boot rather than pick one. Route matching keeps the first of two identical
// patterns, so the loser would be silently dead — and callers could come to depend on
// "first teapot wins", which would make adding balancing later a breaking change.
// Scope tokens already fail this way in setRunner; routes now match.
if (owner) {
throw new Error(
`mesh: ambiguous remote route '${display}' from ${teapot.url} conflicts with ` +
`'${route.method} ${owner.pattern}' from ${owner.url} — ` +
'load balancing across teapots is not implemented yet, so green-tea will not choose one for you. ' +
'Export it from a single teapot.',
);
}
routeOwners.set(key, { url: teapot.url, pattern: route.pattern });
assertNoRemoteSiblingConflict(remoteAccepted, {
method: route.method,
pattern: route.pattern,
url: teapot.url,
});
remoteAccepted.push({ method: route.method, pattern: route.pattern, url: teapot.url });
// Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin
// wins. That precedence is deliberate — your own code beats an imported one, and it is
// how you override a teapot — but silently shadowing an export looks exactly like a
// broken teapot from the outside. Warn and let the developer decide.
if (
registry.routePlans.some(
(plan) =>
plan.method === route.method &&
compilePattern(plan.pattern).shape === compilePattern(route.pattern).shape,
)
) {
logger.warn(
`mesh: route '${display}' is exported by teapot ${teapot.url} but also declared locally — ` +
'the local route takes precedence and the remote one will not be reached. ' +
'Remove one if that is not what you meant.',
);
}
// Marked so the router files it in the remote tree; precedence is unchanged by the split.
remoteRoutes.push(
markRemoteRoute({
method: route.method,
pattern: route.pattern,
transport: 'buffer',
// Built explicitly rather than cast from the handler argument. The cast put the whole
// internal request on the wire — `ip` and `protocol` included — and sent fields the
// protocol never declared, so a teapot could come to rely on something we never promised.
handler: async (req) =>
route.handler({
method: req.method,
params: req.params,
query: req.query,
body: req.body,
headers: req.headers,
url: req.url,
correlation: { requestId: req.requestId, traceId: req.traceId },
}),
}),
);
}
} }
} catch (err) { } catch (err) {
closeLinks(meshLinks); closeLinks(meshLinks);
throw err; throw err;
} }
return { remoteRoutes, meshLinks, absent }; return { meshLinks, absent };
} }
/** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */ /** Swaps provider/step runners by token — a value replaces the runner, a function becomes it. */
@@ -1390,8 +1585,39 @@ function buildMeshControl(
return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus }); return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus });
} }
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */ /**
function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps: PipelineDeps): RouteDef[] { * The one HTTP route table, shared by app.fetch and listen(): local and dev routes, then remote ones.
* Built after boot, on first use. A mesh membership change publishes a new array with the same local
* head (D15), so the router reuses its local trees and rebuilds only the remote ones, and a request in
* flight keeps the array it read. Dev routes sit before the remote ones so their positions, and with
* them the local trees, do not move when remote routes come and go.
*/
function createRouteTable(buildLocal: () => RouteDef[]): {
current: () => RouteDef[];
publish: (remote: RouteDef[]) => void;
} {
let remote: RouteDef[] = [];
let local: RouteDef[] | undefined;
let table: RouteDef[] | undefined;
return {
current: () => {
if (!table) {
local = buildLocal();
table = [...local, ...remote];
}
return table;
},
publish: (next) => {
remote = next;
if (local) table = [...local, ...next];
},
};
}
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline. */
function buildHttpRoutes(routePlans: RoutePlan[], deps: PipelineDeps): RouteDef[] {
const { providedSeed, planSteps, bus, onError, logger } = deps; const { providedSeed, planSteps, bus, onError, logger } = deps;
const local = routePlans const local = routePlans
@@ -1436,7 +1662,7 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
}, },
})); }));
return [...local, ...remoteRoutes]; return local;
} }
/** /**
@@ -1447,12 +1673,9 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
* costs one flag check per request after the first. * costs one flag check per request after the first.
*/ */
function buildAppFetch( function buildAppFetch(
routePlans: RoutePlan[],
deps: PipelineDeps,
fetchOpts: HttpOptions, fetchOpts: HttpOptions,
ensureBooted: () => Promise<void>, ensureBooted: () => Promise<void>,
devRoutes: () => RouteDef[], getRoutes: () => RouteDef[],
getRemoteRoutes: () => RouteDef[],
): (request: Request) => Promise<Response> { ): (request: Request) => Promise<Response> {
let handler: ((request: Request) => Promise<Response>) | undefined; let handler: ((request: Request) => Promise<Response>) | undefined;
@@ -1471,7 +1694,7 @@ function buildAppFetch(
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) {
handler = buildFetch([...buildHttpRoutes(routePlans, getRemoteRoutes(), deps), ...devRoutes()], fetchOpts); handler = buildFetch(getRoutes, fetchOpts);
} }
return handler(request); return handler(request);
@@ -1665,7 +1888,7 @@ function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: numbe
function closeApp( function closeApp(
server: http.Server | undefined, server: http.Server | undefined,
meshLinks: Link[], meshLinks: Closable[],
streams: Set<() => void>, streams: Set<() => void>,
options: { timeoutMs?: number }, options: { timeoutMs?: number },
defaultTimeoutMs: number | undefined, defaultTimeoutMs: number | undefined,
@@ -1750,7 +1973,7 @@ function closeApp(
} }
/** Best-effort close of every mesh link, ignoring individual failures. */ /** Best-effort close of every mesh link, ignoring individual failures. */
function closeLinks(links: Link[]): void { function closeLinks(links: Closable[]): void {
for (const link of links) { for (const link of links) {
try { try {
link.close(); link.close();
+14
View File
@@ -144,6 +144,13 @@ export interface MeshConfig {
* `false` restores that fail-once behaviour. An object tunes the backoff, which doubles from * `false` restores that fail-once behaviour. An object tunes the backoff, which doubles from
* `initialDelayMs` (500ms) up to `maxDelayMs` (30s) with jitter, so teacups that went down * `initialDelayMs` (500ms) up to `maxDelayMs` (30s) with jitter, so teacups that went down
* together do not come back in lockstep. * together do not come back in lockstep.
*
* It also decides what a dropped teapot's routes do (D15). While a link is reconnecting its routes
* stay in the table and answer `503` with `retry-after`, and `Allow` keeps them. A link that gives
* up for good — dropped with `reconnect: false`, or refused permanently (a wrong secret, a
* protocol mismatch) while reconnecting — has its routes removed: they answer `404` and leave
* `Allow`. Each change emits `mesh:routes` with `{ url, added, removed }`. A teapot that missed
* `bootTimeoutMs` is retried in the background with this backoff, unless it is `false`.
*/ */
reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number }; reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
/** /**
@@ -154,6 +161,9 @@ export interface MeshConfig {
* Serving against a manifest that no longer backs the graph would surface as a 500 that looks * Serving against a manifest that no longer backs the graph would surface as a 500 that looks
* like application code. A future `'reconcile'` will rebuild the graph instead; it is named here * like application code. A future `'reconcile'` will rebuild the graph instead; it is named here
* rather than left implicit so that arriving is additive rather than a change of default. * rather than left implicit so that arriving is additive rather than a change of default.
*
* Only steps count. Routes are not part of the graph, so a returning teapot's routes replace its
* old ones: a route it added is served, one it dropped answers `404` (D15).
*/ */
onManifestChange?: 'refuse'; onManifestChange?: 'refuse';
/** /**
@@ -170,6 +180,10 @@ export interface MeshConfig {
* one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a * one of its tokens still fails the boot, naming it. A permanent refusal — a wrong secret, a
* protocol mismatch — fails at once without spending the grace. * protocol mismatch — fails at once without spending the grace.
* *
* After boot, such a teapot keeps being retried in the background with the `reconnect` backoff
* (not with `reconnect: false`). When it connects, its routes are added to the table and served;
* its steps are not, because the graph was validated at boot without them (D15).
*
* `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing * `0` means one attempt and no grace. That is the attempt count boot used to have, and nothing
* more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and * more: exhausting it no longer fails the boot, so a single unreachable teapot still warns and
* starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens. * starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens.
+9
View File
@@ -45,6 +45,9 @@ export type LifecycleEvent =
// Separate from `mesh:disconnect`, which is a link that was up and went away — this one never // Separate from `mesh:disconnect`, which is a link that was up and went away — this one never
// came up, and a deploy watching for trouble wants to tell those apart. // came up, and a deploy watching for trouble wants to tell those apart.
| 'mesh:boot:retry' | 'mesh:boot:retry'
// A teacup's remote routes changed after boot (D15): a late teapot connected, a returning one
// exported a different set, or a link gave up for good. Carries `url`, `added` and `removed`.
| 'mesh:routes'
| 'plugin:mounted' | 'plugin:mounted'
// Paired: see the guarantee above. `request:start` has no status and no duration — it says a // Paired: see the guarantee above. `request:start` has no status and no duration — it says a
// request arrived, not that it routed. // request arrived, not that it routed.
@@ -125,6 +128,12 @@ export interface EventPayload {
* framework does not know what was sent, and will not guess. * framework does not know what was sent, and will not guess.
*/ */
status?: number; status?: number;
/** `mesh:routes`: the teapot whose routes changed. */
url?: string;
/** `mesh:routes`: routes added to the remote table, as `'METHOD /pattern'`. */
added?: string[];
/** `mesh:routes`: routes removed from the remote table, as `'METHOD /pattern'`. */
removed?: string[];
} }
/** /**
+150
View File
@@ -0,0 +1,150 @@
// src/cookies.ts — request cookie parsing and `Set-Cookie` serialisation (RFC 6265), dependency-free.
/**
* Options for {@link setCookie}. Every attribute is optional; the defaults are the safe ones
* (`httpOnly: true`, `sameSite: 'lax'`, `path: '/'`, `secure: true`).
*/
export interface CookieOptions {
/** `Max-Age` in seconds. An integer; `0` or a negative value tells the browser to drop the cookie. */
maxAge?: number;
/** `Expires`, written as an HTTP date. `maxAge` wins in browsers when both are set. */
expires?: Date;
/** `Path`. Default `'/'`. */
path?: string;
/** `Domain`. Omitted by default, which scopes the cookie to the exact host that set it. */
domain?: string;
/**
* `Secure`. Default `true`: Chrome, Edge and Firefox accept a `Secure` cookie on
* `http://localhost`. Safari, a LAN IP or a plain-HTTP dev hostname do not — pass `false` there
* (for example `secure: !isDev`).
*/
secure?: boolean;
/** `HttpOnly`. Default `true`, so page scripts cannot read the cookie. */
httpOnly?: boolean;
/** `SameSite`. Default `'lax'`. `'none'` requires `secure`. */
sameSite?: 'strict' | 'lax' | 'none';
/** `Partitioned` (CHIPS). Requires `secure`. */
partitioned?: boolean;
}
/** RFC 6265 §4.1.1 cookie-name: an RFC 7230 token. */
const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
/** What a cookie value may not contain: CR, LF, `;`, `,`, whitespace and every control character. */
// eslint-disable-next-line no-control-regex
const BAD_VALUE = /[\u0000- ;,\u007f]/;
/**
* What an attribute value may not contain. CR/LF is the header-injection case the card names; `;`
* and the other control characters are refused too, because a `;` inside `Path` would start a new
* attribute and change what the cookie means without breaking the header.
*/
// eslint-disable-next-line no-control-regex
const BAD_ATTRIBUTE = /[\u0000-\u001f;\u007f]/;
const SAME_SITE = { strict: 'Strict', lax: 'Lax', none: 'None' } as const;
/**
* Serialises one `Set-Cookie` header value.
*
* Throws, naming the field, rather than producing a header that would split or reshape the
* response: a name outside the RFC 6265 token set, a value carrying CR, LF, `;`, `,`, whitespace or a
* control character, an attribute carrying CR/LF, `;` or a control character, a non-integer
* `maxAge`, an invalid `expires`, and `sameSite: 'none'` or `partitioned` without `secure`.
*
* The value is written as given. Encode it yourself (`encodeURIComponent`) if it can hold any of the
* refused characters; the cookie decorators decode `%`-sequences on the way back in.
*
* Several cookies on one response go in an array: `headers: { 'set-cookie': [a, b] }`, and each
* element is sent as its own `Set-Cookie` line on every adapter.
*
* @example
* setCookie('session', id, { maxAge: 3600 })
* // 'session=<id>; Max-Age=3600; Path=/; Secure; HttpOnly; SameSite=Lax'
*/
export function setCookie(name: string, value: string, options: CookieOptions = {}): string {
if (typeof name !== 'string' || !TOKEN.test(name))
throw new TypeError(`setCookie: name ${JSON.stringify(name)} is not a valid cookie name (RFC 6265 token)`);
if (typeof value !== 'string' || BAD_VALUE.test(value))
throw new TypeError(
`setCookie: value for '${name}' contains a character a cookie value cannot carry (CR, LF, ';', ',', whitespace or a control character)`,
);
const secure = options.secure ?? true;
const sameSite = options.sameSite ?? 'lax';
const parts = [`${name}=${value}`];
if (options.maxAge !== undefined) {
if (!Number.isInteger(options.maxAge)) throw new TypeError(`setCookie: maxAge for '${name}' must be an integer`);
parts.push(`Max-Age=${options.maxAge}`);
}
if (options.expires !== undefined) {
if (!(options.expires instanceof Date) || Number.isNaN(options.expires.getTime()))
throw new TypeError(`setCookie: expires for '${name}' must be a valid Date`);
parts.push(`Expires=${options.expires.toUTCString()}`);
}
if (options.domain !== undefined) parts.push(`Domain=${attribute(name, 'domain', options.domain)}`);
parts.push(`Path=${attribute(name, 'path', options.path ?? '/')}`);
if (secure) parts.push('Secure');
if (options.httpOnly ?? true) parts.push('HttpOnly');
if (!Object.prototype.hasOwnProperty.call(SAME_SITE, sameSite))
throw new TypeError(`setCookie: sameSite for '${name}' must be 'strict', 'lax' or 'none'`);
if (sameSite === 'none' && !secure)
throw new TypeError(`setCookie: sameSite 'none' for '${name}' requires secure (browsers reject it otherwise)`);
parts.push(`SameSite=${SAME_SITE[sameSite]}`);
if (options.partitioned) {
if (!secure) throw new TypeError(`setCookie: partitioned for '${name}' requires secure`);
parts.push('Partitioned');
}
return parts.join('; ');
}
function attribute(name: string, field: string, value: string): string {
if (typeof value !== 'string' || value === '' || BAD_ATTRIBUTE.test(value))
throw new TypeError(
`setCookie: ${field} for '${name}' must be a non-empty string without CR, LF, ';' or control characters`,
);
return value;
}
/**
* Parses a request `Cookie` header into a name → value map (RFC 6265 §5.2 / §4.2).
*
* - The first value wins for a repeated name — the browser sends the most specific cookie first.
* - `%`-sequences are decoded; a value that fails to decode is kept raw rather than rejected.
* - A malformed pair (no `=`, or an empty name) is skipped. A broken cookie never becomes a 400:
* the header is client state the server did not choose and the request may not even need it.
* - Several `cookie` lines (HTTP/2, some proxies) arrive as an array and are joined with `; `.
*
* The map has no prototype, so a cookie named `__proto__` or `constructor` is just a key.
*/
export function parseCookies(header: string | string[] | undefined): Record<string, string> {
const out: Record<string, string> = Object.create(null);
if (header === undefined) return out;
const raw = Array.isArray(header) ? header.join('; ') : header;
for (const pair of raw.split(';')) {
const eq = pair.indexOf('=');
if (eq === -1) continue;
const key = pair.slice(0, eq).trim();
if (key === '' || key in out) continue;
out[key] = decode(pair.slice(eq + 1).trim());
}
return out;
}
function decode(value: string): string {
if (!value.includes('%')) return value;
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ import type { MatchedRoute, HttpOptions } from './types';
/** A ready-to-send error response produced while acquiring the request body. */ /** A ready-to-send error response produced while acquiring the request body. */
export interface BodyFailure { export interface BodyFailure {
fail: { status: number; headers: Record<string, string>; body: string }; fail: { status: number; headers: Record<string, string | string[]>; body: string };
} }
/** A value, or a promise of one. Readers that have nothing to await return the value directly. */ /** A value, or a promise of one. Readers that have nothing to await return the value directly. */
+3 -3
View File
@@ -85,10 +85,10 @@ export function correlateRequest(headers: Record<string, string | string[] | und
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */ /** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
export type NeutralOutcome = export type NeutralOutcome =
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer } | { kind: 'buffered'; status: number; headers: Record<string, string | string[]>; body: string | Buffer }
| { | {
kind: 'stream'; kind: 'stream';
headers: Record<string, string>; headers: Record<string, string | string[]>;
stream: AsyncIterable<unknown>; stream: AsyncIterable<unknown>;
encoder: StreamEncoder; encoder: StreamEncoder;
/** The matched route's pattern, for naming the stream lifecycle events. */ /** The matched route's pattern, for naming the stream lifecycle events. */
@@ -126,7 +126,7 @@ function errorOutcome(
req: NeutralRequest, req: NeutralRequest,
injected: Record<string, string>, injected: Record<string, string>,
opts: HttpOptions | undefined, opts: HttpOptions | undefined,
headers: Record<string, string> = {}, headers: Record<string, string | string[]> = {},
): HandleResult { ): HandleResult {
const rendered = renderError(error, req, opts?.onError, opts?.logger); const rendered = renderError(error, req, opts?.onError, opts?.logger);
return { return {
+46 -1
View File
@@ -19,7 +19,10 @@ export function mergeInjectedHeaders(
const lowerKey = key.toLowerCase(); const lowerKey = key.toLowerCase();
if (lowerKey === 'vary') { if (lowerKey === 'vary') {
handlerVary = handlerHeaders[key]; // A header value may be an array (D11). `mergeVary` splits on commas, so joining first keeps
// every token a handler listed instead of stringifying the array by accident.
const value = handlerHeaders[key];
handlerVary = Array.isArray(value) ? value.join(', ') : value;
continue; continue;
} }
@@ -40,3 +43,45 @@ export function mergeInjectedHeaders(
else if (handlerVary !== undefined) merged['vary'] = handlerVary; else if (handlerVary !== undefined) merged['vary'] = handlerVary;
return merged; return merged;
} }
/**
* Prepares merged headers for Node's `writeHead`, which writes one header line per array element
* for *any* header. That is right for `set-cookie`, the one header whose values cannot be
* comma-joined (an `Expires` date carries a comma), and wrong for every other: RFC 9110 §5.3 makes a
* list header's repeated lines equivalent to one comma-joined line, and joining keeps all four
* adapters sending the same bytes. So every other array is joined with `, ` here, before
* `writeHead`. Returns the input untouched when it holds no array, which is nearly every response.
*/
export function joinListHeaders<T extends Record<string, unknown>>(headers: T): T {
let out: Record<string, unknown> | undefined;
for (const key of Object.keys(headers)) {
const value = headers[key];
if (!Array.isArray(value) || key.toLowerCase() === 'set-cookie') continue;
out ??= { ...headers };
out[key] = value.join(', ');
}
return (out as T | undefined) ?? headers;
}
/**
* Builds a web `Headers` from merged headers. A plain record cannot be handed to `new Response`:
* the Fetch spec stringifies an array value to `a,b`, which for `set-cookie` is one broken cookie.
* `set-cookie` elements are appended one by one, so each reaches the client as its own line;
* every other array is joined with `, `, exactly as {@link joinListHeaders} does for Node.
*/
export function toWebHeaders(headers: Record<string, unknown>): Headers {
const out = new Headers();
for (const key of Object.keys(headers)) {
const value = headers[key];
if (value === undefined) continue;
if (!Array.isArray(value)) out.set(key, String(value));
else if (key.toLowerCase() === 'set-cookie') for (const cookie of value) out.append(key, String(cookie));
else out.set(key, value.join(', '));
}
return out;
}
+37 -4
View File
@@ -1,4 +1,4 @@
import type { RouteDef, MatchedRoute } from './types'; import type { RouteDef, RouteTable, MatchedRoute } from './types';
export type CompiledSegment = export type CompiledSegment =
| { kind: 'static'; value: string } | { kind: 'static'; value: string }
@@ -152,9 +152,9 @@ function segmentShape(segment: CompiledSegment): string {
* spy on the export cannot see it, so the counts are kept here; they let a test prove that misses * spy on the export cannot see it, so the counts are kept here; they let a test prove that misses
* after the index is built recompile nothing and rebuild nothing (FPRD-001 CARD-10). * after the index is built recompile nothing and rebuild nothing (FPRD-001 CARD-10).
*/ */
const seamCounts = { compilePattern: 0, indexBuilds: 0 }; const seamCounts = { compilePattern: 0, indexBuilds: 0, localTreeBuilds: 0 };
/** @internal Calls so far to `compilePattern` (cache hits included) and route-index builds. For tests. */ /** @internal Calls so far to `compilePattern` (cache hits included), route-index builds and local-tree builds. For tests. */
export const routerSeamCounts = (): Readonly<typeof seamCounts> => ({ ...seamCounts }); export const routerSeamCounts = (): Readonly<typeof seamCounts> => ({ ...seamCounts });
/** Compiles and validates one route pattern. Results are cached by source string. */ /** Compiles and validates one route pattern. Results are cached by source string. */
@@ -417,6 +417,11 @@ interface RouteIndex {
/** The routes a mesh teacup spliced in from its teapots. Identity-keyed, so a route is remote wherever it travels. */ /** The routes a mesh teacup spliced in from its teapots. Identity-keyed, so a route is remote wherever it travels. */
const remoteRouteDefs = new WeakSet<RouteDef>(); const remoteRouteDefs = new WeakSet<RouteDef>();
/** The array a {@link RouteTable} holds right now. Servers call it once per request. */
export function currentRoutes(table: RouteTable): RouteDef[] {
return typeof table === 'function' ? table() : table;
}
/** Marks a route as spliced in from a mesh teapot, so the index files it in the remote tree. */ /** Marks a route as spliced in from a mesh teapot, so the index files it in the remote tree. */
export function markRemoteRoute<T extends RouteDef>(def: T): T { export function markRemoteRoute<T extends RouteDef>(def: T): T {
remoteRouteDefs.add(def); remoteRouteDefs.add(def);
@@ -505,6 +510,34 @@ function buildTrees(entries: Array<{ def: RouteDef; order: number }>): Map<strin
return trees; return trees;
} }
/**
* The last local trees built, and the `(def, position)` entries they were built from.
*
* When mesh membership changes, the app publishes a new array whose local entries are the same
* objects at the same positions, with only the remote tail different (CARD-19, D15). Reusing the
* local trees then means a peer coming or going rebuilds the remote trees alone. Keyed by the
* first local def, so it is collected with the table that owns it.
*/
const localTreeCache = new WeakMap<
RouteDef,
{ entries: Array<{ def: RouteDef; order: number }>; trees: Map<string, MethodTree> }
>();
function sameEntries(a: Array<{ def: RouteDef; order: number }>, b: Array<{ def: RouteDef; order: number }>): boolean {
return a.length === b.length && a.every((entry, i) => entry.def === b[i].def && entry.order === b[i].order);
}
function localTrees(local: Array<{ def: RouteDef; order: number }>): Map<string, MethodTree> {
if (!local.length) return buildTrees(local);
const cached = localTreeCache.get(local[0].def);
if (cached && sameEntries(cached.entries, local)) return cached.trees;
seamCounts.localTreeBuilds++;
const trees = buildTrees(local);
localTreeCache.set(local[0].def, { entries: local, trees });
return trees;
}
function routeIndex(routes: RouteDef[]): RouteIndex { function routeIndex(routes: RouteDef[]): RouteIndex {
const cached = routeIndexCache.get(routes); const cached = routeIndexCache.get(routes);
if (cached?.size === routes.length) return cached; if (cached?.size === routes.length) return cached;
@@ -516,7 +549,7 @@ function routeIndex(routes: RouteDef[]): RouteIndex {
const index: RouteIndex = { const index: RouteIndex = {
size: routes.length, size: routes.length,
local: buildTrees(local), local: localTrees(local),
remote: remote.length ? buildTrees(remote) : undefined, remote: remote.length ? buildTrees(remote) : undefined,
methods: [...new Set(routes.map((route) => route.method))], methods: [...new Set(routes.map((route) => route.method))],
}; };
+8 -7
View File
@@ -6,7 +6,7 @@ import type { Bus } 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';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders, joinListHeaders } from './headers';
import { import {
handle, handle,
correlateRequest, correlateRequest,
@@ -17,13 +17,14 @@ import {
type Preflight, type Preflight,
} from './core'; } from './core';
import type { BodyFailure, BodyReader } from './body'; import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; import type { RouteTable, WsRouteDef, MeshControl, HttpOptions } from './types';
import { currentRoutes } from './router';
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 { answerProbe } from './health';
interface HandlerConfig { interface HandlerConfig {
routes: RouteDef[]; routes: RouteTable;
bus?: Bus; bus?: Bus;
opts?: HttpOptions; opts?: HttpOptions;
trustProxy: boolean; trustProxy: boolean;
@@ -36,14 +37,14 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest {
/** /**
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades. * Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
* @param routes HTTP route definitions. * @param routes HTTP route definitions, or a getter read once per request (a mesh teacup's table changes as peers come and go).
* @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency). * @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency).
* @param bus Optional event bus for stream lifecycle events. * @param bus Optional event bus for stream lifecycle events.
* @param meshControl Optional mesh gateway hook for a reserved upgrade path. * @param meshControl Optional mesh gateway hook for a reserved upgrade path.
* @param opts Limits, TLS, security, CORS, and body-parsing options. * @param opts Limits, TLS, security, CORS, and body-parsing options.
*/ */
export function createHttpServer( export function createHttpServer(
routes: RouteDef[], routes: RouteTable,
wsRoutes: WsRouteDef[] = [], wsRoutes: WsRouteDef[] = [],
bus?: Bus, bus?: Bus,
meshControl?: MeshControl, meshControl?: MeshControl,
@@ -161,7 +162,7 @@ function createRequestHandler(cfg: HandlerConfig) {
} }
result = await handle( result = await handle(
routes, currentRoutes(routes), // once per request, see buildFetch
opts, opts,
{ {
...correlation, ...correlation,
@@ -285,7 +286,7 @@ function patchResponseHeaders(res: http.ServerResponse, injected: Record<string,
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => { (res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined; const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
const merged = mergeInjectedHeaders(handlerHeaders, injected); const merged = joinListHeaders(mergeInjectedHeaders(handlerHeaders, injected));
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged); return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
}; };
} }
+7
View File
@@ -97,6 +97,13 @@ export interface RouteDef {
maxParts?: number; // per-route override of the server's multipart maxParts maxParts?: number; // per-route override of the server's multipart maxParts
} }
/**
* A route table: a fixed array, or a getter the server reads once per request. A mesh teacup passes
* a getter, because its remote routes change as teapots come and go (CARD-19); each change publishes
* a new array, so a request sees the whole old table or the whole new one.
*/
export type RouteTable = RouteDef[] | (() => RouteDef[]);
/** Result of matching a request path against a route: extracted params plus the matched definition. */ /** Result of matching a request path against a route: extracted params plus the matched definition. */
export interface MatchedRoute { export interface MatchedRoute {
params: Record<string, string>; params: Record<string, string>;
+12 -7
View File
@@ -10,13 +10,14 @@ import {
type HandleResult, type HandleResult,
type Preflight, type Preflight,
} from './core'; } from './core';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders, toWebHeaders } from './headers';
import { peerOf, trustedProxyClient } 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 { RouteTable, HttpOptions } from './types';
import { answerProbe } from './health'; import { answerProbe } from './health';
import { currentRoutes } from './router';
/** /**
* Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream * Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream
@@ -203,7 +204,7 @@ export function toBodyInit(body: string | Buffer): ResponseBody {
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */ /** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response { function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correlation = {}): Response {
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>; const headers = toWebHeaders(mergeInjectedHeaders(result.outcome.headers, result.injected));
if (result.outcome.kind === 'stream') { if (result.outcome.kind === 'stream') {
const body = asReadableStream( const body = asReadableStream(
@@ -236,7 +237,7 @@ function forwardedFor(headers: Record<string, string>, opts: HttpOptions | undef
* Routing, body parsing, limits and error rendering all live in the core; this file is the part * Routing, body parsing, limits and error rendering all live in the core; this file is the part
* that knows how to get bytes out of a `Request` and how to put them into a `Response`. * that knows how to get bytes out of a `Request` and how to put them into a `Response`.
*/ */
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) {
// Built once per server, not once per request — see `BodyReader`. // Built once per server, not once per request — see `BodyReader`.
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts); const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests); const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
@@ -273,20 +274,24 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
return new Response(JSON.stringify({ error: 'Service Unavailable' }), { return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
status: 503, status: 503,
headers: mergeInjectedHeaders( headers: toWebHeaders(
mergeInjectedHeaders(
{ {
'content-type': 'application/json', 'content-type': 'application/json',
'retry-after': '1', 'retry-after': '1',
}, },
injected, injected,
), ),
),
}); });
} }
acquired = gate.limited; acquired = gate.limited;
result = await handle( result = await handle(
routes, // Read once per request: a mesh teacup swaps its table when peers come and go, and one
// request must route and build `Allow` against the same table (CARD-19).
currentRoutes(routes),
opts, opts,
{ {
...correlation, ...correlation,
@@ -320,7 +325,7 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
if ('preflight' in result) { if ('preflight' in result) {
return new Response(null, { return new Response(null, {
status: 204, status: 204,
headers: mergeInjectedHeaders(result.preflight, injected), headers: toWebHeaders(mergeInjectedHeaders(result.preflight, injected)),
}); });
} }
+5 -1
View File
@@ -78,9 +78,13 @@ export { flow, Flow } from './flow';
export type { StepFn, CompiledFlow } from './flow'; export type { StepFn, CompiledFlow } from './flow';
// Parameter decorators // Parameter decorators
export { needs, ctx, param, query, body, headers, header, inbound, abort } from './params'; export { needs, ctx, param, query, body, headers, header, cookies, cookie, inbound, abort } from './params';
export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params'; export type { Query, Headers, Context, ArgSpec, ArgDecorator } from './params';
// Cookies
export { setCookie, parseCookies } from './cookies';
export type { CookieOptions } from './cookies';
// Observability // Observability
export { createDefaultLogger, logRequests, withConsoleFallback } from './logger'; export { createDefaultLogger, logRequests, withConsoleFallback } from './logger';
export type { Logger, LogLevel, LogFields } from './logger'; export type { Logger, LogLevel, LogFields } from './logger';
+135 -47
View File
@@ -2,7 +2,6 @@ import type { Bus } from '../bus';
import type { Logger } from '../logger'; import type { Logger } from '../logger';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { connectSocket, type SocketCtor } from '../http/ws-adapter'; import { connectSocket, type SocketCtor } from '../http/ws-adapter';
import { compilePattern } from '../http/router';
import type { WsSocket } from '../http/ws-core'; import type { WsSocket } from '../http/ws-core';
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol'; import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest, type RequestEnvelope, type Frame } from './protocol';
@@ -64,6 +63,8 @@ interface LinkState {
socket: WsSocket | undefined; socket: WsSocket | undefined;
closed: boolean; closed: boolean;
retry: ReturnType<typeof setTimeout> | undefined; retry: ReturnType<typeof setTimeout> | undefined;
/** When the scheduled reconnect attempt fires (epoch ms), for the `retry-after` a 503 carries. */
retryAt: number | undefined;
} }
/** One established connection: its socket, the manifest it announced, and its heartbeat. */ /** One established connection: its socket, the manifest it announced, and its heartbeat. */
@@ -81,10 +82,10 @@ const DEFAULT_MAX_DELAY_MS = 30_000;
* 503, not a bare Error: a dead upstream is not "this service broke", and the status is what * 503, not a bare Error: a dead upstream is not "this service broke", and the status is what
* tells a caller it may retry and an operator where to look. A bare Error renders as a 500. * tells a caller it may retry and an operator where to look. A bare Error renders as a 500.
*/ */
function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): void { function rejectAllPending(pending: Map<string, PendingEntry>, reason: string, headers?: Record<string, string>): void {
for (const [, entry] of pending) { for (const [, entry] of pending) {
clearTimeout(entry.timer); clearTimeout(entry.timer);
entry.reject(new HttpError(503, reason)); entry.reject(new HttpError(503, reason, undefined, headers));
} }
pending.clear(); pending.clear();
@@ -99,13 +100,14 @@ function sendRpc(
name: string, name: string,
ctx: RequestEnvelope, ctx: RequestEnvelope,
timeoutMs: number, timeoutMs: number,
downHeaders?: Record<string, string>,
): Promise<unknown> { ): Promise<unknown> {
// Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting // Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting
// would make every request to a downed teapot hang for the full timeout (30s by default) // would make every request to a downed teapot hang for the full timeout (30s by default)
// before failing anyway — the caller pays for a verdict already known. This is also the // before failing anyway — the caller pays for a verdict already known. This is also the
// window a reconnecting link sits in: down, and answering immediately. // window a reconnecting link sits in: down, and answering immediately.
if (!socket?.isOpen) { if (!socket?.isOpen) {
return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`)); return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`, undefined, downHeaders));
} }
return new Promise((resolveCall, rejectCall) => { return new Promise((resolveCall, rejectCall) => {
@@ -329,37 +331,109 @@ function stepKeys(manifest: Manifest): Set<string> {
} }
/** /**
* Route keys by method plus *effective shape*, the same comparison `spliceRemoteScopes` uses to * The steps the boot manifest had that a returning one does not.
* detect ambiguity — so `/:id` renamed to `/:name` is the same route and does not trip the refusal.
*/
function routeKeys(manifest: Manifest): Set<string> {
return new Set(manifest.routes.map((route) => `${route.method} ${compilePattern(route.pattern).shape}`));
}
/**
* What the boot manifest had that a returning one does not.
* *
* The graph was validated at boot against the first manifest and is already serving. A token that * The graph was validated at boot against the first manifest and is already serving. A step token
* vanished cannot be validated away after the fact, so a manifest missing anything this link * that vanished cannot be validated away after the fact, so a manifest missing one is refused
* contributed is refused rather than accepted — see `ManifestPolicy`. Extra exports are *not* * rather than accepted — see `ManifestPolicy`. Extra steps are ignored: the graph is fixed at boot
* missing and are ignored: the graph is fixed at boot and nothing new is spliced into it. * and nothing new is spliced into it.
*
* Routes are not compared. They are not part of the graph, so a returning teapot's routes replace
* the old ones instead (D15): a route it added is served, one it dropped is removed.
*/ */
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] { export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
const steps = stepKeys(returned); const steps = stepKeys(returned);
const routes = routeKeys(returned);
const missing: string[] = []; const missing: string[] = [];
for (const step of booted.steps) { for (const step of booted.steps) {
if (!steps.has(step)) missing.push(`step '${step}'`); if (!steps.has(step)) missing.push(`step '${step}'`);
} }
for (const route of booted.routes) { return missing;
if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) { }
missing.push(`route '${route.method} ${route.pattern}'`);
} /**
* `retry-after` for a 503 while the link is down and will try again: the seconds until the next
* attempt, at least 1. Nothing when it will not try again, so a client is not told to come back to
* a link that has given up.
*/
function retryAfter(state: LinkState, reconnects: boolean): Record<string, string> | undefined {
if (state.closed || !reconnects) return undefined;
const waitMs = state.retryAt === undefined ? 0 : state.retryAt - Date.now();
return { 'retry-after': String(Math.max(1, Math.ceil(waitMs / 1000))) };
}
/** A session dropped with reconnection off: the link is gone for good, if it was ever up. */
function dropWithoutReconnect(adopted: boolean, giveUp: () => void): void {
if (adopted) giveUp();
}
/** Stop a link for good and say so: a drop with reconnection off, or a permanent refusal (D15). */
function stopForGood(state: LinkState, onGone: (() => void) | undefined): void {
if (state.closed) return;
state.closed = true;
clearTimeout(state.retry);
state.retry = undefined;
onGone?.();
}
/**
* Whether a failed reconnect attempt was the teapot refusing this peer on purpose, in which case the
* link gives up. Retrying reaches the same answer forever, so the link stops and its routes go (D15),
* the same verdict boot gives a refusal.
*/
function refusedWhileReconnecting(
url: string,
error: unknown,
logger: Logger | undefined,
giveUp: () => void,
): boolean {
if (!isPermanentRefusal(error)) return false;
logger?.warn(`mesh: ${url} refused this peer while reconnecting (${(error as Error).message}) — giving up on it.`);
giveUp();
return true;
}
/**
* Hang up on a session whose manifest no longer backs the graph, and return the fingerprint now logged.
*
* Logged once per distinct manifest, not once per attempt: at the 30s ceiling this would otherwise be
* ~2,880 identical lines a day. A rollback can still fix it, which is why the link keeps retrying
* rather than giving up.
*/
function refuseSession(
session: Session,
missing: string[],
logged: string,
url: string,
logger: Logger | undefined,
): string {
session.heartbeat.stop();
session.socket.close();
const fingerprint = missing.join('|');
if (fingerprint !== logged) {
logger?.warn(
`mesh: refusing to reconnect to ${url} — its manifest no longer exports ${missing.join(', ')}, ` +
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
);
} }
return missing; return fingerprint;
}
/** A session was adopted. When it is a returning one: keep the boot steps, take its routes (D15), and tell the caller. */
function reconnected(
returning: boolean,
link: Link,
returned: Manifest,
onReconnect: ((manifest: Manifest) => void) | undefined,
): void {
if (!returning) return;
link.manifest = { steps: link.manifest.steps, routes: returned.routes };
onReconnect?.(link.manifest);
} }
/** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */ /** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */
@@ -394,19 +468,36 @@ export function connectLink(args: {
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */ /** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
onManifestChange?: ManifestPolicy; onManifestChange?: ManifestPolicy;
logger?: Logger; logger?: Logger;
/**
* Called each time a dropped link reconnects and its session is adopted, after `link.manifest`
* has taken the returning manifest's routes. Not called for the first connection: the caller
* has the link, and its manifest, when the returned promise resolves.
*/
onReconnect?: (manifest: Manifest) => void;
/**
* Called once when the link gives up for good: its session dropped with `reconnect: false`, or a
* reconnect attempt was refused permanently (a wrong secret, a protocol mismatch). Not called by
* `close()`, which is the application hanging up, not the teapot going away.
*/
onGone?: () => void;
}): Promise<Link> { }): Promise<Link> {
const timeoutMs = args.timeoutMs ?? 30_000; const timeoutMs = args.timeoutMs ?? 30_000;
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS; const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
const bounds = backoffBounds(args.reconnect); const bounds = backoffBounds(args.reconnect);
const pending = new Map<string, PendingEntry>(); const pending = new Map<string, PendingEntry>();
const state: LinkState = { socket: undefined, closed: false, retry: undefined }; const state: LinkState = { socket: undefined, closed: false, retry: undefined, retryAt: undefined };
let refusalLogged = ''; let refusalLogged = '';
let adopted = false; // a session was adopted at least once, so the link has something to lose
const downHeaders = (): Record<string, string> | undefined => retryAfter(state, bounds !== undefined);
const giveUp = (): void => stopForGood(state, args.onGone);
const link: Link = { const link: Link = {
// replaced with the real manifest before this object escapes; a reconnect never changes it, // replaced with the real manifest before this object escapes. A reconnect keeps the boot
// because the graph is fixed at boot and only the *boot* manifest describes what it holds. // manifest's steps, because the graph is fixed at boot, and takes the returning one's routes.
manifest: { steps: [], routes: [] }, manifest: { steps: [], routes: [] },
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs), rpc: (kind, name, ctx) =>
sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs, downHeaders()),
close: () => { close: () => {
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after // Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
// the application hung up would leave a process that cannot exit. // the application hung up would leave a process that cannot exit.
@@ -438,6 +529,8 @@ export function connectLink(args: {
// the teapot the moment it returns. // the teapot the moment it returns.
const delay = Math.round(capped / 2 + Math.random() * (capped / 2)); const delay = Math.round(capped / 2 + Math.random() * (capped / 2));
clearTimeout(state.retry);
state.retryAt = Date.now() + delay;
state.retry = setTimeout(() => void attemptReconnect(attempt + 1), delay); state.retry = setTimeout(() => void attemptReconnect(attempt + 1), delay);
state.retry.unref?.(); state.retry.unref?.();
}; };
@@ -446,8 +539,12 @@ export function connectLink(args: {
const endSession = (attempt: number): void => { const endSession = (attempt: number): void => {
state.socket = undefined; state.socket = undefined;
args.bus?.emit('mesh:disconnect', { name: args.url }); args.bus?.emit('mesh:disconnect', { name: args.url });
rejectAllPending(pending, `mesh link to ${args.url} is down`); // Scheduled before the rejection, so the 503s carry the real wait in `retry-after`.
scheduleRetry(attempt); scheduleRetry(attempt);
rejectAllPending(pending, `mesh link to ${args.url} is down`, downHeaders());
// With reconnection off, a link that was up and dropped is gone for good (D15). `adopted`
// keeps a first connect that never succeeded out of this: that link never escaped.
if (!bounds) dropWithoutReconnect(adopted, giveUp);
}; };
/** Adopt an established session, or refuse it when its manifest no longer backs the graph. */ /** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
@@ -455,27 +552,16 @@ export function connectLink(args: {
const missing = missingFromManifest(link.manifest, session.manifest); const missing = missingFromManifest(link.manifest, session.manifest);
if (missing.length > 0) { if (missing.length > 0) {
session.heartbeat.stop(); refusalLogged = refuseSession(session, missing, refusalLogged, args.url, args.logger);
session.socket.close();
// Logged once per distinct manifest, not once per attempt: at the 30s ceiling this would
// otherwise be ~2,880 identical lines a day. A rollback can still fix it, which is why the
// link keeps retrying rather than giving up.
const fingerprint = missing.join('|');
if (fingerprint !== refusalLogged) {
refusalLogged = fingerprint;
args.logger?.warn(
`mesh: refusing to reconnect to ${args.url} — its manifest no longer exports ${missing.join(', ')}, ` +
'which the graph was validated against at boot. Retrying in case this is a partial deploy.',
);
}
return false; return false;
} }
refusalLogged = ''; refusalLogged = '';
state.socket = session.socket; state.socket = session.socket;
const returning = adopted;
adopted = true;
args.bus?.emit('mesh:connect', { name: args.url }); args.bus?.emit('mesh:connect', { name: args.url });
reconnected(returning, link, session.manifest, args.onReconnect);
return true; return true;
}; };
@@ -492,10 +578,12 @@ export function connectLink(args: {
} }
if (!adopt(session)) scheduleRetry(attempt); if (!adopt(session)) scheduleRetry(attempt);
} catch { } catch (error) {
// openSession's own abort listener already scheduled the retry through `onEnd`; a rejection // A permanent refusal ends the link. Otherwise: openSession's own abort listener already
// that never opened a socket (a bad URL, DNS) needs one scheduled here instead. // scheduled the retry through `onEnd`; a rejection that never opened a socket (a bad URL,
if (!state.socket && !state.retry) scheduleRetry(attempt); // DNS) needs one scheduled here instead.
if (!refusedWhileReconnecting(args.url, error, args.logger, giveUp) && !state.socket && !state.retry)
scheduleRetry(attempt);
} }
}; };
+5 -1
View File
@@ -3,7 +3,11 @@ import 'reflect-metadata';
/** Any class constructor. Kept `any` because decorators must accept every target shape. */ /** Any class constructor. Kept `any` because decorators must accept every target shape. */
export type Ctor = new (...args: any[]) => any; export type Ctor = new (...args: any[]) => any;
/** Serializes a handler's return value into an HTTP response envelope. */ /** Serializes a handler's return value into an HTTP response envelope. */
export type TransformerFn = (value: unknown) => { status?: number; headers?: Record<string, string>; body: string }; export type TransformerFn = (value: unknown) => {
status?: number;
headers?: Record<string, string | string[]>;
body: string;
};
/** Metadata attached by `@Html`: optional file path and whether it is a template. */ /** Metadata attached by `@Html`: optional file path and whether it is a template. */
export interface HtmlMeta { export interface HtmlMeta {
+11 -4
View File
@@ -26,7 +26,7 @@ export interface OpenApiDoc {
type Parameter = { type Parameter = {
name: string; name: string;
in: 'path' | 'query' | 'header'; in: 'path' | 'query' | 'header' | 'cookie';
required: boolean; required: boolean;
schema: { type: 'string'; pattern?: string }; schema: { type: 'string'; pattern?: string };
}; };
@@ -57,13 +57,20 @@ function pathParams(pattern: string): Parameter[] {
}); });
} }
/** Query and header parameters declared by the handler's `@query` / `@headers` / `@header` argument decorators. */ /** Where each argument source sits in an OpenAPI parameter list; sources absent here are not parameters. */
const ARG_LOCATION: Partial<Record<ArgSpec['source'], Parameter['in']>> = {
query: 'query',
headers: 'header',
cookies: 'cookie',
};
/** Query, header and cookie parameters declared by `@query` / `@headers` / `@header` / `@cookies` / `@cookie`. */
function argParams(args: ArgSpec[]): Parameter[] { function argParams(args: ArgSpec[]): Parameter[] {
const params: Parameter[] = []; const params: Parameter[] = [];
for (const arg of args) { for (const arg of args) {
if (arg.source !== 'query' && arg.source !== 'headers') continue; const location = ARG_LOCATION[arg.source];
const location = arg.source === 'query' ? 'query' : 'header'; if (!location) continue;
const names = arg.keys ?? (arg.key ? [arg.key] : []); const names = arg.keys ?? (arg.key ? [arg.key] : []);
for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } }); for (const name of names) params.push({ name, in: location, required: false, schema: { type: 'string' } });
} }
+27 -3
View File
@@ -2,6 +2,7 @@ import 'reflect-metadata';
import type { Ctor } from './metadata'; import type { Ctor } from './metadata';
import { isStandardSchema, type StandardSchemaV1 } from './standard-schema'; import { isStandardSchema, type StandardSchemaV1 } from './standard-schema';
import { ValidationError } from './signals'; import { ValidationError } from './signals';
import { parseCookies } from './cookies';
/** Parsed URL query string as flat key/value pairs. */ /** Parsed URL query string as flat key/value pairs. */
export type Query = Record<string, string>; export type Query = Record<string, string>;
@@ -10,7 +11,7 @@ export type Headers = Record<string, string | string[] | undefined>;
/** Per-request bag that accumulates values produced by steps and providers. */ /** Per-request bag that accumulates values produced by steps and providers. */
export type Context = Record<string, unknown>; export type Context = Record<string, unknown>;
type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'inbound' | 'abort'; type ArgSource = 'ctx' | 'needs' | 'params' | 'query' | 'body' | 'headers' | 'cookies' | 'inbound' | 'abort';
/** Describes how a single handler parameter is sourced and (optionally) validated. */ /** Describes how a single handler parameter is sourced and (optionally) validated. */
export interface ArgSpec { export interface ArgSpec {
index: number; index: number;
@@ -71,6 +72,14 @@ export const body: ArgDecorator = envelope('body');
export const headers: ArgDecorator = envelope('headers'); export const headers: ArgDecorator = envelope('headers');
/** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */ /** Inject a single request header by name (singular alias of {@link headers}); accepts a schema to validate it. */
export const header: ArgDecorator = envelope('headers'); export const header: ArgDecorator = envelope('headers');
/**
* Inject request cookies, parsed from the `Cookie` header: no arg for the whole map (`{}` when the
* request has none), a key to pick one, an array to pick several. Accepts a schema to validate.
* First value wins for a repeated name, `%`-sequences are decoded, malformed pairs are skipped.
*/
export const cookies: ArgDecorator = envelope('cookies');
/** Inject a single request cookie by name (singular alias of {@link cookies}); `undefined` when absent. */
export const cookie: ArgDecorator = envelope('cookies');
/** Inject a value produced upstream by a step or provider, addressed by key. */ /** Inject a value produced upstream by a step or provider, addressed by key. */
export function needs(key: string): ParameterDecorator { export function needs(key: string): ParameterDecorator {
@@ -126,10 +135,11 @@ export async function resolveArgs(specs: ArgSpec[], context: Context): Promise<u
function resolveOne(spec: ArgSpec, context: Context): unknown { function resolveOne(spec: ArgSpec, context: Context): unknown {
if (spec.source === 'ctx') return context; if (spec.source === 'ctx') return context;
if (spec.source === 'needs') return context[spec.key as string]; // `cookies` is a seed token like `headers`, but parsed on demand rather than seeded on every request.
if (spec.source === 'needs') return spec.key === 'cookies' ? cookiesOf(context) : context[spec.key as string];
if (spec.source === 'inbound') return context.inbound; if (spec.source === 'inbound') return context.inbound;
if (spec.source === 'abort') return context.abort; if (spec.source === 'abort') return context.abort;
const bag = context[spec.source]; const bag = spec.source === 'cookies' ? cookiesOf(context) : context[spec.source];
if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is
const values = bag as Record<string, unknown>; const values = bag as Record<string, unknown>;
@@ -142,3 +152,17 @@ function resolveOne(spec: ArgSpec, context: Context): unknown {
if (spec.key !== undefined) return values[spec.key]; if (spec.key !== undefined) return values[spec.key];
return values; return values;
} }
/**
* The request's cookie map, parsed on first use and cached on the context, so a route that never
* declares a cookie argument never parses the header and one that declares several parses it once.
* Serves `@cookie`, `@cookies` and `@needs('cookies')` alike.
*/
function cookiesOf(context: Context): unknown {
if (context.cookies === undefined) {
const headers = context.headers as Headers | undefined;
context.cookies = parseCookies(headers?.cookie);
}
return context.cookies;
}
+2 -1
View File
@@ -14,7 +14,8 @@ export interface PipelineStep {
/** A fully materialized HTTP response produced by a transformer. */ /** A fully materialized HTTP response produced by a transformer. */
export interface ResponseShape { export interface ResponseShape {
status: number; status: number;
headers: Record<string, string>; /** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
headers: Record<string, string | string[]>;
body: string; body: string;
} }
/** A streaming response; the async iterable is written to the socket and bypasses the transformer. */ /** A streaming response; the async iterable is written to the socket and bypasses the transformer. */
+2 -2
View File
@@ -20,7 +20,7 @@ export interface HttpErrorLike {
status: number; status: number;
message: string; message: string;
body?: unknown; body?: unknown;
headers?: Record<string, string>; headers?: Record<string, string | string[]>;
} }
/** /**
@@ -35,7 +35,7 @@ export class HttpError extends Error {
readonly status: number, readonly status: number,
message?: string, message?: string,
readonly body?: unknown, readonly body?: unknown,
readonly headers?: Record<string, string>, readonly headers?: Record<string, string | string[]>,
) { ) {
super(message ?? `HTTP ${status}`); super(message ?? `HTTP ${status}`);
this.name = new.target.name; this.name = new.target.name;
+2 -1
View File
@@ -6,7 +6,8 @@ import type { Logger } from './logger';
/** A ready-to-send HTTP response. */ /** A ready-to-send HTTP response. */
export interface ErrorResponse { export interface ErrorResponse {
status: number; status: number;
headers: Record<string, string>; /** A value may be an array: `set-cookie` arrays are sent one line per element, others joined with `, `. */
headers: Record<string, string | string[]>;
body: string; body: string;
} }
+29
View File
@@ -0,0 +1,29 @@
// CARD-14 (#113) under the real Bun runtime: Set-Cookie arrays leave `Bun.serve` as separate
// lines, and @cookie reads the request header. Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { CookieModule, C1, C2 } from '../fixtures/cookie-app.ts';
test('T7/T8/T11 on Bun.serve: two Set-Cookie lines, other arrays joined, @cookie decoded', async () => {
const server = await serveBun(createApp({ modules: [CookieModule] }), { hostname: '127.0.0.1', port: 0 });
try {
const base = `http://127.0.0.1:${server.port}`;
const two = await fetch(`${base}/c/two`);
await two.arrayBuffer();
expect(two.headers.getSetCookie()).toEqual([C1, C2]);
expect(two.headers.get('x-custom')).toBe('a, b');
const error = await fetch(`${base}/c/error`);
await error.arrayBuffer();
expect(error.status).toBe(401);
expect(error.headers.getSetCookie()).toEqual([C1, C2]);
const one = await fetch(`${base}/c/one`, { headers: { cookie: 'a=1; a=2; b=%41' } });
expect(await one.json()).toEqual({ a: '1', b: 'A' });
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+88
View File
@@ -99,3 +99,91 @@ test('mesh on Bun: a teacup reconnects to a teapot that came back', async () =>
await teapot.stop(); await teapot.stop();
} }
}); });
// CARD-19 (#124, D15): remote routes follow teapot membership on Bun too.
@Route('/remote')
class PingCtl {
@Get('/ping', { export: true })
ping() {
return { from: 'teapot' };
}
}
@Module({ mountpoint: '/api', controllers: [PingCtl] })
class PingTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class BareTeacupModule {}
async function startPingTeapot(port: number) {
const app = createApp({ modules: [PingTeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = await serveBun(app, { port });
return {
stop: async () => {
server.stop(true);
await app.close();
},
};
}
/** Polls `GET path` until it answers `status`, or fails after `ms`. */
async function untilStatus(app: ReturnType<typeof createApp>, path: string, status: number, ms = 3000) {
const deadline = Date.now() + ms;
let last = 0;
while (Date.now() < deadline) {
const res = await app.fetch(new Request(`http://x${path}`));
await res.text();
last = res.status;
if (last === status) return;
await settle(25);
}
throw new Error(`${path} answered ${last}, expected ${status}`);
}
const pingTeacup = (port: number) =>
createApp({
modules: [BareTeacupModule],
experimental: true,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
bootTimeoutMs: 100,
heartbeatMs: 50,
timeoutMs: 2000,
},
});
test('mesh on Bun: a teapot absent at boot has its routes served once it connects (CARD-19 T1)', async () => {
const port = freePort();
const teacup = pingTeacup(port);
let teapot: Awaited<ReturnType<typeof startPingTeapot>> | undefined;
try {
expect((await teacup.fetch(new Request('http://x/api/remote/ping'))).status).toBe(404);
teapot = await startPingTeapot(port);
await untilStatus(teacup, '/api/remote/ping', 200);
} finally {
await teacup.close();
await teapot?.stop();
}
});
test('mesh on Bun: a reconnecting teapot keeps its routes with 503 + retry-after (CARD-19 T2)', async () => {
const port = freePort();
const teapot = await startPingTeapot(port);
const teacup = pingTeacup(port);
try {
await untilStatus(teacup, '/api/remote/ping', 200);
await teapot.stop();
await untilStatus(teacup, '/api/remote/ping', 503);
const down = await teacup.fetch(new Request('http://x/api/remote/ping'));
expect(down.status).toBe(503);
expect(Number(down.headers.get('retry-after'))).toBeGreaterThanOrEqual(1);
const options = await teacup.fetch(new Request('http://x/api/remote/ping', { method: 'OPTIONS' }));
expect(options.headers.get('allow')).toBe('GET, HEAD, OPTIONS');
} finally {
await teacup.close();
}
});
+36
View File
@@ -112,3 +112,39 @@ test('mesh on Bun: a remote step colliding with a local token fails the splice',
tServer.stop(true); tServer.stop(true);
} }
}); });
// CARD-20 (#125, D16): HEAD on a remote GET answers like HEAD on a local one.
@Route('/remote')
class RemoteHeadCtl {
@Get('/x', { export: true })
x() {
return { a: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteHeadCtl] })
class RemoteHeadTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class EmptyTeacupModule {}
test('mesh on Bun: HEAD on a remote GET answers 200 with the GET headers and no body', async () => {
const teapot = createApp({ modules: [RemoteHeadTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await serveBun(teapot, { port: 0 });
const teacup = createApp({
modules: [EmptyTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(tServer.port), secret: SECRET }], reconnect: false },
});
const cServer = await serveBun(teacup, { port: 0 });
try {
const res = await fetch(`http://127.0.0.1:${cServer.port}/api/remote/x`, { method: 'HEAD' });
expect(res.status).toBe(200);
expect(res.headers.get('content-type') ?? '').toContain('application/json');
expect(await res.text()).toBe('');
} finally {
await teacup.close();
cServer.stop(true);
tServer.stop(true);
}
});
+306
View File
@@ -0,0 +1,306 @@
// CARD-14 (#113): reading cookies with @cookie/@cookies, writing them with setCookie, and more than
// one Set-Cookie line per response on the Node adapter and app.fetch. Deno, Bun and edge repeat the
// two-line cases in test/deno/cookies.test.ts, test/bun/cookies.test.ts and test/edge/run.ts.
import 'reflect-metadata';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import WebSocket from 'ws';
import { describe, expect, it, afterAll } from 'vitest';
import {
createApp,
Route,
Get,
Ws,
Module,
Transformer,
HttpError,
needs,
cookie,
cookies,
setCookie,
parseCookies,
type TransformerFn,
} from '../src/index';
const C1 = setCookie('a', '1');
const C2 = setCookie('b', '2', { maxAge: 60 });
const twoCookies: TransformerFn = (value) => ({
status: 200,
headers: { 'content-type': 'application/json', 'set-cookie': [C1, C2] },
body: JSON.stringify(value),
});
@Route('/c')
class CookieCtl {
@Get('/one')
one(@cookie('a') a: string | undefined, @cookie('b') b: string | undefined) {
return { a: a ?? null, b: b ?? null };
}
@Get('/all')
all(@cookies() all: Record<string, string>) {
return { all, keys: Object.keys(all) };
}
@Get('/pick')
pick(@cookies(['d', 'e']) picked: Record<string, string>) {
return picked;
}
@Get('/needs')
viaNeeds(@needs('cookies') jar: Record<string, string>) {
return { sid: jar.sid ?? null };
}
@Get('/transformer')
@Transformer(twoCookies)
transformer() {
return { ok: true };
}
@Get('/error')
error() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': [C1, C2] });
}
@Get('/custom')
@Transformer((v) => ({ headers: { 'x-custom': ['a', 'b'], vary: ['Accept', 'Accept-Language'] }, body: String(v) }))
custom() {
return 'x';
}
@Get('/renderer')
renderer() {
throw new Error('render me');
}
@Ws('/ws')
ws(@cookie('a') a: string | undefined) {
return (async function* () {
yield `a=${a}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [CookieCtl] })
class M {}
const app = createApp({
modules: [M],
cors: { origins: ['http://ok.test'] },
onError: (error) =>
error instanceof Error && error.message === 'render me'
? { status: 418, headers: { 'content-type': 'text/plain', 'set-cookie': [C1, C2] }, body: 'teapot' }
: undefined,
});
let server: http.Server;
let port: number;
afterAll(() => server?.close());
async function boot(): Promise<void> {
if (server) return;
server = await app.listen(0);
port = (server.address() as AddressInfo).port;
}
/** A raw request, so repeated header lines are visible as they came off the socket. */
async function raw(
path: string,
headers: Record<string, string> = {},
): Promise<{ status: number; lines: [string, string][]; body: string }> {
await boot();
return new Promise((resolve, reject) => {
http
.get({ host: '127.0.0.1', port, path, headers }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => {
const lines: [string, string][] = [];
for (let i = 0; i < res.rawHeaders.length; i += 2)
lines.push([res.rawHeaders[i].toLowerCase(), res.rawHeaders[i + 1]]);
resolve({ status: res.statusCode!, lines, body });
});
})
.on('error', reject);
});
}
const valuesOf = (lines: [string, string][], name: string) => lines.filter(([k]) => k === name).map(([, v]) => v);
const fetchVia = (path: string, headers: Record<string, string> = {}) =>
app.fetch(new Request(`http://x${path}`, { headers }));
describe('parseCookies', () => {
it('T1: first value wins, %-sequences decode', () => {
expect(parseCookies('a=1; a=2; b=%41')).toEqual({ a: '1', b: 'A' });
});
it('T2: malformed pairs are skipped, an undecodable value is kept raw', () => {
expect({ ...parseCookies('=x; c; d=%ZZ; e=5') }).toEqual({ d: '%ZZ', e: '5' });
});
it('T3: no header is an empty map', () => {
expect({ ...parseCookies(undefined) }).toEqual({});
});
it('joins several cookie lines (HTTP/2, proxies) with "; "', () => {
expect({ ...parseCookies(['a=1', 'b=2; a=3']) }).toEqual({ a: '1', b: '2' });
});
it('treats __proto__ as an ordinary key, never a prototype write', () => {
const map = parseCookies('__proto__=x; constructor=y');
expect(map['__proto__']).toBe('x');
expect(map['constructor']).toBe('y');
expect(({} as any).x).toBeUndefined();
});
});
describe('setCookie', () => {
it('T4: documented defaults, Secure per D10', () => {
expect(setCookie('s', 'v')).toBe('s=v; Path=/; Secure; HttpOnly; SameSite=Lax');
});
it('serialises every option', () => {
const expires = new Date(Date.UTC(2030, 0, 1));
expect(
setCookie('s', 'v', {
maxAge: 10,
expires,
domain: 'example.com',
path: '/app',
httpOnly: false,
sameSite: 'none',
partitioned: true,
}),
).toBe(
's=v; Max-Age=10; Expires=Tue, 01 Jan 2030 00:00:00 GMT; Domain=example.com; Path=/app; Secure; SameSite=None; Partitioned',
);
expect(setCookie('s', 'v', { secure: false, sameSite: 'strict' })).toBe('s=v; Path=/; HttpOnly; SameSite=Strict');
});
it('T5: refuses header injection and bad names, naming the field', () => {
expect(() => setCookie('s', 'v\r\nX: y')).toThrow(/value for 's'/);
expect(() => setCookie('a b', 'v')).toThrow(/name "a b"/);
for (const bad of ['a;b', 'a,b', 'a b', 'a\tb', 'a\u0001b'])
expect(() => setCookie('s', bad), JSON.stringify(bad)).toThrow(/value/);
expect(() => setCookie('s', 'v', { path: '/\r\nX: y' })).toThrow(/path/);
expect(() => setCookie('s', 'v', { domain: 'a.com\nX' })).toThrow(/domain/);
expect(() => setCookie('s', 'v', { path: '/; Domain=evil' })).toThrow(/path/);
expect(() => setCookie('s', 'v', { maxAge: 1.5 })).toThrow(/maxAge/);
expect(() => setCookie('s', 'v', { expires: new Date('nope') })).toThrow(/expires/);
expect(() => setCookie('s', 'v', { sameSite: 'loose' as never })).toThrow(/sameSite/);
});
it('T6: sameSite none and partitioned both require secure', () => {
expect(() => setCookie('s', 'v', { sameSite: 'none', secure: false })).toThrow(/sameSite 'none'.*secure/);
expect(() => setCookie('s', 'v', { partitioned: true, secure: false })).toThrow(/partitioned.*secure/);
});
});
describe('@cookie / @cookies on a live Node server', () => {
it('T1: first wins and decodes', async () => {
const res = await raw('/c/one', { cookie: 'a=1; a=2; b=%41' });
expect(JSON.parse(res.body)).toEqual({ a: '1', b: 'A' });
});
it('T2: malformed pairs never 400', async () => {
const res = await raw('/c/all', { cookie: '=x; c; d=%ZZ; e=5' });
expect(res.status).toBe(200);
expect(JSON.parse(res.body).all).toEqual({ d: '%ZZ', e: '5' });
});
it('T3: no Cookie header', async () => {
expect(JSON.parse((await raw('/c/all')).body).all).toEqual({});
expect(JSON.parse((await raw('/c/one')).body)).toEqual({ a: null, b: null });
});
it('picks a key list', async () => {
expect(JSON.parse((await raw('/c/pick', { cookie: 'd=4; e=5; f=6' })).body)).toEqual({ d: '4', e: '5' });
});
it('@needs("cookies") resolves the same map', async () => {
expect(JSON.parse((await raw('/c/needs', { cookie: 'sid=abc' })).body)).toEqual({ sid: 'abc' });
});
it('resolves on a WebSocket route', async () => {
await boot();
const client = new WebSocket(`ws://127.0.0.1:${port}/c/ws`, { headers: { cookie: 'a=hello' } });
const message = await new Promise<string>((resolve, reject) => {
client.on('message', (data) => resolve(String(data)));
client.on('error', reject);
});
client.close();
expect(message).toBe('a=hello');
});
});
describe('several Set-Cookie lines', () => {
it('T7: custom @Transformer, Node: two lines', async () => {
const res = await raw('/c/transformer');
expect(valuesOf(res.lines, 'set-cookie')).toEqual([C1, C2]);
});
it('T7: custom @Transformer, app.fetch: two lines', async () => {
const res = await fetchVia('/c/transformer');
expect(res.headers.getSetCookie()).toEqual([C1, C2]);
});
it('T8: HttpError.headers and an onError renderer: two lines on both adapters', async () => {
for (const path of ['/c/error', '/c/renderer']) {
const res = await raw(path);
expect(valuesOf(res.lines, 'set-cookie'), path).toEqual([C1, C2]);
expect((await fetchVia(path)).headers.getSetCookie(), path).toEqual([C1, C2]);
}
});
it('T9: array kept, injected vary merged with a handler vary array', async () => {
const res = await raw('/c/custom', { origin: 'http://ok.test' });
const vary = valuesOf(res.lines, 'vary');
expect(vary).toHaveLength(1);
expect(vary[0].split(', ')).toEqual(['Accept', 'Accept-Language', 'Origin']);
const viaFetch = await fetchVia('/c/custom', { origin: 'http://ok.test' });
expect(viaFetch.headers.get('vary')).toBe('Accept, Accept-Language, Origin');
const cookieRes = await raw('/c/transformer', { origin: 'http://ok.test' });
expect(valuesOf(cookieRes.lines, 'set-cookie')).toEqual([C1, C2]);
expect(valuesOf(cookieRes.lines, 'vary')).toEqual(['Origin']);
});
it('T11: any other array header is one line joined with ", "', async () => {
const res = await raw('/c/custom');
expect(valuesOf(res.lines, 'x-custom')).toEqual(['a, b']);
expect((await fetchVia('/c/custom')).headers.get('x-custom')).toBe('a, b');
});
it('injected security headers stay authoritative over a handler array', async () => {
@Route('/s')
class Spoof {
@Get('/')
@Transformer(() => ({ headers: { 'x-content-type-options': ['sniff', 'me'] }, body: '' }))
get() {
return null;
}
}
@Module({ mountpoint: '/', controllers: [Spoof] })
class SM {}
const res = await createApp({ modules: [SM] }).fetch(new Request('http://x/s'));
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
});
describe('OpenAPI', () => {
it('lists a @cookie arg as an in: cookie parameter', () => {
const doc = app.openapi();
const params = (doc.paths['/c/one'].get as any).parameters;
expect(params).toEqual(
expect.arrayContaining([
{ name: 'a', in: 'cookie', required: false, schema: { type: 'string' } },
{ name: 'b', in: 'cookie', required: false, schema: { type: 'string' } },
]),
);
});
});
+29
View File
@@ -0,0 +1,29 @@
// CARD-14 (#113) under the real Deno runtime: Set-Cookie arrays leave `Deno.serve` as separate
// lines, and @cookie reads the request header. Run with: npm run test:deno
import 'npm:reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { CookieModule, C1, C2 } from '../fixtures/cookie-app.ts';
Deno.test('T7/T8/T11 on Deno.serve: two Set-Cookie lines, other arrays joined, @cookie decoded', async () => {
const server = await serveDeno(createApp({ modules: [CookieModule] }), { hostname: '127.0.0.1', port: 0, onListen: () => {} });
const port = (server as unknown as { addr: { port: number } }).addr.port;
try {
const two = await fetch(`http://127.0.0.1:${port}/c/two`);
await two.body?.cancel();
assertEquals(two.headers.getSetCookie(), [C1, C2]);
assertEquals(two.headers.get('x-custom'), 'a, b');
const error = await fetch(`http://127.0.0.1:${port}/c/error`);
await error.body?.cancel();
assertEquals(error.status, 401);
assertEquals(error.headers.getSetCookie(), [C1, C2]);
const one = await fetch(`http://127.0.0.1:${port}/c/one`, { headers: { cookie: 'a=1; a=2; b=%41' } });
assertEquals(await one.json(), { a: '1', b: 'A' });
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+93
View File
@@ -99,3 +99,96 @@ Deno.test('mesh on Deno: a teacup reconnects to a teapot that came back', async
await teapot.stop(); await teapot.stop();
} }
}); });
// CARD-19 (#124, D15): remote routes follow teapot membership on Deno too.
@Route('/remote')
class PingCtl {
@Get('/ping', { export: true })
ping() {
return { from: 'teapot' };
}
}
@Module({ mountpoint: '/api', controllers: [PingCtl] })
class PingTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class BareTeacupModule {}
async function startPingTeapot(port: number) {
const app = createApp({ modules: [PingTeapotModule], experimental: true, mesh: { secret: SECRET } });
const server = await serveDeno(app, { port });
await new Promise((r) => setTimeout(r, 50));
return {
stop: async () => {
await server.shutdown();
await app.close();
},
};
}
/** Polls `GET path` until it answers `status`, or fails after `ms`. */
async function untilStatus(app: ReturnType<typeof createApp>, path: string, status: number, ms = 3000) {
const deadline = Date.now() + ms;
let last = 0;
while (Date.now() < deadline) {
const res = await app.fetch(new Request(`http://x${path}`));
await res.body?.cancel();
last = res.status;
if (last === status) return;
await settle(25);
}
throw new Error(`${path} answered ${last}, expected ${status}`);
}
const pingTeacup = (port: number) =>
createApp({
modules: [BareTeacupModule],
experimental: true,
mesh: {
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
bootTimeoutMs: 100,
heartbeatMs: 50,
timeoutMs: 2000,
},
});
Deno.test('mesh on Deno: a teapot absent at boot has its routes served once it connects (CARD-19 T1)', async () => {
const port = freePort();
const teacup = pingTeacup(port);
let teapot: Awaited<ReturnType<typeof startPingTeapot>> | undefined;
try {
const before = await teacup.fetch(new Request('http://x/api/remote/ping'));
await before.body?.cancel();
assertEquals(before.status, 404);
teapot = await startPingTeapot(port);
await untilStatus(teacup, '/api/remote/ping', 200);
} finally {
await teacup.close();
await teapot?.stop();
}
});
Deno.test('mesh on Deno: a reconnecting teapot keeps its routes with 503 + retry-after (CARD-19 T2)', async () => {
const port = freePort();
const teapot = await startPingTeapot(port);
const teacup = pingTeacup(port);
try {
await untilStatus(teacup, '/api/remote/ping', 200);
await teapot.stop();
await untilStatus(teacup, '/api/remote/ping', 503);
const down = await teacup.fetch(new Request('http://x/api/remote/ping'));
await down.body?.cancel();
assertEquals(down.status, 503);
assertEquals(Number(down.headers.get('retry-after')) >= 1, true);
const options = await teacup.fetch(new Request('http://x/api/remote/ping', { method: 'OPTIONS' }));
assertEquals(options.headers.get('allow'), 'GET, HEAD, OPTIONS');
} finally {
await teacup.close();
}
});
+36
View File
@@ -142,3 +142,39 @@ Deno.test('mesh on Deno: a remote step colliding with a local token fails the sp
await t.server.shutdown(); await t.server.shutdown();
} }
}); });
// CARD-20 (#125, D16): HEAD on a remote GET answers like HEAD on a local one.
@Route('/remote')
class RemoteHeadCtl {
@Get('/x', { export: true })
x() {
return { a: 1 };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteHeadCtl] })
class RemoteHeadTeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class EmptyTeacupModule {}
Deno.test('mesh on Deno: HEAD on a remote GET answers 200 with the GET headers and no body', async () => {
const teapot = createApp({ modules: [RemoteHeadTeapotModule], experimental: true, mesh: { secret: SECRET } });
const t = await serve(teapot);
const teacup = createApp({
modules: [EmptyTeacupModule],
experimental: true,
mesh: { teapots: [{ url: controlUrl(t.port), secret: SECRET }], reconnect: false },
});
const c = await serve(teacup);
try {
const res = await fetch(`http://127.0.0.1:${c.port}/api/remote/x`, { method: 'HEAD' });
assertEquals(res.status, 200);
assertStringIncludes(res.headers.get('content-type') ?? '', 'application/json');
assertEquals(await res.text(), '');
} finally {
await teacup.close();
await c.server.shutdown();
await t.server.shutdown();
}
});
+13 -1
View File
@@ -66,6 +66,18 @@ async function main() {
assert.equal(httpRes.status, 200); assert.equal(httpRes.status, 200);
assert.deepEqual(await httpRes.json(), { ok: true }); assert.deepEqual(await httpRes.json(), { ok: true });
// CARD-14 (#113): a Set-Cookie array leaves workerd as one line per cookie; other arrays join.
const cookieRes = await mf.dispatchFetch('http://localhost/rt/cookies');
await cookieRes.arrayBuffer();
assert.deepEqual(cookieRes.headers.getSetCookie(), ['a=1; Path=/', 'b=2; Path=/']);
assert.equal(cookieRes.headers.get('x-custom'), 'a, b');
const cookieErr = await mf.dispatchFetch('http://localhost/rt/cookie-error');
await cookieErr.arrayBuffer();
assert.equal(cookieErr.status, 401);
assert.deepEqual(cookieErr.headers.getSetCookie(), ['a=1; Path=/', 'b=2; Path=/']);
const readCookie = await mf.dispatchFetch('http://localhost/rt/cookie', { headers: { cookie: 'a=1; b=%41' } });
assert.deepEqual(await readCookie.json(), { b: 'A' });
// Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a // Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a
// chunked upload's content-length, so the streamed case is enforced by the read count alone. // chunked upload's content-length, so the streamed case is enforced by the read count alone.
const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts
@@ -191,7 +203,7 @@ async function main() {
assert.equal(ready.headers.get('cache-control'), 'no-store'); assert.equal(ready.headers.get('cache-control'), 'no-store');
console.log( console.log(
'edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + health — PASS', 'edge (workerd via miniflare): HTTP 200 + cookies + 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();
+18 -1
View File
@@ -1,7 +1,7 @@
// Worker entry for the real workerd (Miniflare) integration test. // Worker entry for the real workerd (Miniflare) integration test.
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven // Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts). // identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
import { createApp, Route, Get, Post, Ws, body, ctx, Module } from '../../src/index'; import { createApp, Route, Get, Post, Ws, body, ctx, cookie, Module, Transformer, HttpError } from '../../src/index';
import { edgeHandler } from '../../src/edge'; import { edgeHandler } from '../../src/edge';
@Route('/rt') @Route('/rt')
@@ -11,6 +11,23 @@ class Rt {
return { ok: true }; return { ok: true };
} }
// CARD-14 (#113): two Set-Cookie lines from workerd, and @cookie on the request side.
@Get('/cookies')
@Transformer(() => ({ headers: { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'], 'x-custom': ['a', 'b'] }, body: '{}' }))
cookies() {
return null;
}
@Get('/cookie-error')
cookieError() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'] });
}
@Get('/cookie')
readCookie(@cookie('b') b: string | undefined) {
return { b: b ?? null };
}
// #105: the body limit, read from workerd's own request stream. Small, so every refused body still // #105: the body limit, read from workerd's own request stream. Small, so every refused body still
// fits in the socket buffer: a client that is mid-upload when the 413 lands can see ECONNRESET // fits in the socket buffer: a client that is mid-upload when the 413 lands can see ECONNRESET
// instead, which is the transport racing the answer rather than a different answer. // instead, which is the transport racing the answer rather than a different answer.
+28
View File
@@ -0,0 +1,28 @@
// CARD-14 (#113): one graph for the Deno and Bun cookie suites, so both prove the same thing the
// Node suite (test/cookies.test.ts) does — two cookies on one response arrive as two lines.
import { Route, Get, Module, Transformer, HttpError, cookie, setCookie } from '../../src/index';
export const C1 = setCookie('a', '1');
export const C2 = setCookie('b', '2', { maxAge: 60 });
@Route('/c')
class CookieCtl {
@Get('/one')
one(@cookie('a') a: string | undefined, @cookie('b') b: string | undefined) {
return { a: a ?? null, b: b ?? null };
}
@Get('/two')
@Transformer(() => ({ headers: { 'set-cookie': [C1, C2], 'x-custom': ['a', 'b'] }, body: '{}' }))
two() {
return null;
}
@Get('/error')
error() {
throw new HttpError(401, 'nope', undefined, { 'set-cookie': [C1, C2] });
}
}
@Module({ mountpoint: '/', controllers: [CookieCtl] })
export class CookieModule {}
+25 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { mergeInjectedHeaders } from '../src/http/headers'; import { mergeInjectedHeaders, joinListHeaders, toWebHeaders } from '../src/http/headers';
describe('mergeInjectedHeaders', () => { describe('mergeInjectedHeaders', () => {
it('makes injected keys authoritative regardless of handler casing', () => { it('makes injected keys authoritative regardless of handler casing', () => {
@@ -23,3 +23,27 @@ describe('mergeInjectedHeaders', () => {
expect(out['vary']).toBe('Accept'); expect(out['vary']).toBe('Accept');
}); });
}); });
describe('array header values (D11)', () => {
it('keeps a handler array intact and still merges vary', () => {
const cookies = ['a=1', 'b=2'];
const out = mergeInjectedHeaders({ 'set-cookie': cookies, Vary: ['Accept', 'Accept-Language'] }, { vary: 'Origin' });
expect(out['set-cookie']).toEqual(['a=1', 'b=2']);
expect(out['vary']).toBe('Accept, Accept-Language, Origin');
});
it('joinListHeaders joins every array but set-cookie, and returns the input when there is none', () => {
const plain = { a: '1' };
expect(joinListHeaders(plain)).toBe(plain);
expect(joinListHeaders({ 'Set-Cookie': ['a=1', 'b=2'], 'x-list': ['a', 'b'] })).toEqual({
'Set-Cookie': ['a=1', 'b=2'],
'x-list': 'a, b',
});
});
it('toWebHeaders appends one set-cookie per element', () => {
const h = toWebHeaders({ 'set-cookie': ['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2'], 'x-list': ['a', 'b'] });
expect(h.getSetCookie()).toEqual(['a=1; Expires=Tue, 01 Jan 2030 00:00:00 GMT', 'b=2']);
expect(h.get('x-list')).toBe('a, b');
});
});
+31 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; import { createApp, Step, Route, Get, Module, Transformer, needs } from '../../src/index';
const SECRET = 's3cr3t'; const SECRET = 's3cr3t';
@@ -281,3 +281,33 @@ describe('mesh skeleton integration', () => {
tServer.close(); tServer.close();
}); });
}); });
describe('mesh: Set-Cookie arrays (CARD-14, T10)', () => {
it('a remote route that returns two cookies reaches the teacup client as two lines', async () => {
@Route('/jar')
class JarCtl {
@Get('/two', { export: true })
@Transformer(() => ({ headers: { 'set-cookie': ['a=1; Path=/', 'b=2; Path=/'] }, body: '{}' }))
two() {
return null;
}
}
@Module({ mountpoint: '/api', controllers: [JarCtl] })
class JarTeapotModule {}
const teapot = createApp({ modules: [JarTeapotModule], experimental: true, mesh: { secret: SECRET } });
const tServer = await teapot.listen(0);
const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`;
const teacup = createApp({ modules: [PlainTeacupModule], experimental: true, mesh: { teapots: [{ url, secret: SECRET }] } });
const cServer = await teacup.listen(0);
try {
const res = await fetch(`http://127.0.0.1:${(cServer.address() as any).port}/api/jar/two`);
expect(res.status).toBe(200);
expect(res.headers.getSetCookie()).toEqual(['a=1; Path=/', 'b=2; Path=/']);
} finally {
tServer.close();
cServer.close();
}
});
});
+438
View File
@@ -0,0 +1,438 @@
/**
* CARD-19 (#124, D15): a teacup's remote routes follow which teapots are connected.
*
* Late teapot → its routes are added. Reconnecting → they stay and answer 503 with `retry-after`.
* Gone for good → they are removed (404, `Allow` without them). A returning manifest adds and drops
* routes. A late route that conflicts is refused and logged. Every change emits `mesh:routes`, and
* none rebuilds the local route tree.
*/
import 'reflect-metadata';
import http from 'http';
import net from 'net';
import type { AddressInfo } from 'net';
import { describe, it, expect, afterEach } from 'vitest';
import { WebSocketServer } from 'ws';
import { encode, decode, MESH_PROTOCOL_VERSION, type RouteEntry } from '../../src/mesh/protocol';
import { createApp, Route, Get, Module } from '../../src/index';
import { routerSeamCounts } from '../../src/http/router';
import type { App, MeshConfig } from '../../src/app/types';
import type { EventPayload } from '../../src/bus';
const SECRET = 'membership-secret';
@Route('/remote')
class PingCtl {
@Get('/ping', { export: true }) ping() {
return { from: 'teapot' };
}
}
@Module({ mountpoint: '/api', controllers: [PingCtl] })
class PingTeapot {}
@Route('/remote')
class PingExtraCtl {
@Get('/ping', { export: true }) ping() {
return { from: 'teapot v2' };
}
@Get('/extra', { export: true }) extra() {
return { extra: true };
}
}
@Module({ mountpoint: '/api', controllers: [PingExtraCtl] })
class PingExtraTeapot {}
@Route('/remote')
class ExtraOnlyCtl {
@Get('/extra', { export: true }) extra() {
return { extra: true };
}
}
@Module({ mountpoint: '/api', controllers: [ExtraOnlyCtl] })
class ExtraOnlyTeapot {}
@Route('/shape')
class ShapeIdCtl {
@Get('/:id', { export: true }) get() {
return { from: 'id' };
}
}
@Module({ mountpoint: '/api', controllers: [ShapeIdCtl] })
class ShapeIdTeapot {}
@Route('/')
class ShapeNameCtl {
@Get('/shape/:name', { export: true }) get() {
return { from: 'name' };
}
@Get('/other', { export: true }) other() {
return { from: 'other' };
}
}
@Module({ mountpoint: '/api', controllers: [ShapeNameCtl] })
class ShapeNameTeapot {}
@Route('/local')
class LocalCtl {
@Get('/ok') ok() {
return { from: 'teacup' };
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const FAST = { initialDelayMs: 20, maxDelayMs: 60 };
/** A port nothing listens on, that a teapot can take later. */
async function freePort(): Promise<number> {
const server = net.createServer();
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
await new Promise<void>((resolve) => server.close(() => resolve()));
return port;
}
const controlUrl = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
const open: App[] = [];
afterEach(async () => {
while (open.length) await open.pop()!.close();
});
async function teapotOn(port: number, module: new () => unknown): Promise<App> {
const teapot = createApp({ modules: [module], experimental: true, mesh: { secret: SECRET } });
await teapot.listen(port);
open.push(teapot);
return teapot;
}
async function stop(teapot: App): Promise<void> {
await teapot.close();
open.splice(open.indexOf(teapot), 1);
}
interface Teacup {
app: App;
warnings: string[];
events: EventPayload[];
/** Resolves on the next `name` event. */
next: (name: 'mesh:routes' | 'mesh:disconnect') => Promise<EventPayload>;
}
function teacup(ports: number[], mesh: Partial<MeshConfig> = {}, extra: { health?: boolean } = {}): Teacup {
const warnings: string[] = [];
const events: EventPayload[] = [];
const waiting = new Map<string, Array<(e: EventPayload) => void>>();
const app = createApp({
modules: [TeacupModule],
experimental: true,
...extra,
logger: { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error: (m: string) => warnings.push(m) },
mesh: {
teapots: ports.map((port) => ({ url: controlUrl(port), secret: SECRET })),
bootTimeoutMs: 100,
timeoutMs: 1000,
heartbeatMs: 1000,
reconnect: FAST,
...mesh,
},
});
for (const name of ['mesh:routes', 'mesh:disconnect'] as const) {
app.bus.on(name, (payload) => {
if (name === 'mesh:routes') events.push(payload);
const list = waiting.get(name) ?? [];
waiting.delete(name);
for (const resolve of list) resolve(payload);
});
}
open.unshift(app); // closed before the teapots
const next = (name: string) =>
new Promise<EventPayload>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`no ${name} within 5s`)), 5000);
waiting.set(name, [
...(waiting.get(name) ?? []),
(e) => {
clearTimeout(timer);
resolve(e);
},
]);
});
return { app, warnings, events, next };
}
const get = (app: App, path: string, method = 'GET') => app.fetch(new Request(`http://mesh.test${path}`, { method }));
function nodeGet(port: number, path: string) {
return new Promise<{ status: number; body: string }>((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, method: 'GET', path, agent: false }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => resolve({ status: res.statusCode ?? 0, body }));
});
req.on('error', reject);
req.end();
});
}
/**
* A teapot speaking the wire protocol directly, so its manifest can carry what a real teapot's own
* boot refuses — an older or foreign peer advertising a reserved path. Every RPC answers `answer`.
*/
async function rawTeapotOn(
port: number,
routes: RouteEntry[],
answer: unknown,
): Promise<{ close: () => Promise<void> }> {
const wss = new WebSocketServer({ port, host: '127.0.0.1' });
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 }));
else if (frame.type === 'ping') ws.send(encode({ type: 'pong' }));
else if (frame.type === 'rpc-req')
ws.send(
encode({
type: 'rpc-res',
id: frame.id,
ok: true,
result: { status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify(answer) },
}),
);
});
});
await new Promise((resolve) => wss.on('listening', resolve));
return {
close: () =>
new Promise<void>((done) => {
for (const client of wss.clients) client.terminate();
wss.close(() => done());
}),
};
}
describe('mesh: remote routes follow teapot membership (CARD-19, D15)', () => {
it('T1: a teapot absent at boot is served once it connects, on app.fetch and listen(), without rebuilding the local tree', async () => {
const port = await freePort();
const cup = teacup([port]);
const listenPort = ((await cup.app.listen(0)).address() as AddressInfo).port;
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
expect((await get(cup.app, '/api/local/ok')).status).toBe(200);
const before = routerSeamCounts();
const routed = cup.next('mesh:routes');
await teapotOn(port, PingTeapot);
expect(await routed).toEqual({
name: controlUrl(port),
url: controlUrl(port),
added: ['GET /api/remote/ping'],
removed: [],
});
const res = await get(cup.app, '/api/remote/ping');
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ from: 'teapot' });
expect(await nodeGet(listenPort, '/api/remote/ping')).toEqual({ status: 200, body: '{"from":"teapot"}' });
expect((await get(cup.app, '/api/local/ok')).status).toBe(200);
const after = routerSeamCounts();
expect(after.indexBuilds).toBeGreaterThan(before.indexBuilds); // the remote trees were rebuilt
expect(after.localTreeBuilds).toBe(before.localTreeBuilds); // the local ones were not
});
it('T2/T3: a reconnecting teapot keeps its routes with 503 + retry-after, then serves again', async () => {
const port = await freePort();
let teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
const dropped = cup.next('mesh:disconnect');
await stop(teapot);
await dropped;
const down = await get(cup.app, '/api/remote/ping');
expect(down.status).toBe(503);
expect(Number(down.headers.get('retry-after'))).toBeGreaterThanOrEqual(1);
expect((await get(cup.app, '/api/remote/ping', 'OPTIONS')).headers.get('allow')).toBe('GET, HEAD, OPTIONS');
expect((await get(cup.app, '/api/remote/ping', 'POST')).headers.get('allow')).toBe('GET, HEAD, OPTIONS');
teapot = await teapotOn(port, PingTeapot);
await expect.poll(async () => (await get(cup.app, '/api/remote/ping')).status, { timeout: 5000 }).toBe(200);
// Same routes back: nothing changed in the table, so no event.
expect(cup.events).toEqual([]);
});
it('T4: with reconnect: false a dropped teapot is gone — 404, Allow without its methods, local routes unaffected', async () => {
const port = await freePort();
const teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port], { reconnect: false });
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
const routed = cup.next('mesh:routes');
await stop(teapot);
expect(await routed).toMatchObject({ added: [], removed: ['GET /api/remote/ping'] });
const gone = await get(cup.app, '/api/remote/ping');
expect(gone.status).toBe(404);
expect(gone.headers.get('retry-after')).toBeNull();
const options = await get(cup.app, '/api/remote/ping', 'OPTIONS');
expect(options.status).toBe(404);
expect(options.headers.get('allow')).toBeNull();
expect((await get(cup.app, '/api/local/ok')).status).toBe(200);
expect(cup.warnings.some((w) => w.includes('gone for good'))).toBe(true);
});
it('T5: a teapot that returns with an extra route has it served', async () => {
const port = await freePort();
const teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/extra')).status).toBe(404);
const dropped = cup.next('mesh:disconnect');
await stop(teapot);
await dropped;
const routed = cup.next('mesh:routes');
await teapotOn(port, PingExtraTeapot);
expect(await routed).toMatchObject({ added: ['GET /api/remote/extra'], removed: [] });
expect((await get(cup.app, '/api/remote/extra')).status).toBe(200);
expect(await (await get(cup.app, '/api/remote/ping')).json()).toEqual({ from: 'teapot v2' });
});
it('T6: a teapot that returns without a route has it removed', async () => {
const port = await freePort();
const teapot = await teapotOn(port, PingTeapot);
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
const dropped = cup.next('mesh:disconnect');
await stop(teapot);
await dropped;
const routed = cup.next('mesh:routes');
await teapotOn(port, ExtraOnlyTeapot);
expect(await routed).toMatchObject({ added: ['GET /api/remote/extra'], removed: ['GET /api/remote/ping'] });
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
expect((await get(cup.app, '/api/remote/extra')).status).toBe(200);
});
it('T7: a late route ambiguous with another teapot’s is refused and logged; everything else serves', async () => {
const [portA, portB] = [await freePort(), await freePort()];
await teapotOn(portA, ShapeIdTeapot);
const cup = teacup([portA, portB]);
expect(await (await get(cup.app, '/api/shape/1')).json()).toEqual({ from: 'id' });
const routed = cup.next('mesh:routes');
await teapotOn(portB, ShapeNameTeapot);
expect(await routed).toMatchObject({ url: controlUrl(portB), added: ['GET /api/other'], removed: [] });
expect(await (await get(cup.app, '/api/shape/1')).json()).toEqual({ from: 'id' });
expect((await get(cup.app, '/api/other')).status).toBe(200);
expect(
cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /api/shape/:name'")),
).toBe(true);
});
it('T8: 1 000 requests across a late connect each see the old table or the new one', async () => {
const port = await freePort();
const cup = teacup([port]);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
const routed = cup.next('mesh:routes');
const starting = teapotOn(port, PingTeapot);
const statuses: number[] = [];
let changed = false;
void routed.then(() => (changed = true));
// 100 waves of 10 concurrent requests, spread across the moment the table changes. Ten at a time,
// not more: past 16 RPCs in flight on one link the teapot's control channel hits the WebSocket
// inbound-queue bound (#107) and drops the link. That is pre-existing and not about membership.
for (let wave = 0; wave < 100; wave++) {
const batch = await Promise.all(
Array.from({ length: 10 }, () => get(cup.app, '/api/remote/ping').then((res) => res.status)),
);
statuses.push(...batch);
if (!changed) await new Promise((resolve) => setTimeout(resolve, 2));
}
await starting;
await routed;
expect(statuses).toHaveLength(1000);
expect(statuses.every((status) => status === 404 || status === 200)).toBe(true);
// Both tables were actually seen, so the change happened while requests were flowing.
expect(statuses).toContain(404);
expect(statuses).toContain(200);
expect((await get(cup.app, '/api/remote/ping')).status).toBe(200);
});
it('with reconnect: false a teapot absent at boot is not retried (no backoff to retry with)', async () => {
const port = await freePort();
const cup = teacup([port], { reconnect: false });
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
await teapotOn(port, PingTeapot);
await new Promise((resolve) => setTimeout(resolve, 300));
expect((await get(cup.app, '/api/remote/ping')).status).toBe(404);
expect(cup.events).toEqual([]);
});
it('a late teapot advertising /__mesh__/control has that route refused; its other routes are served', async () => {
const port = await freePort();
const cup = teacup([port]);
expect((await get(cup.app, '/api/fake/ok')).status).toBe(404);
const routed = cup.next('mesh:routes');
const raw = await rawTeapotOn(
port,
[
{ method: 'GET', pattern: '/__mesh__/control' },
{ method: 'GET', pattern: '/api/fake/ok' },
],
{ from: 'raw teapot' },
);
try {
expect(await routed).toMatchObject({ added: ['GET /api/fake/ok'], removed: [] });
expect(await (await get(cup.app, '/api/fake/ok')).json()).toEqual({ from: 'raw teapot' });
expect(await (await get(cup.app, '/__mesh__/control')).text()).not.toContain('raw teapot');
expect(
cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /__mesh__/control'")),
).toBe(true);
} finally {
await cup.app.close();
open.splice(open.indexOf(cup.app), 1);
await raw.close();
}
});
it('with health on, a late teapot advertising /__ready__ has that route refused; its other routes are served', async () => {
const port = await freePort();
const cup = teacup([port], {}, { health: true });
expect((await get(cup.app, '/api/fake/ok')).status).toBe(404);
const routed = cup.next('mesh:routes');
const raw = await rawTeapotOn(
port,
[
{ method: 'GET', pattern: '/__ready__' },
{ method: 'GET', pattern: '/api/fake/ok' },
],
{ from: 'raw teapot' },
);
try {
expect(await routed).toMatchObject({ added: ['GET /api/fake/ok'], removed: [] });
expect((await get(cup.app, '/api/fake/ok')).status).toBe(200);
expect(await (await get(cup.app, '/__ready__')).text()).not.toContain('raw teapot');
expect(cup.warnings.some((w) => w.includes('not serving a route from') && w.includes("'GET /__ready__'"))).toBe(
true,
);
} finally {
await cup.app.close();
open.splice(open.indexOf(cup.app), 1);
await raw.close();
}
});
});
+5 -3
View File
@@ -143,7 +143,7 @@ describe('missingFromManifest', () => {
expect(missingFromManifest(booted, booted)).toEqual([]); expect(missingFromManifest(booted, booted)).toEqual([]);
}); });
it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => { it('accepts extra exports — extra steps are ignored, since the graph is fixed at boot', () => {
const wider: Manifest = { const wider: Manifest = {
steps: [...booted.steps, 'billing'], steps: [...booted.steps, 'billing'],
routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }], routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }],
@@ -161,8 +161,10 @@ describe('missingFromManifest', () => {
expect(missingFromManifest(booted, shrunk)).toEqual(["step 'auth'"]); expect(missingFromManifest(booted, shrunk)).toEqual(["step 'auth'"]);
}); });
it('reports a missing route by method and pattern', () => { // D15 (CARD-19): routes are not part of the graph, so a returning teapot's routes replace the old
// ones (a dropped route is removed from the remote table) instead of refusing the reconnect.
it('does not report a missing route — routes follow the returning manifest', () => {
const routeless: Manifest = { steps: booted.steps, routes: [] }; const routeless: Manifest = { steps: booted.steps, routes: [] };
expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]); expect(missingFromManifest(booted, routeless)).toEqual([]);
}); });
}); });
+152
View File
@@ -0,0 +1,152 @@
/**
* CARD-20 (#125, D16): `HEAD` on a remote buffered `GET` behaves like `HEAD` on a local one.
*
* The teacup resolves `HEAD` to the remote `GET` (implicit HEAD) and forwards it to the teapot as a
* `GET`, then drops the body. The teapot is unchanged, so an older teapot works too.
*/
import 'reflect-metadata';
import http from 'http';
import type { AddressInfo } from 'net';
import { describe, it, expect, afterEach } from 'vitest';
import { createApp, Route, Get, Head, Module, NotFound, ctx } from '../../src/index';
import type { App } from '../../src/app/types';
import type { Logger } from '../../src/logger';
const SECRET = 'head-secret';
const quiet: Logger = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} };
const seen: string[] = [];
@Route('/')
class RemoteCtl {
@Get('/x', { export: true }) x(@ctx() c: { req: { method: string } }) {
seen.push(`x ${c.req.method}`);
return { a: 1 };
}
@Get('/missing', { export: true }) missing() {
seen.push('missing');
throw new NotFound();
}
@Get('/boom', { export: true }) boom() {
seen.push('boom');
throw new Error('kaboom');
}
@Get('/both', { export: true }) bothGet() {
seen.push('both GET');
return { via: 'get' };
}
@Head('/both', { export: true }) bothHead(@ctx() c: { req: { method: string } }) {
seen.push(`both HEAD as ${c.req.method}`);
return { via: 'head' };
}
}
@Module({ mountpoint: '/api', controllers: [RemoteCtl] })
class TeapotModule {}
@Module({ mountpoint: '/api', controllers: [] })
class TeacupModule {}
const open: App[] = [];
afterEach(async () => {
while (open.length) await open.pop()!.close();
seen.length = 0;
});
async function mesh(): Promise<{ teacup: App; port: number }> {
const teapot = createApp({ modules: [TeapotModule], experimental: true, logger: quiet, mesh: { secret: SECRET } });
open.push(teapot);
const tPort = ((await teapot.listen(0)).address() as AddressInfo).port;
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
logger: quiet,
mesh: { teapots: [{ url: `ws://127.0.0.1:${tPort}/__mesh__/control`, secret: SECRET }], reconnect: false },
});
open.unshift(teacup); // closed first
const port = ((await teacup.listen(0)).address() as AddressInfo).port;
return { teacup, port };
}
function nodeRequest(port: number, method: string, path: string) {
return new Promise<{ status: number; headers: http.IncomingHttpHeaders; body: string }>((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, method, path, agent: false }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => (body += chunk));
res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body }));
});
req.on('error', reject);
req.end();
});
}
const fetchVia = (app: App, method: string, path: string) =>
app.fetch(new Request(`http://mesh.test${path}`, { method }));
describe('mesh: HEAD on a remote GET route (CARD-20, D16)', () => {
it('T1: HEAD via app.fetch answers 200 with the GET headers and no body', async () => {
const { teacup } = await mesh();
const get = await fetchVia(teacup, 'GET', '/api/x');
const head = await fetchVia(teacup, 'HEAD', '/api/x');
expect(head.status).toBe(200);
expect(head.headers.get('content-type')).toBe(get.headers.get('content-type'));
expect(head.headers.get('content-type')).toContain('application/json');
expect(await head.text()).toBe('');
expect(await get.json()).toEqual({ a: 1 });
});
it('T2: HEAD via the Node listener answers 200 with the GET headers and no body', async () => {
const { port } = await mesh();
const get = await nodeRequest(port, 'GET', '/api/x');
const head = await nodeRequest(port, 'HEAD', '/api/x');
expect(head.status).toBe(200);
expect(head.headers['content-type']).toBe(get.headers['content-type']);
expect(head.body).toBe('');
});
it('OPTIONS still advertises GET, HEAD, OPTIONS', async () => {
const { teacup, port } = await mesh();
expect((await fetchVia(teacup, 'OPTIONS', '/api/x')).headers.get('allow')).toBe('GET, HEAD, OPTIONS');
expect((await nodeRequest(port, 'OPTIONS', '/api/x')).headers.allow).toBe('GET, HEAD, OPTIONS');
});
it('T3: an explicit remote HEAD route keeps precedence over the implicit fallback', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/both');
expect(viaFetch.status).toBe(200);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/both');
expect(viaNode.status).toBe(200);
expect(viaNode.body).toBe('');
// The explicit HEAD handler ran, reached as HEAD — the GET handler never did.
expect(seen).toEqual(['both HEAD as HEAD', 'both HEAD as HEAD']);
});
it('T4: a remote GET that throws NotFound answers HEAD with 404 and no body', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/missing');
expect(viaFetch.status).toBe(404);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/missing');
expect(viaNode.status).toBe(404);
expect(viaNode.body).toBe('');
// The teapot handler ran: the 404 is the route's, not a missing HEAD plan on the teapot.
expect(seen).toEqual(['missing', 'missing']);
});
it('a remote GET that fails answers HEAD with 500 and no body', async () => {
const { teacup, port } = await mesh();
const viaFetch = await fetchVia(teacup, 'HEAD', '/api/boom');
expect(viaFetch.status).toBe(500);
expect(await viaFetch.text()).toBe('');
const viaNode = await nodeRequest(port, 'HEAD', '/api/boom');
expect(viaNode.status).toBe(500);
expect(viaNode.body).toBe('');
});
it('T5: one HEAD calls the teapot handler once, as a GET', async () => {
const { teacup } = await mesh();
await fetchVia(teacup, 'HEAD', '/api/x');
expect(seen).toEqual(['x GET']);
});
});
+1 -1
View File
@@ -31,7 +31,7 @@ Nothing can regenerate the baseline by accident:
| `frozen/matcher-*.json` | Captured matcher outputs: declaration ID, decoded params, `implicitHead`, ordered `Allow`, or the normalization error. The generated file also stores the seed, the generator rules and every generated input. | | `frozen/matcher-*.json` | Captured matcher outputs: declaration ID, decoded params, `implicitHead`, ordered `Allow`, or the normalization error. The generated file also stores the seed, the generator rules and every generated input. |
| `frozen/app-*.json` | Status, headers, `Allow` and body through `app.fetch` and through a Node socket, including HEAD body suppression. | | `frozen/app-*.json` | Status, headers, `Allow` and body through `app.fetch` and through a Node socket, including HEAD body suppression. |
| `frozen/ws-*.json` | WS upgrade selection through `app.upgrade` and the Node listener, plus HTTP requests at the WS paths. | | `frozen/ws-*.json` | WS upgrade selection through `app.upgrade` and the Node listener, plus HTTP requests at the WS paths. |
| `frozen/owner-*.json` | Owner additions needing a running app: cross-pattern `Allow` through both adapters, and the mesh HTTP route table across a peer's lifetime (it is built once at boot and never changes — see `owner.test.ts`). | | `frozen/owner-*.json` | Owner additions needing a running app: cross-pattern `Allow` through both adapters, and the mesh HTTP route table across a peer's lifetime (built once at boot at the pinned revision; since CARD-19 it follows teapot membership — see `owner.test.ts`). |
| `frozen/boot-*.json` | Boot-time rejections: pattern compilation, local ambiguity, mesh splicing. | | `frozen/boot-*.json` | Boot-time rejections: pattern compilation, local ambiguity, mesh splicing. |
| `frozen/golden-*.json` | `graph()`, `explain()`, `openapi({ title: 'Parity', version: '1' })`, and a mesh teacup before and after `ready()`. | | `frozen/golden-*.json` | `graph()`, `explain()`, `openapi({ title: 'Parity', version: '1' })`, and a mesh teacup before and after `ready()`. |
@@ -206,7 +206,7 @@
"adapter": "fetch", "adapter": "fetch",
"method": "HEAD", "method": "HEAD",
"path": "/api/x", "path": "/api/x",
"status": 404, "status": 200,
"headers": { "headers": {
"content-type": "application/json", "content-type": "application/json",
"referrer-policy": "no-referrer", "referrer-policy": "no-referrer",
@@ -472,7 +472,7 @@
"adapter": "node", "adapter": "node",
"method": "HEAD", "method": "HEAD",
"path": "/api/x", "path": "/api/x",
"status": 404, "status": 200,
"headers": { "headers": {
"content-type": "application/json", "content-type": "application/json",
"referrer-policy": "no-referrer", "referrer-policy": "no-referrer",
@@ -101,17 +101,17 @@
"phase": "B2 teapot up after boot", "phase": "B2 teapot up after boot",
"method": "GET", "method": "GET",
"path": "/api/remote/ping", "path": "/api/remote/ping",
"status": 404, "status": 200,
"allow": null, "allow": null,
"body": "{\"error\":\"Not Found\"}" "body": "{\"from\":\"teapot\"}"
}, },
{ {
"phase": "B2 teapot up after boot", "phase": "B2 teapot up after boot",
"method": "POST", "method": "POST",
"path": "/api/remote/ping", "path": "/api/remote/ping",
"status": 404, "status": 405,
"allow": null, "allow": "GET, HEAD, OPTIONS",
"body": "{\"error\":\"Not Found\"}" "body": "{\"error\":\"Method Not Allowed\"}"
}, },
{ {
"phase": "B2 teapot up after boot", "phase": "B2 teapot up after boot",
+24 -7
View File
@@ -88,15 +88,30 @@ const teacupFor = (port: number) =>
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }], teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
bootTimeoutMs: 300, bootTimeoutMs: 300,
timeoutMs: 500, timeoutMs: 500,
reconnect: false, // Reconnect on (CARD-19, D15): a dropped teapot is "reconnecting" and keeps its routes (A2),
// and one absent at boot is retried in the background (B). Captured at ed47836 with
// `reconnect: false`, when neither depended on it. Fast backoff keeps the test short.
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
}, },
}); });
/** Resolves on the teacup's next `mesh:routes` event: its remote table changed. */
const routesChanged = (app: App) =>
new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('no mesh:routes within 5s')), 5000);
const off = app.bus.on('mesh:routes', () => {
clearTimeout(timer);
off();
resolve();
});
});
/** /**
* Two lifetimes. A: the teapot is up at boot, then goes away. B: the teapot is absent at boot and * Two lifetimes. A: the teapot is up at boot, then goes away. B: the teapot is absent at boot and
* comes up afterwards. The current code builds the HTTP table once, at boot, and never changes it: * comes up afterwards. At ed47836 the HTTP table was built once, at boot, and never changed, so B2
* routes spliced at boot stay in the table after their peer leaves, and a peer that arrives late * answered 404. Since CARD-19 (D15, owner approval) the remote routes follow membership: a teapot
* is never spliced in. CARD-10 can reuse this to assert the index is not rebuilt per request. * that is reconnecting keeps its routes and answers 503 (A2), and a late one is spliced in when it
* connects (B2). CARD-10 can reuse this to assert the index is not rebuilt per request.
*/ */
async function meshLifetimes() { async function meshLifetimes() {
const results = []; const results = [];
@@ -118,7 +133,9 @@ async function meshLifetimes() {
const teapotB = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const teapotB = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
try { try {
results.push(...(await probe(teacupB, 'B1 teapot absent at boot'))); results.push(...(await probe(teacupB, 'B1 teapot absent at boot')));
const spliced = routesChanged(teacupB);
await teapotB.listen(portB); await teapotB.listen(portB);
await spliced;
results.push(...(await probe(teacupB, 'B2 teapot up after boot'))); results.push(...(await probe(teacupB, 'B2 teapot up after boot')));
} finally { } finally {
await teacupB.close(); await teacupB.close();
@@ -141,9 +158,9 @@ class RemoteMixCtl {
return { from: 'teapot', route: 'POST /api/v/:id' }; return { from: 'teapot', route: 'POST /api/v/:id' };
} }
// Remote only: remote routes are `buffer`, so the teacup's router resolves HEAD to it implicitly. // Remote only: remote routes are `buffer`, so the teacup's router resolves HEAD to it implicitly.
// Captured as observed at ed47836: the teacup forwards the request as HEAD, the teapot looks its // Captured at ed47836 as HEAD → 404 (the teacup forwarded HEAD, and the teapot has no HEAD plan).
// plan up by (pattern, method) and has none for HEAD, so HEAD answers 404 while OPTIONS still // CARD-20 (#125, D16) changed that deliberately, with owner approval: the teacup forwards the
// advertises HEAD. That is the mesh proxy's behaviour, not the matcher's; CARD-07 must keep it. // HEAD as a GET and drops the body, so HEAD now answers 200 like a local route.
@Get('/x', { export: true }) x() { @Get('/x', { export: true }) x() {
return { from: 'teapot', route: 'GET /api/x' }; return { from: 'teapot', route: 'GET /api/x' };
} }