Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f9e6b19d6 | ||
|
|
7be26fda5c | ||
|
|
e540752f1e | ||
|
|
e86051382d | ||
|
|
b8cb684a6b | ||
|
|
2c838c8753 | ||
|
|
cd4f47486f | ||
|
|
ffb5139cae | ||
|
|
46342a0aa2 | ||
|
|
1975a7c03f | ||
|
|
f2cb411eac | ||
|
|
1ccbf6cadf | ||
|
|
6ffbad9825 | ||
|
|
6672185ba2 | ||
|
|
198e62944f | ||
|
|
7d04b2d736 | ||
|
|
51608b0631 | ||
|
|
08310ac252 |
No files matched your search
@@ -12,6 +12,8 @@ jobs:
|
|||||||
publish-prod:
|
publish-prod:
|
||||||
if: ${{ github.server_url == 'https://github.com' }}
|
if: ${{ github.server_url == 'https://github.com' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
PKG: '@green-tea/core'
|
||||||
permissions:
|
permissions:
|
||||||
id-token: write # OIDC for Trusted Publishing (also enables provenance)
|
id-token: write # OIDC for Trusted Publishing (also enables provenance)
|
||||||
contents: read
|
contents: read
|
||||||
@@ -42,9 +44,17 @@ jobs:
|
|||||||
- run: deno publish --dry-run
|
- run: deno publish --dry-run
|
||||||
- name: Publish to npmjs
|
- name: Publish to npmjs
|
||||||
run: |
|
run: |
|
||||||
|
VERSION=$(node -p "require('./package.json').version")
|
||||||
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')")
|
TAG=$(node -e "const v=require('./package.json').version;const m=v.match(/-([a-z]+)/);console.log(m?m[1]:'latest')")
|
||||||
echo "dist-tag: $TAG"
|
echo "$VERSION under dist-tag: $TAG"
|
||||||
|
# Skip rather than fail when the version is already up. A step after this one can fail —
|
||||||
|
# the dist-tag move below does — and a re-run of the job has to be able to finish the
|
||||||
|
# remaining work instead of dying on a duplicate npm rejects anyway.
|
||||||
|
if npm view "$PKG@$VERSION" version >/dev/null 2>&1; then
|
||||||
|
echo "npm already has $VERSION"
|
||||||
|
else
|
||||||
npm publish --access public --tag "$TAG"
|
npm publish --access public --tag "$TAG"
|
||||||
|
fi
|
||||||
# JSR last, deliberately. npm allows an unpublish within 72 hours; JSR versions are immutable
|
# JSR last, deliberately. npm allows an unpublish within 72 hours; JSR versions are immutable
|
||||||
# and can never be replaced or removed. Ordered so a failure here costs a re-run, while a
|
# and can never be replaced or removed. Ordered so a failure here costs a re-run, while a
|
||||||
# failure *after* it would cost a version number permanently. Version and entry points come
|
# failure *after* it would cost a version number permanently. Version and entry points come
|
||||||
@@ -52,4 +62,46 @@ jobs:
|
|||||||
# dist-tags, so a prerelease simply publishes under its own version. Auth is the same OIDC
|
# dist-tags, so a prerelease simply publishes under its own version. Auth is the same OIDC
|
||||||
# id-token npm just used; the package is linked to this repository on jsr.io.
|
# id-token npm just used; the package is linked to this repository on jsr.io.
|
||||||
- name: Publish to JSR
|
- name: Publish to JSR
|
||||||
run: deno publish
|
run: |
|
||||||
|
VERSION=$(node -p "require('./package.json').version")
|
||||||
|
PKG=${PKG#@}
|
||||||
|
# 404 until the version exists — and it stays 404 for a package with no versions yet, which
|
||||||
|
# is the state this repository is actually in, so the guard must not read that as an error.
|
||||||
|
if curl -fsS -o /dev/null "https://api.jsr.io/scopes/${PKG%%/*}/packages/${PKG#*/}/versions/$VERSION"; then
|
||||||
|
echo "JSR already has $VERSION"
|
||||||
|
else
|
||||||
|
deno publish
|
||||||
|
fi
|
||||||
|
# `latest` is what a bare `npm install @green-tea/core` resolves to, and while there is no
|
||||||
|
# stable release the docs promise it is the newest beta. `npm publish --tag beta` sets exactly
|
||||||
|
# one tag, so `latest` has to be moved separately — and `npm dist-tag` cannot use Trusted
|
||||||
|
# Publishing, whose OIDC exchange lives only inside `npm publish`. So we run that same exchange
|
||||||
|
# by hand (id-token → short-lived npm token) rather than keep a long-lived token in a secret for
|
||||||
|
# one command. Last on purpose: both registries already have the version, and a dist-tag is the
|
||||||
|
# only thing here that can be redone. If this step fails, the release is out but `latest` is
|
||||||
|
# stale — recover with `npm dist-tag add @green-tea/core@<version> latest`.
|
||||||
|
- name: Point `latest` at this release while no stable exists
|
||||||
|
run: |
|
||||||
|
VERSION=$(node -p "require('./package.json').version")
|
||||||
|
case "$VERSION" in
|
||||||
|
*-*) ;;
|
||||||
|
*) echo "$VERSION is stable — npm publish already put it on latest"; exit 0 ;;
|
||||||
|
esac
|
||||||
|
# A stable release owns `latest` for good; a beta published afterwards must never drag it
|
||||||
|
# backwards, so the newest-beta rule applies only until the first stable exists.
|
||||||
|
# Read the list first so a failed lookup fails the step, rather than reading as "no stable
|
||||||
|
# exists" and moving `latest` backwards on the strength of a network error.
|
||||||
|
VERSIONS=$(npm view "$PKG" versions --json)
|
||||||
|
if node -e "process.exit([].concat(JSON.parse(process.argv[1])).some(v=>!v.includes('-'))?0:1)" "$VERSIONS"; then
|
||||||
|
echo "a stable version exists — leaving latest where it is"; exit 0
|
||||||
|
fi
|
||||||
|
URL=$(node -p "const u=new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL);u.searchParams.set('audience','npm:registry.npmjs.org');u.href")
|
||||||
|
ID_TOKEN=$(curl -fsS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$URL" \
|
||||||
|
| node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).value")
|
||||||
|
echo "::add-mask::$ID_TOKEN"
|
||||||
|
NODE_AUTH_TOKEN=$(curl -fsS -X POST -H "Authorization: Bearer $ID_TOKEN" \
|
||||||
|
"https://registry.npmjs.org/-/npm/v1/oidc/token/exchange/package/$(node -p "encodeURIComponent(process.env.PKG)")" \
|
||||||
|
| node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).token")
|
||||||
|
echo "::add-mask::$NODE_AUTH_TOKEN"
|
||||||
|
export NODE_AUTH_TOKEN
|
||||||
|
npm dist-tag add "$PKG@$VERSION" latest
|
||||||
@@ -66,6 +66,25 @@ The exception is a `hotfix/*`, which lands on `main` without passing through `de
|
|||||||
|
|
||||||
A conflict against unreleased `develop` work can never be delegated to an outside contributor — they cannot see the code they are conflicting with. Those are always the maintainer's to resolve.
|
A conflict against unreleased `develop` work can never be delegated to an outside contributor — they cannot see the code they are conflicting with. Those are always the maintainer's to resolve.
|
||||||
|
|
||||||
|
## Releasing
|
||||||
|
|
||||||
|
**Close the `CHANGELOG` section as the step immediately before the tag, never earlier.** A version
|
||||||
|
heading with a date is a claim that the release exists. Until the tag is pushed and the registries
|
||||||
|
have it, that claim is false — and a `[26.8.0-beta.1] - 2026-08-17` sitting above work that shipped
|
||||||
|
nowhere is worse than no heading at all, because the next reader believes it.
|
||||||
|
|
||||||
|
This is not hypothetical: the beta.1 section was written the day the version was *decided*, the
|
||||||
|
release slipped, and a day of further work landed underneath it as `[Unreleased]`. The file then said
|
||||||
|
two contradictory things — that beta.1 was released, and that everything in it was not.
|
||||||
|
|
||||||
|
So the order is: everything merged and promoted → **close the section with the release date** → tag →
|
||||||
|
registries. Until that step, work accumulates under `[Unreleased]`, however certain the next version
|
||||||
|
number feels.
|
||||||
|
|
||||||
|
Bumping `package.json` and `deno.json` ahead of the tag is fine and necessary — those say what the
|
||||||
|
*next* publish will be called, and the docs repo's `verify:release` compares the tag against them.
|
||||||
|
A version number is a plan; a changelog heading is a receipt.
|
||||||
|
|
||||||
## CI
|
## CI
|
||||||
|
|
||||||
The audit gate is scoped, not severity-filtered: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. A critical in the test runner reaches nobody; a high in `reflect-metadata` reaches everyone. It runs *after* the code gates, because an advisory published by a third party must never decide whether a contributor sees their own lint and typecheck output.
|
The audit gate is scoped, not severity-filtered: `npm audit --omit=dev` blocks, everything else is `continue-on-error`. A critical in the test runner reaches nobody; a high in `reflect-metadata` reaches everyone. It runs *after* the code gates, because an advisory published by a third party must never decide whether a contributor sees their own lint and typecheck output.
|
||||||
|
|||||||
+95
-7
@@ -8,15 +8,15 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
## [26.8.0-beta.1] - 2026-08-17
|
## [26.8.0-beta.1] - 2026-08-19
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- **Observability: a correlated lifecycle event stream and an injectable logger.** Every request is
|
- **Observability: a correlated lifecycle event stream and an injectable logger.** Every request is
|
||||||
given an id — an incoming `x-request-id` is adopted rather than replaced — and every event of that
|
given an id — an incoming `x-request-id` is adopted rather than replaced — and every event of that
|
||||||
request carries it, alongside the matched route *pattern* (never the concrete URL, which would give
|
request carries it, alongside the matched route _pattern_ (never the concrete URL, which would give
|
||||||
a metrics backend one label per distinct path). Each step reports its own duration. `createApp({
|
a metrics backend one label per distinct path). Each step reports its own duration. `createApp({
|
||||||
logger })` accepts any object with `debug`/`info`/`warn`/`error`; the default writes structured JSON,
|
logger })` accepts any object with `debug`/`info`/`warn`/`error`; the default writes structured JSON,
|
||||||
or a readable line on a TTY, decided once at boot. Nothing in core writes to `console`, enforced by a
|
or a readable line on a TTY, decided once at boot. Nothing in core writes to `console`, enforced by a
|
||||||
lint rule rather than by intention. `createApp({ logRequests: true })` logs one line per request, off
|
lint rule rather than by intention. `createApp({ logRequests: true })` logs one line per request, off
|
||||||
by default. New exports: `Logger`, `LogLevel`, `LogFields`, `createDefaultLogger`,
|
by default. New exports: `Logger`, `LogLevel`, `LogFields`, `createDefaultLogger`,
|
||||||
@@ -57,6 +57,37 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
|
- **A request that crosses the mesh keeps its identity.** The RPC envelope now carries the caller's
|
||||||
|
`requestId` and `traceId`, and a teapot adopts them rather than opening a new investigation — the
|
||||||
|
same rule an incoming `x-request-id` already got, applied at the process boundary where a trace
|
||||||
|
matters most. It also carries `url`, so a proxied handler sees the path its caller asked for.
|
||||||
|
|
||||||
|
Both fields are **optional on the wire and the protocol version does not move**: `decode` validates
|
||||||
|
only what a frame type requires and passes extras through, so a teapot on an older green-tea
|
||||||
|
ignores them and keeps answering. That is degraded, not broken. The rule for when the version
|
||||||
|
_does_ move is now written next to the constant, because "bump on any breaking change" never said
|
||||||
|
what counts as breaking.
|
||||||
|
|
||||||
|
The remote-route envelope is also built explicitly instead of cast from the internal request
|
||||||
|
object, which had been putting `ip` and `protocol` on the wire — fields the protocol never
|
||||||
|
declared and a teapot could have come to depend on.
|
||||||
|
|
||||||
|
- **Boot waits for a teapot that is merely slow, and still fails for one that is absent.**
|
||||||
|
`createApp({ mesh: { bootTimeoutMs } })` gives a teacup a grace period — default `timeoutMs`, so
|
||||||
|
30s — in which a teapot that has not finished starting is retried with backoff. When it passes,
|
||||||
|
the boot still fails, because a provider the graph depends on is not optional: booting without it
|
||||||
|
would only move the failure to the first request, where it becomes a caller's 503 instead of the
|
||||||
|
deploy's error. `bootTimeoutMs: 0` restores a single attempt.
|
||||||
|
|
||||||
|
**A refusal is not retried.** A wrong secret or a protocol-version mismatch is the teapot's
|
||||||
|
decision and will be the same decision in thirty seconds, so it fails immediately rather than
|
||||||
|
spending the whole budget to reach an identical error. The two are told apart by whether the
|
||||||
|
socket ever opened — a peer that accepted the connection and then hung up rejected us on purpose;
|
||||||
|
one that never accepted it may simply not be listening yet.
|
||||||
|
|
||||||
|
Every retry is logged _and_ emitted as the new `mesh:boot:retry` lifecycle event, so a slow boot
|
||||||
|
is visible to whatever collects events and not only to whoever is watching a terminal.
|
||||||
|
|
||||||
- **`.` and `..` in a request path are now resolved rather than 404'd.** `GET /public/../admin` reaches
|
- **`.` and `..` in a request path are now resolved rather than 404'd.** `GET /public/../admin` reaches
|
||||||
a route declared as `/admin`, and `%2e` counts as a dot, so the encoded spelling cannot reach a route
|
a route declared as `/admin`, and `%2e` counts as a dot, so the encoded spelling cannot reach a route
|
||||||
the plain one resolves away from. This is a **behaviour change on Node only**, and it exists to end a
|
the plain one resolves away from. This is a **behaviour change on Node only**, and it exists to end a
|
||||||
@@ -68,6 +99,58 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
- **A mesh export that carried behaviour arrived as `{}`, with HTTP 200 and no warning.** The wire is
|
||||||
|
JSON, so a value with methods — a connection pool, a client, a `Map` — lost everything but its
|
||||||
|
shape in transit. What reached the caller was an object: truthy, passing any `if (db)` check, and
|
||||||
|
missing every method, so the failure surfaced as `db.query is not a function` at a call site
|
||||||
|
arbitrarily far from the export that caused it.
|
||||||
|
|
||||||
|
A teapot now refuses to send one, on the side that still holds the real value, with a message
|
||||||
|
naming the token and what sat where: `mesh cannot transport 'db': result.db is a Pool instance`.
|
||||||
|
The check is an allowlist — primitives, plain objects, arrays — so `Date` is refused too, since it
|
||||||
|
would arrive as a string rather than the type the caller declared, which is the same silent
|
||||||
|
difference in a smaller costume. It is bounded by a scan budget, so a large legitimate payload is
|
||||||
|
never turned into an error by the cost of checking it.
|
||||||
|
|
||||||
|
**This is a constraint the documentation never stated:** a mesh export carries _data_, never
|
||||||
|
behaviour. Export what a handle produces, not the handle.
|
||||||
|
|
||||||
|
- **A mesh teacup now reconnects to a teapot that came back.** A dropped link used to stay dead for
|
||||||
|
the life of the process: every RPC answered 503 until the teacup was restarted, so deploying a
|
||||||
|
teapot forced a restart of every teacup that depended on it, and boot order became load-bearing.
|
||||||
|
Links now reconnect with exponential backoff and jitter (500ms doubling to 30s), tunable through
|
||||||
|
`mesh: { reconnect: { initialDelayMs, maxDelayMs } }` and disabled with `reconnect: false`.
|
||||||
|
`close()` is terminal — a link the application hung up on never reconnects, so `app.close()` cannot
|
||||||
|
leave a process that refuses to exit.
|
||||||
|
|
||||||
|
A returning teapot whose manifest no longer exports something the graph was validated against at
|
||||||
|
boot is **refused** rather than adopted, named by `mesh: { onManifestChange: 'refuse' }`, which is
|
||||||
|
the default and currently the only policy. The link keeps retrying, since a partial deploy may
|
||||||
|
still restore it, and logs the refusal once per distinct manifest rather than once per attempt.
|
||||||
|
Serving against a manifest that no longer backs the graph would surface as a 500 that looks like
|
||||||
|
application code. Extra exports in a returning manifest are ignored: the graph is fixed at boot.
|
||||||
|
|
||||||
|
This also closes the documented gap where **an app-scope export outlived its teapot with a stale
|
||||||
|
value** — a successful reconnect re-registers those bindings, so the next resolve re-runs the RPC.
|
||||||
|
|
||||||
|
Mesh remains **alpha** and behind `experimental: true`.
|
||||||
|
|
||||||
|
- **`mesh:rpc:error` reported the wire id where every other emitter reports a name.** A failing
|
||||||
|
remote call emitted `name: "0"` — the per-link request counter — so the teacup's event could not be
|
||||||
|
lined up with the teapot's event for the same failure. It now names the token or route.
|
||||||
|
|
||||||
|
- **A teapot now bounds its own handshake and caps the size of a control frame.** The teacup has
|
||||||
|
always timed out its side; the teapot had no equivalent, so an unauthenticated peer could hold a
|
||||||
|
socket open forever by simply never sending `hello`. And `decode` runs `JSON.parse` on
|
||||||
|
peer-controlled input _before_ authentication, with no ceiling below whatever the WebSocket layer
|
||||||
|
allowed — 100 MiB under the `ws` package's defaults. Frames above 4,000,000 characters are now
|
||||||
|
refused with close code 1009, sized above the 1 MB default body limit a legitimate RPC can carry.
|
||||||
|
|
||||||
|
- **A `ws://` teapot on a non-loopback host now warns at boot.** The shared secret travels verbatim
|
||||||
|
in the `hello` frame, so an unencrypted link puts it in front of anyone on the path. A warning
|
||||||
|
rather than a refusal, since a private network doing its own mutual TLS is a real deployment and
|
||||||
|
green-tea cannot tell the two apart.
|
||||||
|
|
||||||
- **Buffered response bodies are narrowed to what the host runtime's `Response` accepts.** A Node
|
- **Buffered response bodies are narrowed to what the host runtime's `Response` accepts.** A Node
|
||||||
`Buffer` is a `Uint8Array` at runtime but its declared backing store admits `SharedArrayBuffer`, which
|
`Buffer` is a `Uint8Array` at runtime but its declared backing store admits `SharedArrayBuffer`, which
|
||||||
`BodyInit` does not — so Deno's types rejected it. This was a real typing hole on the `app.fetch`
|
`BodyInit` does not — so Deno's types rejected it. This was a real typing hole on the `app.fetch`
|
||||||
@@ -80,6 +163,7 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
## [26.8.0-beta.0] - 2026-08-02
|
## [26.8.0-beta.0] - 2026-08-02
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- **Safe constrained route parameters:** patterns such as `:id(\d+)` match a complete decoded
|
- **Safe constrained route parameters:** patterns such as `:id(\d+)` match a complete decoded
|
||||||
segment. The parser accepts a deliberately small, bounded regex subset and rejects unsafe or
|
segment. The parser accepts a deliberately small, bounded regex subset and rejects unsafe or
|
||||||
malformed expressions at boot. Specificity is now static ▸ constrained param ▸ plain param ▸
|
malformed expressions at boot. Specificity is now static ▸ constrained param ▸ plain param ▸
|
||||||
@@ -99,14 +183,14 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
- **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno.
|
- **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno.
|
||||||
- **Cloudflare Workers / edge adapter** (`@green-tea/core/edge`): `edgeHandler(app)` runs HTTP + SSE + WebSocket on workerd, reusing the neutral `app.upgrade` / `WsSocket` capability. Requires the `nodejs_compat` compatibility flag. Green Tea now runs on Node, Deno, Bun, and the edge — with identical WebSocket, rooms, and channel behaviour on all four.
|
- **Cloudflare Workers / edge adapter** (`@green-tea/core/edge`): `edgeHandler(app)` runs HTTP + SSE + WebSocket on workerd, reusing the neutral `app.upgrade` / `WsSocket` capability. Requires the `nodejs_compat` compatibility flag. Green Tea now runs on Node, Deno, Bun, and the edge — with identical WebSocket, rooms, and channel behaviour on all four.
|
||||||
- **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`).
|
- **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`).
|
||||||
- **Mesh (alpha) runs on Node, Deno and Bun** — teapot *and* teacup, in any combination
|
- **Mesh (alpha) runs on Node, Deno and Bun** — teapot _and_ teacup, in any combination
|
||||||
(a Deno teapot can serve a Node teacup). It no longer needs `app.listen()`: the graph boots on
|
(a Deno teapot can serve a Node teacup). It no longer needs `app.listen()`: the graph boots on
|
||||||
first use, so `serveDeno`/`serveBun` work through `app.fetch`/`app.upgrade`. Edge is **not**
|
first use, so `serveDeno`/`serveBun` work through `app.fetch`/`app.upgrade`. Edge is **not**
|
||||||
supported — the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which
|
supported — the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which
|
||||||
`nodejs_compat` does not provide.
|
`nodejs_compat` does not provide.
|
||||||
- **`MESH_PROTOCOL_VERSION`**: the mesh wire is versioned. Peers exchange it in the `hello`/`manifest`
|
- **`MESH_PROTOCOL_VERSION`**: the mesh wire is versioned. Peers exchange it in the `hello`/`manifest`
|
||||||
frames and refuse a mismatch, naming both versions, instead of misreading each other's frames.
|
frames and refuse a mismatch, naming both versions, instead of misreading each other's frames.
|
||||||
The teapot checks the version *before* the secret — a skewed peer is not an auth failure.
|
The teapot checks the version _before_ the secret — a skewed peer is not an auth failure.
|
||||||
- **`HttpError` accepts `headers`**, so a custom error can carry its own response headers
|
- **`HttpError` accepts `headers`**, so a custom error can carry its own response headers
|
||||||
(`retry-after`, `etag`, …) without a special case in the error renderer.
|
(`retry-after`, `etag`, …) without a special case in the error renderer.
|
||||||
- **`app.ready(): Promise<void>`** — resolves the dependency graph and returns. On a mesh app it
|
- **`app.ready(): Promise<void>`** — resolves the dependency graph and returns. On a mesh app it
|
||||||
@@ -122,6 +206,7 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
|
pings — the platform `WebSocket` on Deno/Bun does not expose `ws.ping()`.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
- The Deno WebSocket adapter snapshots request and connection metadata before accepting an upgrade;
|
- The Deno WebSocket adapter snapshots request and connection metadata before accepting an upgrade;
|
||||||
Deno 2.9 invalidates that metadata once upgraded, which previously broke WebSocket and mesh boots.
|
Deno 2.9 invalidates that metadata once upgraded, which previously broke WebSocket and mesh boots.
|
||||||
- Repeated slashes and malformed path encoding now return `400` consistently across Node and Fetch
|
- Repeated slashes and malformed path encoding now return `400` consistently across Node and Fetch
|
||||||
@@ -157,6 +242,7 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
`request:step:leave`.
|
`request:step:leave`.
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
- Root, runtime-only, and website dependency audits are clean after supported package updates and
|
- Root, runtime-only, and website dependency audits are clean after supported package updates and
|
||||||
narrow pins for vulnerable transitives. CI audits root + website trees and builds the docs; the
|
narrow pins for vulnerable transitives. CI audits root + website trees and builds the docs; the
|
||||||
GitHub OIDC release workflow audits immediately before its publish gate.
|
GitHub OIDC release workflow audits immediately before its publish gate.
|
||||||
@@ -181,6 +267,7 @@ First public beta, published under the npm `beta` dist-tag. The API may still
|
|||||||
change before the stable release.
|
change before the stable release.
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- **Transport security** — native TLS termination (https/wss), CORS with a
|
- **Transport security** — native TLS termination (https/wss), CORS with a
|
||||||
guarded preflight and credentials-safe origins, secure-by-default response
|
guarded preflight and credentials-safe origins, secure-by-default response
|
||||||
headers (nosniff, X-Frame-Options, Referrer-Policy, HSTS-when-secure), and
|
headers (nosniff, X-Frame-Options, Referrer-Policy, HSTS-when-secure), and
|
||||||
@@ -200,7 +287,7 @@ change before the stable release.
|
|||||||
`405 Method Not Allowed` with an `Allow` header when a path exists under a
|
`405 Method Not Allowed` with an `Allow` header when a path exists under a
|
||||||
different method.
|
different method.
|
||||||
- **Argument decorators** — `@needs/@ctx/@param/@query/@body/@headers/@inbound/
|
- **Argument decorators** — `@needs/@ctx/@param/@query/@body/@headers/@inbound/
|
||||||
@abort`, plus `@header('name')` as a singular alias of `@headers`.
|
@abort`, plus `@header('name')` as a singular alias of `@headers`.
|
||||||
- **Streams** — SSE / ndjson / WebSocket duplex over a multicast
|
- **Streams** — SSE / ndjson / WebSocket duplex over a multicast
|
||||||
`AsyncIterable` channel, with backpressure and cleanup; `rooms` broadcast hubs.
|
`AsyncIterable` channel, with backpressure and cleanup; `rooms` broadcast hubs.
|
||||||
- **Graph introspection** — `app.explain(route)`, `app.graph()`,
|
- **Graph introspection** — `app.explain(route)`, `app.graph()`,
|
||||||
@@ -222,6 +309,7 @@ change before the stable release.
|
|||||||
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
- **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5,
|
||||||
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md).
|
||||||
|
|
||||||
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...main
|
[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...main
|
||||||
|
[26.8.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.0...v26.8.0-beta.1
|
||||||
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
|
[26.8.0-beta.0]: https://github.com/Expressive-Tea/green-tea/compare/v26.7.0-beta.0...v26.8.0-beta.0
|
||||||
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
|
[26.7.0-beta.0]: https://github.com/Expressive-Tea/green-tea/releases/tag/v26.7.0-beta.0
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
# A teapot that may be absent, declared per teapot
|
||||||
|
|
||||||
|
**Status:** planned, 2026-08-18
|
||||||
|
**Depends on:** the boot grace (`bootTimeoutMs`) and the reconnect/refuse work already merged
|
||||||
|
**Mesh stays alpha.**
|
||||||
|
|
||||||
|
## The decision
|
||||||
|
|
||||||
|
Strictness is a property of the *teapot*, not of the app. Diego: *"es mejor que los teapots definan
|
||||||
|
esa estrategia … 503 suena mejor para billing que para authorization."* A payment provider being
|
||||||
|
away is a degraded checkout; an authorization provider being away is not a degraded anything.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
mesh: {
|
||||||
|
teapots: [
|
||||||
|
{ url: billingUrl, secret, expects: ['billing'], onUnreachable: 'degrade' },
|
||||||
|
{ url: authUrl, secret }, // 'fail' — the default
|
||||||
|
],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Why `expects` is required for `'degrade'`, and not inferred
|
||||||
|
|
||||||
|
A teapot that never answered never sent a manifest, so **we do not know what it exported**. Without
|
||||||
|
that list there is nothing to put in the graph, `@needs('billing')` has no provider, and graph
|
||||||
|
validation fails the boot anyway — degrading would fail identically, just later.
|
||||||
|
|
||||||
|
The tempting shortcut is to placeholder *every unresolved token*. That must not happen: it would
|
||||||
|
turn a misspelled `needs` into a runtime 503 instead of a boot error, and destroy the property the
|
||||||
|
framework leads with. `expects` keeps the placeholder set exact, so a typo anywhere else still fails
|
||||||
|
loudly.
|
||||||
|
|
||||||
|
It also pushes the developer to state what a service depends on, which is the same discipline the
|
||||||
|
graph asks for everywhere else. `createApp` throws when `'degrade'` is set without a non-empty
|
||||||
|
`expects`, naming the teapot.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
**D1 — Placeholders are request-scope, never app-scope.** An app-scope placeholder resolves once at
|
||||||
|
boot, and throwing there is the very failure we are avoiding. A request-scope node runs per request
|
||||||
|
and throws `503`, naming the token and the teapot it belongs to.
|
||||||
|
|
||||||
|
**D2 — `expects` covers scope tokens only, not routes.** A degraded teapot's exported *routes*
|
||||||
|
simply do not exist locally, because a route needs a method and a pattern we were never told. A
|
||||||
|
request for one 404s, which is what an unregistered route does everywhere else. Documented, not
|
||||||
|
silent.
|
||||||
|
|
||||||
|
**D3 — Degraded tokens surface through `app.degraded()`**, the API that already reports optional
|
||||||
|
providers that failed to boot. A teapot that came up degraded is the same idea, not a parallel one,
|
||||||
|
and a consumer that already checks `degraded()` before reporting healthy gets this for free. Plus a
|
||||||
|
boot-time `logger.warn` and a `mesh:boot:degraded` event, for the same reason retries are both
|
||||||
|
logged and emitted.
|
||||||
|
|
||||||
|
**D4 — A degraded link keeps trying in the background.** Reconnection today only covers links that
|
||||||
|
handshook at least once; this one never did, so it needs its own attempt loop. Without it a degraded
|
||||||
|
teapot stays degraded until the process restarts, which is the bug this plan exists to avoid, moved.
|
||||||
|
|
||||||
|
**D5 — Adoption is the refuse rule again.** When a degraded teapot finally answers, its manifest
|
||||||
|
must contain everything in `expects`; if it does not, the connection is refused and the placeholders
|
||||||
|
stay. Same policy, same reason, and it reuses `missingFromManifest` with `expects` as the baseline
|
||||||
|
instead of a boot manifest.
|
||||||
|
|
||||||
|
**D6 — Swapping placeholders for real runners reuses the rebind seam** added for reconnection
|
||||||
|
(`invalidateRemoteBindings`). If that seam turns out not to fit, that is a signal the seam was
|
||||||
|
wrong, not a reason to write a second one.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
|
||||||
|
1. `expects` and `onUnreachable` on the teapot entry; `createApp` throws for `'degrade'` without
|
||||||
|
`expects`.
|
||||||
|
2. Placeholder step nodes per D1, registered when the boot grace runs out under `'degrade'`.
|
||||||
|
3. `degraded()` reporting per D3, plus the warn and the event.
|
||||||
|
4. Background attempt loop per D4, and adoption per D5/D6.
|
||||||
|
5. Tests, on all three server runtimes: boots degraded, the token 503s with a message naming it,
|
||||||
|
the teapot arrives late and the same request then succeeds, a manifest missing `expects` is
|
||||||
|
refused, and `'degrade'` without `expects` fails at `createApp`.
|
||||||
|
6. Docs: the mesh guide, `app.degraded()` in the reference, and the event table.
|
||||||
|
|
||||||
|
## Size
|
||||||
|
|
||||||
|
Comparable to the reconnection work — a background loop, a graph mutation and a runtime swap, on
|
||||||
|
three runtimes. Not a follow-up to squeeze into another change.
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
# Mesh reconnection, with a refusing manifest policy
|
||||||
|
|
||||||
|
**Status:** planned, 2026-08-18
|
||||||
|
**Scope:** `src/mesh/link.ts`, `src/app/index.ts`, `src/container.ts`, mesh tests, `guides/mesh.md`
|
||||||
|
**Mesh stays alpha.** It remains behind `experimental: true`. This closes the gap that makes mesh
|
||||||
|
unusable in production; it does not move the label, because the label is a statement about how much
|
||||||
|
we know, and we will know more once this runs somewhere real.
|
||||||
|
|
||||||
|
## The problem
|
||||||
|
|
||||||
|
There is no reconnection anywhere in `src/`. Combined with `spliceRemoteScopes` connecting teapots
|
||||||
|
serially and throwing on any failure (`src/app/index.ts:631`):
|
||||||
|
|
||||||
|
- a teapot down at boot → the teacup does not start;
|
||||||
|
- a teapot that dies afterwards → that link is dead for the life of the process, 503 on every RPC.
|
||||||
|
|
||||||
|
**Deploying a teapot therefore forces a restart of every teacup**, and boot order becomes
|
||||||
|
load-bearing. That is a worse operational property than any gap currently written in the docs.
|
||||||
|
|
||||||
|
## Vocabulary
|
||||||
|
|
||||||
|
**Reconnect** is returning to the *same* teapot when it comes back. **Failover** — switching to a
|
||||||
|
different teapot exporting the same thing — needs load balancing and stays out of scope. The two
|
||||||
|
words must not be used interchangeably in code, CHANGELOG or docs.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
**D1 — The `Link` object must survive the reconnect.** `buildRemote` captures `link.rpc` into the
|
||||||
|
registry's runners at boot, and the graph holds those closures. A reconnect that produced a new
|
||||||
|
`Link` would leave the graph pointing at the dead one. So `Link` owns a *swappable* socket, and
|
||||||
|
`connectLink` becomes "establish, then keep established".
|
||||||
|
|
||||||
|
**D2 — Reconnection covers links that handshook at least once.** A boot-time failure still fails
|
||||||
|
boot, unchanged. Boot retry is a separate piece of work; mixing them would blur "this app cannot be
|
||||||
|
configured" with "this dependency is temporarily away".
|
||||||
|
|
||||||
|
**D3 — Exponential backoff with jitter**, 500 ms initial, 30 s cap, timer `unref`'d — matching the
|
||||||
|
heartbeat, so reconnection never holds a process open on its own.
|
||||||
|
|
||||||
|
**D4 — The refuse rule.** On reconnect, the new manifest must still contain **everything this link
|
||||||
|
contributed at boot**: every scope token, with the same `app`/`request` lifetime, and every route by
|
||||||
|
method plus *effective shape* (the same comparison `spliceRemoteScopes` already uses for ambiguity,
|
||||||
|
so `/:id` and `/:name` are the same shape). Anything missing → refuse the connection.
|
||||||
|
|
||||||
|
Rationale: the graph was validated at boot against the old manifest and is already running. A token
|
||||||
|
that vanished cannot be validated away after the fact, and serving requests against a manifest that
|
||||||
|
no longer backs the graph is how you get a 500 that looks like application code.
|
||||||
|
|
||||||
|
**D5 — Extra exports in a returned manifest are ignored.** The graph is fixed at boot; new tokens are
|
||||||
|
not spliced in. Documented, not silent.
|
||||||
|
|
||||||
|
**D6 — A refused reconnect keeps retrying, but logs once per distinct manifest fingerprint.** A
|
||||||
|
rollback can restore the missing token, so giving up permanently would turn a recoverable state into
|
||||||
|
an outage. Logging every attempt at the 30 s cap would be 2,880 identical lines a day.
|
||||||
|
|
||||||
|
**D7 — The policy is a named strategy from day one**: `mesh: { onManifestChange: 'refuse' }`, and
|
||||||
|
`'refuse'` is the default. Reconciliation is a future version and lands as `'reconcile'`, additively.
|
||||||
|
If refusal shipped as implicit behaviour instead, adding reconciliation later would change the
|
||||||
|
meaning of an existing default across processes on separate deploy cadences — breaking, in the worst
|
||||||
|
place to be breaking.
|
||||||
|
|
||||||
|
**D8 — App-scope invalidation is lazy, and re-registers rather than clears.** A remote app-scope
|
||||||
|
provider is resolved once at boot and frozen into the container as `() => value`
|
||||||
|
(`src/app/index.ts:744`). Invalidation re-registers the binding with a factory that re-runs the RPC
|
||||||
|
and resets `resolved`, so the *next* resolve pays for it. Eager re-resolution would put a network
|
||||||
|
call on the reconnect path, where its failure has nowhere to go. This closes the documented
|
||||||
|
"app-scope export survives its teapot with a stale value" gap.
|
||||||
|
|
||||||
|
The invalidation is written as **"invalidate the remote bindings of link X"**, a named function, not
|
||||||
|
inline in the reconnect handler — that function is what reconciliation will reuse.
|
||||||
|
|
||||||
|
**D9 — `close()` is terminal.** `closeLinks` runs on shutdown; a link closed by the application must
|
||||||
|
never reconnect. This is the trap worth naming: without it, `app.close()` leaves a process that
|
||||||
|
cannot exit.
|
||||||
|
|
||||||
|
**D10 — RPCs during the down window are unchanged**: immediate 503 from the existing `isOpen` guard,
|
||||||
|
not a wait for `timeoutMs`.
|
||||||
|
|
||||||
|
## Tasks
|
||||||
|
|
||||||
|
1. **`Link` owns its socket.** Extract the handshake into something callable more than once; `Link`
|
||||||
|
holds `current: WsSocket | undefined`, and `rpc` reads it. `isOpen` false → the existing 503.
|
||||||
|
2. **Reconnect loop** on `abort`, unless closed by D9. Backoff per D3, `mesh:disconnect` on drop and
|
||||||
|
`mesh:connect` on success (existing events; no new bus contract in alpha).
|
||||||
|
3. **Manifest comparison.** Capture the contributed set at boot, compare per D4, reuse
|
||||||
|
`compilePattern(...).shape` for routes. Refusal logs the missing token or route by name.
|
||||||
|
4. **`invalidateRemoteBindings(link)`** per D8, called on successful reconnect.
|
||||||
|
5. **Config**: `mesh: { reconnect?: boolean | { initialDelayMs?, maxDelayMs? }, onManifestChange?: 'refuse' }`.
|
||||||
|
Reconnect defaults **on**. Validate at boot like the other mesh options.
|
||||||
|
6. **Tests.** Reconnect after the teapot returns; refuse when a token disappears, with the message
|
||||||
|
naming it; `close()` stops reconnection (assert no timer keeps the process alive); an app-scope
|
||||||
|
value re-resolves after reconnect; a heartbeat-triggered close reconnects. Deno and Bun get the
|
||||||
|
reconnect case — the platform `WebSocket` is a different client implementation, which is exactly
|
||||||
|
where a swappable socket can break.
|
||||||
|
7. **Docs.** `guides/mesh.md`: mesh stays alpha, the gap list loses the stale-value entry and gains
|
||||||
|
"extra exports are not spliced". CHANGELOG under `Fixed`, because from the operator's side this is
|
||||||
|
a defect, not a feature.
|
||||||
|
|
||||||
|
## Not in this plan
|
||||||
|
|
||||||
|
Boot retry, correlation across the mesh (and the `mesh:rpc:error` name/id bug), the teapot handshake
|
||||||
|
deadline, the frame size cap, `req.url` in the envelope. All queued, none blocked by this.
|
||||||
+147
-13
@@ -29,7 +29,7 @@ import {
|
|||||||
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views';
|
import { buildHtmlTransformer, buildStaticResolver, type ViewsContext } from '../views';
|
||||||
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
|
import { getArgs, getHandlerNeeds, resolveArgs } from '../params';
|
||||||
import { buildOpenApi, type OpenApiInfo } from '../openapi';
|
import { buildOpenApi, type OpenApiInfo } from '../openapi';
|
||||||
import { connectLink, 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 } from '../mesh/teacup';
|
||||||
@@ -217,7 +217,7 @@ export function createApp(opts: {
|
|||||||
// can only be built here, after finalize(), and never at construction time.
|
// can only be built here, after finalize(), and never at construction time.
|
||||||
const prepareGraph = async (): Promise<void> => {
|
const prepareGraph = async (): Promise<void> => {
|
||||||
if (opts.mesh && !booted) {
|
if (opts.mesh && !booted) {
|
||||||
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger);
|
const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, container);
|
||||||
remoteRoutes = spliced.remoteRoutes;
|
remoteRoutes = spliced.remoteRoutes;
|
||||||
meshLinks.push(...spliced.meshLinks);
|
meshLinks.push(...spliced.meshLinks);
|
||||||
finalize();
|
finalize();
|
||||||
@@ -615,12 +615,102 @@ function assertNeedsSatisfiable(routePlans: RoutePlan[], providerNodes: GraphNod
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Keep trying to reach a teapot until `bootTimeoutMs` passes, then give up and fail the boot.
|
||||||
|
*
|
||||||
|
* The grace exists because "the container is thirty seconds behind" and "the teapot does not
|
||||||
|
* exist" look identical for the first thirty seconds, and only one of them should stop a deploy.
|
||||||
|
* When the deadline passes it still throws: a provider the graph depends on is not optional, and
|
||||||
|
* booting without it would only move the failure to the first request, where it becomes a caller's
|
||||||
|
* 503 instead of the deploy's error.
|
||||||
|
*
|
||||||
|
* Each failed attempt is both logged and emitted as `mesh:boot:retry` — logged so an operator
|
||||||
|
* watching a deploy sees why it is taking so long, emitted so the wait is visible to whatever
|
||||||
|
* collects lifecycle events rather than only to whoever is reading a terminal.
|
||||||
|
*/
|
||||||
|
async function connectUntilDeadline(
|
||||||
|
mesh: MeshConfig,
|
||||||
|
bus: Bus,
|
||||||
|
logger: Logger,
|
||||||
|
attempt: () => Promise<Link>,
|
||||||
|
): Promise<Link> {
|
||||||
|
const budgetMs = mesh.bootTimeoutMs ?? mesh.timeoutMs ?? 30_000;
|
||||||
|
const deadline = Date.now() + budgetMs;
|
||||||
|
let delay = 500;
|
||||||
|
let attempts = 0;
|
||||||
|
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
return await attempt();
|
||||||
|
} catch (error) {
|
||||||
|
attempts += 1;
|
||||||
|
const remaining = deadline - Date.now();
|
||||||
|
|
||||||
|
// A refusal is the teapot's decision, not the network's, and it will be the same decision in
|
||||||
|
// thirty seconds. Retrying a wrong secret only spends the deploy's patience to reach the
|
||||||
|
// identical error, so it fails now.
|
||||||
|
if (isPermanentRefusal(error)) {
|
||||||
|
logger.error(`mesh: the teapot refused this peer, which retrying cannot fix — ${(error as Error).message}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rethrown as-is rather than wrapped: connectLink already says whether this was a refused
|
||||||
|
// handshake, a version mismatch or a timeout, and each sends you somewhere different.
|
||||||
|
if (remaining <= 0) {
|
||||||
|
logger.error(`mesh: giving up after ${attempts} attempt(s) over ${budgetMs}ms — ${(error as Error).message}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
bus.emit('mesh:boot:retry', { name: `attempt ${attempts}`, error });
|
||||||
|
logger.warn(
|
||||||
|
`mesh: teapot unreachable (${(error as Error).message}) — retrying, ${remaining}ms of boot budget left`,
|
||||||
|
);
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, Math.min(delay, Math.max(0, remaining))));
|
||||||
|
delay = Math.min(delay * 2, 5_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Warn when a teapot's shared secret would cross a network in cleartext.
|
||||||
|
*
|
||||||
|
* The `hello` frame carries the secret verbatim, so `ws://` to anywhere but this machine puts it on
|
||||||
|
* the wire for anyone in the path to read. Loopback is exempt because there is no path.
|
||||||
|
*
|
||||||
|
* A warning rather than a refusal: a private network behind a service mesh that already does mutual
|
||||||
|
* TLS is a legitimate deployment, and green-tea cannot tell it apart from an exposed one.
|
||||||
|
*/
|
||||||
|
function warnIfCleartext(url: string, logger: Logger): void {
|
||||||
|
if (!url.startsWith('ws://')) return;
|
||||||
|
const host = url.slice('ws://'.length).split('/')[0].split(':')[0];
|
||||||
|
if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]') return;
|
||||||
|
|
||||||
|
logger.warn(
|
||||||
|
`mesh: ${url} is not encrypted, and the shared secret is sent in the handshake — ` +
|
||||||
|
'use wss:// unless the link already runs inside an encrypted network.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Re-register a link's app-scope bindings after it reconnects, so their next resolve re-runs the RPC.
|
||||||
|
*
|
||||||
|
* Named and separate rather than inlined in the reconnect handler: this is the seam a future
|
||||||
|
* `onManifestChange: 'reconcile'` reuses, and burying it would mean writing it twice.
|
||||||
|
*
|
||||||
|
* Lazy on purpose — the RPC runs on the next resolve, not here. Re-resolving eagerly would put a
|
||||||
|
* network call on the reconnect path, where a failure has nowhere to go but a swallowed rejection.
|
||||||
|
*/
|
||||||
|
function invalidateRemoteBindings(rebind: Array<() => void>): void {
|
||||||
|
for (const bind of rebind) bind();
|
||||||
|
}
|
||||||
|
|
||||||
/** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */
|
/** Connects the configured teapots, splices their remote providers/steps into the registry, and returns their routes. */
|
||||||
async function spliceRemoteScopes(
|
async function spliceRemoteScopes(
|
||||||
mesh: MeshConfig,
|
mesh: MeshConfig,
|
||||||
bus: Bus,
|
bus: Bus,
|
||||||
registry: Registry,
|
registry: Registry,
|
||||||
logger: Logger,
|
logger: Logger,
|
||||||
|
container: Container,
|
||||||
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[] }> {
|
||||||
const remoteRoutes: RouteDef[] = [];
|
const remoteRoutes: RouteDef[] = [];
|
||||||
const meshLinks: Link[] = [];
|
const meshLinks: Link[] = [];
|
||||||
@@ -628,13 +718,23 @@ async function spliceRemoteScopes(
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
for (const teapot of mesh.teapots ?? []) {
|
for (const teapot of mesh.teapots ?? []) {
|
||||||
const link = await connectLink({
|
warnIfCleartext(teapot.url, logger);
|
||||||
|
// Deferred so the reconnect callback can name this link's provider tokens, which are only
|
||||||
|
// known once its manifest arrives — the callback is registered before the link can drop.
|
||||||
|
const rebind: Array<() => void> = [];
|
||||||
|
const link = await connectUntilDeadline(mesh, bus, logger, () =>
|
||||||
|
connectLink({
|
||||||
url: teapot.url,
|
url: teapot.url,
|
||||||
secret: teapot.secret,
|
secret: teapot.secret,
|
||||||
timeoutMs: mesh.timeoutMs,
|
timeoutMs: mesh.timeoutMs,
|
||||||
heartbeatMs: mesh.heartbeatMs,
|
heartbeatMs: mesh.heartbeatMs,
|
||||||
|
reconnect: mesh.reconnect,
|
||||||
|
onManifestChange: mesh.onManifestChange,
|
||||||
|
onReconnect: () => invalidateRemoteBindings(rebind),
|
||||||
|
logger,
|
||||||
bus,
|
bus,
|
||||||
});
|
}),
|
||||||
|
);
|
||||||
meshLinks.push(link);
|
meshLinks.push(link);
|
||||||
const { providers, steps, routes } = buildRemote(link);
|
const { providers, steps, routes } = buildRemote(link);
|
||||||
const origin = `mesh:${teapot.url}`;
|
const origin = `mesh:${teapot.url}`;
|
||||||
@@ -643,6 +743,10 @@ async function spliceRemoteScopes(
|
|||||||
registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin });
|
registry.providerNodes.push({ name: provider.name, needs: [], provides: [provider.name], origin });
|
||||||
registry.providerMeta.set(provider.name, { optional: false });
|
registry.providerMeta.set(provider.name, { optional: false });
|
||||||
registry.setRunner(provider.name, provider.run);
|
registry.setRunner(provider.name, provider.run);
|
||||||
|
// A remote app-scope value is resolved once at boot and frozen into the container, so it
|
||||||
|
// would keep answering from a cache the teapot no longer stands behind. Re-registering
|
||||||
|
// gives the binding a factory that re-runs the RPC, and `register` drops the memo with it.
|
||||||
|
rebind.push(() => container.register(provider.name, 'app', () => provider.run({})));
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const step of steps) {
|
for (const step of steps) {
|
||||||
@@ -692,7 +796,19 @@ async function spliceRemoteScopes(
|
|||||||
method: route.method,
|
method: route.method,
|
||||||
pattern: route.pattern,
|
pattern: route.pattern,
|
||||||
transport: 'buffer',
|
transport: 'buffer',
|
||||||
handler: async (req) => route.handler(req as RequestEnvelope),
|
// 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 },
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -842,7 +958,14 @@ function buildMeshControl(
|
|||||||
if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name));
|
if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name));
|
||||||
|
|
||||||
const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! }));
|
const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! }));
|
||||||
const context = await runSteps(steps, seed, bus);
|
// The caller's identity, adopted rather than replaced — the same rule an incoming
|
||||||
|
// `x-request-id` gets, applied at the process boundary where it matters most. No `route`:
|
||||||
|
// resolving a scope is not a route, and inventing one would put a token in a route label.
|
||||||
|
const context = await runSteps(steps, seed, bus, {
|
||||||
|
requestId: env.correlation?.requestId,
|
||||||
|
traceId: env.correlation?.traceId,
|
||||||
|
method: env.method,
|
||||||
|
});
|
||||||
|
|
||||||
return context[name];
|
return context[name];
|
||||||
};
|
};
|
||||||
@@ -864,6 +987,13 @@ function buildMeshControl(
|
|||||||
bus,
|
bus,
|
||||||
onError,
|
onError,
|
||||||
transport: plan.transport,
|
transport: plan.transport,
|
||||||
|
correlation: {
|
||||||
|
requestId: env.correlation?.requestId,
|
||||||
|
traceId: env.correlation?.traceId,
|
||||||
|
route: plan.pattern,
|
||||||
|
method: plan.method,
|
||||||
|
transport: plan.transport,
|
||||||
|
},
|
||||||
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
|
seed: { ...provided, req: env, params: env.params, query: env.query, body: env.body, headers: env.headers },
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1095,13 +1225,9 @@ function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: numbe
|
|||||||
return new Promise<void>((resolve) => {
|
return new Promise<void>((resolve) => {
|
||||||
let settled = false;
|
let settled = false;
|
||||||
|
|
||||||
const finish = (): void => {
|
// Armed before `finish` exists, for the reason spelled out in `closeApp` below: setTimeout
|
||||||
if (settled) return;
|
// cannot fire synchronously, so the forward reference to `finish` rests on a guarantee, while
|
||||||
settled = true;
|
// the reverse ordering would rest on `teardown.run().then()` deferring.
|
||||||
clearTimeout(timer);
|
|
||||||
resolve();
|
|
||||||
};
|
|
||||||
|
|
||||||
const timer = setTimeout(
|
const timer = setTimeout(
|
||||||
() => {
|
() => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
@@ -1114,6 +1240,14 @@ function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: numbe
|
|||||||
);
|
);
|
||||||
|
|
||||||
timer.unref?.();
|
timer.unref?.();
|
||||||
|
|
||||||
|
const finish = (): void => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
|
||||||
void teardown.run(logger).then(finish, finish);
|
void teardown.run(logger).then(finish, finish);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -103,6 +103,38 @@ export interface MeshConfig {
|
|||||||
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
|
* `timeoutMs` first. Lower it to notice a dead teapot sooner, at the cost of more chatter.
|
||||||
*/
|
*/
|
||||||
heartbeatMs?: number;
|
heartbeatMs?: number;
|
||||||
|
/**
|
||||||
|
* Reconnect to a teapot after its link drops (default: on). A dropped link used to stay dead for
|
||||||
|
* the life of the process, which meant deploying a teapot forced a restart of every teacup.
|
||||||
|
*
|
||||||
|
* `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
|
||||||
|
* together do not come back in lockstep.
|
||||||
|
*/
|
||||||
|
reconnect?: boolean | { initialDelayMs?: number; maxDelayMs?: number };
|
||||||
|
/**
|
||||||
|
* What to do when a returning teapot's manifest no longer exports something the graph was
|
||||||
|
* validated against at boot (default: `'refuse'`).
|
||||||
|
*
|
||||||
|
* `'refuse'` hangs up on that session and keeps retrying — a partial deploy may still restore it.
|
||||||
|
* 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
|
||||||
|
* rather than left implicit so that arriving is additive rather than a change of default.
|
||||||
|
*/
|
||||||
|
onManifestChange?: 'refuse';
|
||||||
|
/**
|
||||||
|
* How long boot keeps trying to reach a teapot before giving up on it (default: `timeoutMs`,
|
||||||
|
* so 30s). Attempts use the same backoff as reconnection.
|
||||||
|
*
|
||||||
|
* A teapot that is merely slow to start — a container scheduled a moment later, a network that
|
||||||
|
* has not settled — should not fail a deploy, and this is the grace for that. A teapot that is
|
||||||
|
* genuinely absent still fails the boot when the deadline passes, because a provider the graph
|
||||||
|
* depends on is not optional: booting without it would only move the failure to the first
|
||||||
|
* request, where it is somebody else's 503 instead of your deploy's error.
|
||||||
|
*
|
||||||
|
* `0` restores the old behaviour of a single attempt.
|
||||||
|
*/
|
||||||
|
bootTimeoutMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ export type LifecycleEvent =
|
|||||||
| 'mesh:connect'
|
| 'mesh:connect'
|
||||||
| 'mesh:disconnect'
|
| 'mesh:disconnect'
|
||||||
| 'mesh:rpc:error'
|
| 'mesh:rpc:error'
|
||||||
|
// A boot-time connect attempt that failed and will be retried until `bootTimeoutMs` passes.
|
||||||
|
// 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.
|
||||||
|
| 'mesh:boot:retry'
|
||||||
| 'plugin:mounted'
|
| 'plugin:mounted'
|
||||||
| 'request:start'
|
| 'request:start'
|
||||||
| 'request:end'
|
| 'request:end'
|
||||||
|
|||||||
+312
-60
@@ -1,6 +1,8 @@
|
|||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
|
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';
|
||||||
|
|
||||||
@@ -11,15 +13,71 @@ export interface Link {
|
|||||||
close(): void;
|
close(): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Backoff bounds for reconnection. `false` disables reconnecting entirely. */
|
||||||
|
export interface ReconnectOptions {
|
||||||
|
/** Delay before the first retry; doubles from here (default: 500ms). */
|
||||||
|
initialDelayMs?: number;
|
||||||
|
/** Ceiling the doubling stops at (default: 30s). */
|
||||||
|
maxDelayMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What to do when a reconnecting teapot answers with a manifest that no longer backs the graph.
|
||||||
|
*
|
||||||
|
* Only `'refuse'` exists. It is a named strategy rather than implicit behaviour so that hot graph
|
||||||
|
* reconciliation can arrive later as `'reconcile'` *additively* — peers run on separate deploy
|
||||||
|
* cadences, and silently changing what the default means is the worst kind of breaking change.
|
||||||
|
*/
|
||||||
|
export type ManifestPolicy = 'refuse';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A connection failure the peer decided, rather than one the network caused.
|
||||||
|
*
|
||||||
|
* The distinction is what boot retry needs: a refused secret or a version mismatch will fail
|
||||||
|
* identically forever, so retrying one spends a deploy's patience to reach the same error. It is
|
||||||
|
* derived from whether the socket ever *opened* — a peer that accepted the connection and then hung
|
||||||
|
* up before the manifest rejected us on purpose; one that never accepted it may simply not be up.
|
||||||
|
*/
|
||||||
|
export function isPermanentRefusal(error: unknown): boolean {
|
||||||
|
return (error as { meshRefused?: boolean } | undefined)?.meshRefused === true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tag an error as a decision by the peer, so the caller does not retry it. */
|
||||||
|
function refused(message: string): Error {
|
||||||
|
const error = new Error(message) as Error & { meshRefused: boolean };
|
||||||
|
error.meshRefused = true;
|
||||||
|
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
|
/** An in-flight RPC awaiting its `rpc-res`, keyed by id in the pending map. */
|
||||||
type PendingEntry = {
|
type PendingEntry = {
|
||||||
|
/** The token or route asked for. Kept so an error can be reported by name — the frame only carries the id. */
|
||||||
|
name: string;
|
||||||
resolve: (v: unknown) => void;
|
resolve: (v: unknown) => void;
|
||||||
reject: (e: unknown) => void;
|
reject: (e: unknown) => void;
|
||||||
timer: ReturnType<typeof setTimeout>;
|
timer: ReturnType<typeof setTimeout>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Mutable per-link state: which socket is current, and whether the application hung up for good. */
|
||||||
|
interface LinkState {
|
||||||
|
socket: WsSocket | undefined;
|
||||||
|
closed: boolean;
|
||||||
|
retry: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One established connection: its socket, the manifest it announced, and its heartbeat. */
|
||||||
|
interface Session {
|
||||||
|
socket: WsSocket;
|
||||||
|
manifest: Manifest;
|
||||||
|
heartbeat: { stop: () => void; markAlive: () => void };
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_INITIAL_DELAY_MS = 500;
|
||||||
|
const DEFAULT_MAX_DELAY_MS = 30_000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reject and clear every in-flight RPC — used when the link closes.
|
* Reject and clear every in-flight RPC — used when a session ends.
|
||||||
* 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.
|
||||||
*/
|
*/
|
||||||
@@ -34,7 +92,7 @@ function rejectAllPending(pending: Map<string, PendingEntry>, reason: string): v
|
|||||||
|
|
||||||
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
|
/** Register one RPC in `pending` by id, send its request, and reject it on timeout. */
|
||||||
function sendRpc(
|
function sendRpc(
|
||||||
socket: WsSocket,
|
socket: WsSocket | undefined,
|
||||||
pending: Map<string, PendingEntry>,
|
pending: Map<string, PendingEntry>,
|
||||||
id: string,
|
id: string,
|
||||||
kind: 'scope' | 'route',
|
kind: 'scope' | 'route',
|
||||||
@@ -44,8 +102,9 @@ function sendRpc(
|
|||||||
): 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.
|
// before failing anyway — the caller pays for a verdict already known. This is also the
|
||||||
if (!socket.isOpen) {
|
// window a reconnecting link sits in: down, and answering immediately.
|
||||||
|
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}'`));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,30 +116,11 @@ function sendRpc(
|
|||||||
rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
|
rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`));
|
||||||
}, timeoutMs);
|
}, timeoutMs);
|
||||||
|
|
||||||
pending.set(id, { resolve: resolveCall, reject: rejectCall, timer });
|
pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer });
|
||||||
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
|
socket.send(encode({ type: 'rpc-req', id, kind, name, ctx }));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Assemble the client-facing Link once the manifest arrives. */
|
|
||||||
function buildLink(socket: WsSocket, pending: Map<string, PendingEntry>, manifest: Manifest, timeoutMs: number): Link {
|
|
||||||
// ids only need to be unique within this link: `pending` is per-connection, so a
|
|
||||||
// per-link counter suffices (no module-global sequence, no test-order coupling).
|
|
||||||
let counter = 0;
|
|
||||||
|
|
||||||
return {
|
|
||||||
manifest,
|
|
||||||
rpc(kind, name, ctx) {
|
|
||||||
const id = String(counter++);
|
|
||||||
|
|
||||||
return sendRpc(socket, pending, id, kind, name, ctx, timeoutMs);
|
|
||||||
},
|
|
||||||
close() {
|
|
||||||
socket.close();
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */
|
/** Settle a pending RPC from its `rpc-res` frame — resolve on ok, reject (and emit) on error. */
|
||||||
function settleRpcResponse(
|
function settleRpcResponse(
|
||||||
pending: Map<string, PendingEntry>,
|
pending: Map<string, PendingEntry>,
|
||||||
@@ -95,7 +135,10 @@ function settleRpcResponse(
|
|||||||
if (frame.ok) {
|
if (frame.ok) {
|
||||||
entry.resolve(frame.result);
|
entry.resolve(frame.result);
|
||||||
} else {
|
} else {
|
||||||
bus?.emit('mesh:rpc:error', { name: frame.id, error: frame.error });
|
// `entry.name`, not `frame.id`: the id is a per-link counter, so this event used to report
|
||||||
|
// "0" or "1" where every other emitter reports what failed — including the teapot's own
|
||||||
|
// emit for the same call, which made the two sides of one failure impossible to line up.
|
||||||
|
bus?.emit('mesh:rpc:error', { name: entry.name, error: frame.error });
|
||||||
entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
|
entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -118,7 +161,8 @@ const CLOSE_HEARTBEAT_TIMEOUT = 4011;
|
|||||||
* A TCP connection can die without either side noticing — a dropped route, a killed container,
|
* A TCP connection can die without either side noticing — a dropped route, a killed container,
|
||||||
* a NAT timing out — leaving the socket "open" with nobody home. Without this, a teacup only
|
* a NAT timing out — leaving the socket "open" with nobody home. Without this, a teacup only
|
||||||
* learns on the next request, which pays the full rpc timeout before failing. Closing the socket
|
* learns on the next request, which pays the full rpc timeout before failing. Closing the socket
|
||||||
* turns that into an immediate 503 from the dead-link guard, and emits `mesh:disconnect`.
|
* turns that into an immediate 503 from the dead-link guard, emits `mesh:disconnect`, and starts
|
||||||
|
* the reconnect backoff.
|
||||||
*
|
*
|
||||||
* The interval is unref'd, so a heartbeat never holds the process open by itself.
|
* The interval is unref'd, so a heartbeat never holds the process open by itself.
|
||||||
*/
|
*/
|
||||||
@@ -144,25 +188,24 @@ function startHeartbeat(socket: WsSocket, everyMs: number): { stop: () => void;
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Handle for the in-flight handshake, so the frame loop can settle `connectLink`'s promise. */
|
/** Handle for the in-flight handshake, so the frame loop can settle the session promise. */
|
||||||
interface Handshake {
|
interface Handshake {
|
||||||
url: string;
|
url: string;
|
||||||
socket: WsSocket;
|
socket: WsSocket;
|
||||||
pending: Map<string, PendingEntry>;
|
pending: Map<string, PendingEntry>;
|
||||||
timeoutMs: number;
|
|
||||||
bus?: Bus;
|
bus?: Bus;
|
||||||
resolve: (link: Link) => void;
|
resolve: (session: Session) => void;
|
||||||
reject: (error: unknown) => void;
|
reject: (error: unknown) => void;
|
||||||
onManifest: () => void;
|
onManifest: (socket: WsSocket) => Session['heartbeat'];
|
||||||
onPong: () => void;
|
onPong: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else build the Link. */
|
/** Settle the handshake from a `manifest` frame: refuse a version mismatch, else hand back the session. */
|
||||||
function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handshake): void {
|
function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handshake): void {
|
||||||
if (frame.v !== MESH_PROTOCOL_VERSION) {
|
if (frame.v !== MESH_PROTOCOL_VERSION) {
|
||||||
hs.socket.close();
|
hs.socket.close();
|
||||||
hs.reject(
|
hs.reject(
|
||||||
new Error(
|
refused(
|
||||||
`mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
|
`mesh protocol version mismatch at ${hs.url}: teapot speaks v${frame.v}, this teacup speaks v${MESH_PROTOCOL_VERSION}`,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -170,12 +213,15 @@ function settleManifest(frame: Extract<Frame, { type: 'manifest' }>, hs: Handsha
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
hs.onManifest();
|
const heartbeat = hs.onManifest(hs.socket);
|
||||||
hs.bus?.emit('mesh:connect', { name: hs.url });
|
|
||||||
hs.resolve(buildLink(hs.socket, hs.pending, { scopes: frame.scopes, routes: frame.routes }, hs.timeoutMs));
|
// `mesh:connect` is emitted by the caller, not here: a reconnect whose manifest no longer backs
|
||||||
|
// the graph is refused after this point, and announcing a connection we are about to hang up on
|
||||||
|
// would tell an operator the opposite of what happened.
|
||||||
|
hs.resolve({ socket: hs.socket, manifest: { scopes: frame.scopes, routes: frame.routes }, heartbeat });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Consume the link's inbound frames until it closes, settling the handshake then each RPC. */
|
/** Consume the session's inbound frames until it closes, settling the handshake then each RPC. */
|
||||||
async function readFrames(hs: Handshake): Promise<void> {
|
async function readFrames(hs: Handshake): Promise<void> {
|
||||||
for await (const data of hs.socket.inbound) {
|
for await (const data of hs.socket.inbound) {
|
||||||
let frame: Frame;
|
let frame: Frame;
|
||||||
@@ -192,49 +238,61 @@ async function readFrames(hs: Handshake): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Everything a link needs to open one session, shared by the first connect and every retry. */
|
||||||
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
|
interface SessionArgs {
|
||||||
* arrives. `Ctor` is injectable to exercise both client implementations on a single runtime.
|
|
||||||
*/
|
|
||||||
export function connectLink(args: {
|
|
||||||
url: string;
|
url: string;
|
||||||
secret: string;
|
secret: string;
|
||||||
timeoutMs?: number;
|
timeoutMs: number;
|
||||||
heartbeatMs?: number;
|
heartbeatMs: number;
|
||||||
|
pending: Map<string, PendingEntry>;
|
||||||
bus?: Bus;
|
bus?: Bus;
|
||||||
Ctor?: SocketCtor;
|
Ctor?: SocketCtor;
|
||||||
}): Promise<Link> {
|
onEnd: () => void;
|
||||||
const timeoutMs = args.timeoutMs ?? 30_000;
|
}
|
||||||
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
|
|
||||||
const pending = new Map<string, PendingEntry>();
|
|
||||||
let manifest = false;
|
|
||||||
let heartbeat: { stop: () => void; markAlive: () => void } | undefined;
|
|
||||||
|
|
||||||
return new Promise<Link>((resolve, reject) => {
|
/**
|
||||||
|
* Open one authenticated session: connect, handshake, and resolve once the manifest arrives.
|
||||||
|
*
|
||||||
|
* `onEnd` fires when this session's socket aborts — on a clean close and on an error alike — and is
|
||||||
|
* where the supervisor rejects in-flight RPCs and decides whether to retry. It fires for a session
|
||||||
|
* that never handshook too, which is what turns a refused connection into a scheduled retry rather
|
||||||
|
* than a silent stall.
|
||||||
|
*/
|
||||||
|
function openSession(args: SessionArgs): Promise<Session> {
|
||||||
|
const { socket, opened } = connectSocket(args.url, args.Ctor ?? undefined);
|
||||||
|
let heartbeat: Session['heartbeat'] | undefined;
|
||||||
|
let handshook = false;
|
||||||
|
let accepted = false;
|
||||||
|
|
||||||
|
return new Promise<Session>((resolve, reject) => {
|
||||||
const connectTimer = setTimeout(() => {
|
const connectTimer = setTimeout(() => {
|
||||||
socket.close();
|
socket.close();
|
||||||
reject(new Error(`mesh connect timeout: ${args.url}`));
|
reject(new Error(`mesh connect timeout: ${args.url}`));
|
||||||
}, timeoutMs);
|
}, args.timeoutMs);
|
||||||
|
|
||||||
const hs: Handshake = {
|
const hs: Handshake = {
|
||||||
url: args.url,
|
url: args.url,
|
||||||
socket,
|
socket,
|
||||||
pending,
|
pending: args.pending,
|
||||||
timeoutMs,
|
|
||||||
bus: args.bus,
|
bus: args.bus,
|
||||||
resolve,
|
resolve,
|
||||||
reject,
|
reject,
|
||||||
onManifest: () => {
|
onManifest: (established) => {
|
||||||
manifest = true;
|
handshook = true;
|
||||||
clearTimeout(connectTimer);
|
clearTimeout(connectTimer);
|
||||||
// started only once authenticated: an unauthenticated peer should not be pinging
|
// started only once authenticated: an unauthenticated peer should not be pinging
|
||||||
heartbeat = startHeartbeat(socket, args.heartbeatMs ?? HEARTBEAT_MS);
|
heartbeat = startHeartbeat(established, args.heartbeatMs);
|
||||||
|
|
||||||
|
return heartbeat;
|
||||||
},
|
},
|
||||||
onPong: () => heartbeat?.markAlive(),
|
onPong: () => heartbeat?.markAlive(),
|
||||||
};
|
};
|
||||||
|
|
||||||
opened.then(
|
opened.then(
|
||||||
() => socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret })),
|
() => {
|
||||||
|
accepted = true;
|
||||||
|
socket.send(encode({ type: 'hello', v: MESH_PROTOCOL_VERSION, secret: args.secret }));
|
||||||
|
},
|
||||||
(error) => reject(error),
|
(error) => reject(error),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -245,9 +303,16 @@ export function connectLink(args: {
|
|||||||
() => {
|
() => {
|
||||||
clearTimeout(connectTimer);
|
clearTimeout(connectTimer);
|
||||||
heartbeat?.stop();
|
heartbeat?.stop();
|
||||||
args.bus?.emit('mesh:disconnect', { name: args.url });
|
|
||||||
rejectAllPending(pending, `mesh link to ${args.url} is down`);
|
if (!handshook) {
|
||||||
if (!manifest) reject(new Error(`mesh handshake failed: ${args.url}`));
|
// Opened and then hung up before answering: the teapot refused this peer — a bad secret,
|
||||||
|
// or a version it would not speak. Never opened: it may just not be listening yet.
|
||||||
|
const message = `mesh handshake failed: ${args.url}`;
|
||||||
|
|
||||||
|
reject(accepted ? refused(message) : new Error(message));
|
||||||
|
}
|
||||||
|
|
||||||
|
args.onEnd();
|
||||||
},
|
},
|
||||||
{ once: true },
|
{ once: true },
|
||||||
);
|
);
|
||||||
@@ -257,3 +322,190 @@ export function connectLink(args: {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A scope token and its lifetime, flattened to the string the refusal check compares. */
|
||||||
|
function scopeKeys(manifest: Manifest): Set<string> {
|
||||||
|
return new Set(manifest.scopes.map((scope) => `${scope.scope}:${scope.token}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Route keys by method plus *effective shape*, the same comparison `spliceRemoteScopes` uses to
|
||||||
|
* 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
|
||||||
|
* vanished cannot be validated away after the fact, so a manifest missing anything this link
|
||||||
|
* contributed is refused rather than accepted — see `ManifestPolicy`. Extra exports are *not*
|
||||||
|
* missing and are ignored: the graph is fixed at boot and nothing new is spliced into it.
|
||||||
|
*/
|
||||||
|
export function missingFromManifest(booted: Manifest, returned: Manifest): string[] {
|
||||||
|
const scopes = scopeKeys(returned);
|
||||||
|
const routes = routeKeys(returned);
|
||||||
|
const missing: string[] = [];
|
||||||
|
|
||||||
|
for (const scope of booted.scopes) {
|
||||||
|
if (!scopes.has(`${scope.scope}:${scope.token}`)) missing.push(`${scope.scope}-scope '${scope.token}'`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const route of booted.routes) {
|
||||||
|
if (!routes.has(`${route.method} ${compilePattern(route.pattern).shape}`)) {
|
||||||
|
missing.push(`route '${route.method} ${route.pattern}'`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return missing;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolved backoff bounds, or `undefined` when the caller turned reconnection off. */
|
||||||
|
function backoffBounds(
|
||||||
|
reconnect: boolean | ReconnectOptions | undefined,
|
||||||
|
): { initial: number; max: number } | undefined {
|
||||||
|
if (reconnect === false) return undefined;
|
||||||
|
const opts = typeof reconnect === 'object' ? reconnect : {};
|
||||||
|
|
||||||
|
return {
|
||||||
|
initial: opts.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS,
|
||||||
|
max: opts.maxDelayMs ?? DEFAULT_MAX_DELAY_MS,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open a WebSocket link to a mesh server, handshake with `secret`, and resolve once its manifest
|
||||||
|
* arrives. The returned `Link` outlives any single socket: when a session drops, the link keeps its
|
||||||
|
* identity — the graph captured `rpc` at boot — and reconnects underneath it.
|
||||||
|
*
|
||||||
|
* `Ctor` is injectable to exercise both client implementations on a single runtime.
|
||||||
|
*/
|
||||||
|
export function connectLink(args: {
|
||||||
|
url: string;
|
||||||
|
secret: string;
|
||||||
|
timeoutMs?: number;
|
||||||
|
heartbeatMs?: number;
|
||||||
|
bus?: Bus;
|
||||||
|
Ctor?: SocketCtor;
|
||||||
|
/** Reconnect after a dropped session (default: on). `false` restores the old fail-once behaviour. */
|
||||||
|
reconnect?: boolean | ReconnectOptions;
|
||||||
|
/** What to do when a returning teapot's manifest no longer backs the graph (default: `'refuse'`). */
|
||||||
|
onManifestChange?: ManifestPolicy;
|
||||||
|
/** Called after a *successful* reconnect, so app-scope values resolved from this link are re-resolved. */
|
||||||
|
onReconnect?: () => void;
|
||||||
|
logger?: Logger;
|
||||||
|
}): Promise<Link> {
|
||||||
|
const timeoutMs = args.timeoutMs ?? 30_000;
|
||||||
|
const heartbeatMs = args.heartbeatMs ?? HEARTBEAT_MS;
|
||||||
|
const bounds = backoffBounds(args.reconnect);
|
||||||
|
const pending = new Map<string, PendingEntry>();
|
||||||
|
const state: LinkState = { socket: undefined, closed: false, retry: undefined };
|
||||||
|
let refusalLogged = '';
|
||||||
|
|
||||||
|
const link: Link = {
|
||||||
|
// replaced with the real manifest before this object escapes; a reconnect never changes it,
|
||||||
|
// because the graph is fixed at boot and only the *boot* manifest describes what it holds.
|
||||||
|
manifest: { scopes: [], routes: [] },
|
||||||
|
rpc: (kind, name, ctx) => sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs),
|
||||||
|
close: () => {
|
||||||
|
// Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after
|
||||||
|
// the application hung up would leave a process that cannot exit.
|
||||||
|
state.closed = true;
|
||||||
|
clearTimeout(state.retry);
|
||||||
|
state.socket?.close();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
// ids only need to be unique within this link: `pending` is per-link, so a per-link counter
|
||||||
|
// suffices (no module-global sequence, no test-order coupling).
|
||||||
|
let counter = 0;
|
||||||
|
|
||||||
|
const sessionArgs = (onEnd: () => void): SessionArgs => ({
|
||||||
|
url: args.url,
|
||||||
|
secret: args.secret,
|
||||||
|
timeoutMs,
|
||||||
|
heartbeatMs,
|
||||||
|
pending,
|
||||||
|
bus: args.bus,
|
||||||
|
Ctor: args.Ctor,
|
||||||
|
onEnd,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Schedule the next attempt, doubling from `initial` up to `max` with jitter. */
|
||||||
|
const scheduleRetry = (attempt: number): void => {
|
||||||
|
if (state.closed || !bounds) return;
|
||||||
|
const capped = Math.min(bounds.initial * 2 ** attempt, bounds.max);
|
||||||
|
// Full jitter: peers that went down together must not come back in lockstep and stampede
|
||||||
|
// the teapot the moment it returns.
|
||||||
|
const delay = Math.round(capped / 2 + Math.random() * (capped / 2));
|
||||||
|
|
||||||
|
state.retry = setTimeout(() => void attemptReconnect(attempt + 1), delay);
|
||||||
|
state.retry.unref?.();
|
||||||
|
};
|
||||||
|
|
||||||
|
/** End the current session: nothing can be delivered on it, so fail what was waiting. */
|
||||||
|
const endSession = (attempt: number): void => {
|
||||||
|
state.socket = undefined;
|
||||||
|
args.bus?.emit('mesh:disconnect', { name: args.url });
|
||||||
|
rejectAllPending(pending, `mesh link to ${args.url} is down`);
|
||||||
|
scheduleRetry(attempt);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Adopt an established session, or refuse it when its manifest no longer backs the graph. */
|
||||||
|
const adopt = (session: Session, attempt: number, reconnected: boolean): boolean => {
|
||||||
|
const missing = missingFromManifest(link.manifest, session.manifest);
|
||||||
|
|
||||||
|
if (missing.length > 0) {
|
||||||
|
session.heartbeat.stop();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
refusalLogged = '';
|
||||||
|
state.socket = session.socket;
|
||||||
|
args.bus?.emit('mesh:connect', { name: args.url });
|
||||||
|
if (reconnected) args.onReconnect?.();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const attemptReconnect = async (attempt: number): Promise<void> => {
|
||||||
|
if (state.closed) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = await openSession(sessionArgs(() => endSession(attempt)));
|
||||||
|
|
||||||
|
if (state.closed) {
|
||||||
|
session.socket.close(); // hung up while this attempt was in flight
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!adopt(session, attempt, true)) scheduleRetry(attempt);
|
||||||
|
} catch {
|
||||||
|
// openSession's own abort listener already scheduled the retry through `onEnd`; a rejection
|
||||||
|
// that never opened a socket (a bad URL, DNS) needs one scheduled here instead.
|
||||||
|
if (!state.socket && !state.retry) scheduleRetry(attempt);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return openSession(sessionArgs(() => endSession(0))).then((session) => {
|
||||||
|
link.manifest = session.manifest;
|
||||||
|
adopt(session, 0, false);
|
||||||
|
|
||||||
|
return link;
|
||||||
|
});
|
||||||
|
}
|
||||||
+117
-3
@@ -1,18 +1,46 @@
|
|||||||
/**
|
/**
|
||||||
* Version of the mesh wire protocol. Peers are separate processes on separate deploy
|
* Version of the mesh wire protocol. Peers are separate processes on separate deploy
|
||||||
* cadences — possibly on different runtimes — so the frame shapes are a contract between
|
* cadences — possibly on different runtimes — so the frame shapes are a contract between
|
||||||
* green-tea versions, not an internal detail. Bump on any breaking frame change; peers
|
* green-tea versions, not an internal detail. Peers refuse each other on mismatch rather
|
||||||
* refuse each other on mismatch rather than misparsing downstream.
|
* than misparsing downstream.
|
||||||
|
*
|
||||||
|
* **This is a compatibility boundary, not a changelog.** Bump it only when a peer running the
|
||||||
|
* old version would *misparse a frame or misbehave silently*:
|
||||||
|
*
|
||||||
|
* - removing or renaming a field, or changing its type or meaning;
|
||||||
|
* - adding a **required** field;
|
||||||
|
* - adding a frame type that expects an answer — an old peer cannot decode it, drops it as
|
||||||
|
* undecodable, and the sender waits for a reply that will never come.
|
||||||
|
*
|
||||||
|
* Adding an **optional** field is not one of those: `decode` validates only the fields a frame
|
||||||
|
* type requires and passes extras through untouched, so an old peer ignores what it does not
|
||||||
|
* know and keeps answering. That is degraded, not broken, and does not earn a bump.
|
||||||
|
*
|
||||||
|
* Bumping per change would make the number mean "work happened" rather than "we are
|
||||||
|
* incompatible", which is the one thing it is here to say.
|
||||||
*/
|
*/
|
||||||
export const MESH_PROTOCOL_VERSION = 1;
|
export const MESH_PROTOCOL_VERSION = 1;
|
||||||
|
|
||||||
/** Serialized request context sent across the mesh for a scope or route RPC. */
|
/**
|
||||||
|
* Serialized request context sent across the mesh for a scope or route RPC.
|
||||||
|
*
|
||||||
|
* `correlation` and `url` are optional by protocol, not by intent: a teapot running an older
|
||||||
|
* green-tea simply ignores them, which costs the correlation of that hop and nothing else.
|
||||||
|
*/
|
||||||
export interface RequestEnvelope {
|
export interface RequestEnvelope {
|
||||||
method: string;
|
method: string;
|
||||||
params: Record<string, string>;
|
params: Record<string, string>;
|
||||||
query: Record<string, string>;
|
query: Record<string, string>;
|
||||||
body: unknown;
|
body: unknown;
|
||||||
headers: Record<string, string | string[] | undefined>;
|
headers: Record<string, string | string[] | undefined>;
|
||||||
|
/** The requested URL, so a teapot's handler sees the same path its caller did. */
|
||||||
|
url?: string;
|
||||||
|
/**
|
||||||
|
* The caller's request identity, so a request that crosses the mesh keeps one id end to end.
|
||||||
|
* Without it every hop opens a new investigation, in the one place a distributed trace is
|
||||||
|
* the whole point.
|
||||||
|
*/
|
||||||
|
correlation?: { requestId?: string; traceId?: string };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Manifest entry for an exported scope token and its lifetime. */
|
/** Manifest entry for an exported scope token and its lifetime. */
|
||||||
@@ -87,6 +115,92 @@ const SHAPE: Record<Frame['type'], ShapeCheck> = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** How much of a value the transport check walks before it stops looking. */
|
||||||
|
const TRANSPORT_SCAN_BUDGET = 10_000;
|
||||||
|
|
||||||
|
/** Names what a value is, for an error a reader can act on: `Pool`, `Map`, `Date`, `function`. */
|
||||||
|
function describe(value: unknown): string {
|
||||||
|
if (typeof value === 'function') return 'a function';
|
||||||
|
const name = (value as object).constructor?.name;
|
||||||
|
|
||||||
|
return name ? `a ${name} instance` : 'an object with no prototype';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the first part of `value` that cannot survive the wire, or `undefined` if all of it can.
|
||||||
|
*
|
||||||
|
* The wire is JSON, so the mesh transports **data, never behaviour**. Before this check, exporting a
|
||||||
|
* value with methods — a connection pool, a client, a `Map` — serialized to `{}` and arrived looking
|
||||||
|
* alive: truthy, an object, and missing every method. The failure then surfaced as
|
||||||
|
* `db.query is not a function` at the call site, arbitrarily far from the export that caused it.
|
||||||
|
*
|
||||||
|
* The rule is an allowlist rather than a denylist, on purpose. `Date` is refused too: it would
|
||||||
|
* arrive as a string, which is not the type the caller declared and is the same silent difference
|
||||||
|
* in a smaller costume.
|
||||||
|
*
|
||||||
|
* Bounded by a node budget so a large legitimate payload is never turned into an error by the cost
|
||||||
|
* of checking it — past the budget the value is assumed fine, since the shapes this catches are
|
||||||
|
* structural and show up immediately.
|
||||||
|
*/
|
||||||
|
export function untransportable(value: unknown, path = 'result'): Offender | undefined {
|
||||||
|
return walk(value, path, { left: TRANSPORT_SCAN_BUDGET });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What could not cross, and where it sat in the value. */
|
||||||
|
type Offender = { path: string; what: string };
|
||||||
|
|
||||||
|
/** Remaining nodes the scan may visit, shared across the whole walk. */
|
||||||
|
type Budget = { left: number };
|
||||||
|
|
||||||
|
/** Values JSON cannot represent at all, whatever they are nested in. */
|
||||||
|
function isBehaviour(kind: string): boolean {
|
||||||
|
return kind === 'function' || kind === 'symbol' || kind === 'bigint';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a container survives the round trip as itself: a plain object or a null-prototype bag.
|
||||||
|
* Anything else is a class instance whose identity JSON discards — `Pool`, `Map`, `Set`, `Date`.
|
||||||
|
*/
|
||||||
|
function isPlainContainer(node: object): boolean {
|
||||||
|
const proto = Object.getPrototypeOf(node);
|
||||||
|
|
||||||
|
return proto === Object.prototype || proto === null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Walk labelled children in order, returning the first offender. */
|
||||||
|
function walkEntries(entries: Array<[string, unknown]>, budget: Budget): Offender | undefined {
|
||||||
|
for (const [at, item] of entries) {
|
||||||
|
const found = walk(item, at, budget);
|
||||||
|
|
||||||
|
if (found) return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One node of the scan: reject behaviour and class instances, otherwise descend. */
|
||||||
|
function walk(node: unknown, at: string, budget: Budget): Offender | undefined {
|
||||||
|
if (budget.left-- <= 0 || node === null) return undefined;
|
||||||
|
const kind = typeof node;
|
||||||
|
|
||||||
|
if (isBehaviour(kind)) return { path: at, what: describe(node) };
|
||||||
|
if (kind !== 'object') return undefined;
|
||||||
|
|
||||||
|
if (Array.isArray(node)) {
|
||||||
|
return walkEntries(
|
||||||
|
node.map((item, index) => [`${at}[${index}]`, item] as [string, unknown]),
|
||||||
|
budget,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isPlainContainer(node as object)) return { path: at, what: describe(node) };
|
||||||
|
|
||||||
|
return walkEntries(
|
||||||
|
Object.entries(node as Record<string, unknown>).map(([key, item]) => [`${at}.${key}`, item] as [string, unknown]),
|
||||||
|
budget,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** Serialize a frame to a JSON wire string. */
|
/** Serialize a frame to a JSON wire string. */
|
||||||
export function encode(frame: Frame): string {
|
export function encode(frame: Frame): string {
|
||||||
return JSON.stringify(frame);
|
return JSON.stringify(frame);
|
||||||
|
|||||||
+14
-2
@@ -14,14 +14,26 @@ export interface RemoteRoute {
|
|||||||
handler: (req: RequestEnvelope) => Promise<ResponseShape>;
|
handler: (req: RequestEnvelope) => Promise<ResponseShape>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh. */
|
/**
|
||||||
|
* Extract a {@link RequestEnvelope} from a local request context for transmission over the mesh.
|
||||||
|
*
|
||||||
|
* `url` and `correlation` are read off `ctx.req`, the handler argument the pipeline seeds the
|
||||||
|
* context with — so a request that crosses to a teapot arrives carrying the id it already had,
|
||||||
|
* and its events on the far side join the same trace instead of starting a new one.
|
||||||
|
*/
|
||||||
export function envelopeFrom(ctx: any): RequestEnvelope {
|
export function envelopeFrom(ctx: any): RequestEnvelope {
|
||||||
|
const req = ctx?.req;
|
||||||
|
const correlation = { requestId: req?.requestId, traceId: req?.traceId };
|
||||||
|
|
||||||
return {
|
return {
|
||||||
method: ctx?.req?.method ?? ctx?.method ?? 'GET',
|
method: req?.method ?? ctx?.method ?? 'GET',
|
||||||
params: ctx?.params ?? {},
|
params: ctx?.params ?? {},
|
||||||
query: ctx?.query ?? {},
|
query: ctx?.query ?? {},
|
||||||
body: ctx?.body,
|
body: ctx?.body,
|
||||||
headers: ctx?.headers ?? {},
|
headers: ctx?.headers ?? {},
|
||||||
|
url: req?.url,
|
||||||
|
// omitted rather than sent empty: an envelope with no identity should look like one
|
||||||
|
...(correlation.requestId || correlation.traceId ? { correlation } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+53
-1
@@ -9,6 +9,7 @@ import { isHttpError } from '../signals';
|
|||||||
import {
|
import {
|
||||||
encode,
|
encode,
|
||||||
decode,
|
decode,
|
||||||
|
untransportable,
|
||||||
MESH_PROTOCOL_VERSION,
|
MESH_PROTOCOL_VERSION,
|
||||||
type Manifest,
|
type Manifest,
|
||||||
type RequestEnvelope,
|
type RequestEnvelope,
|
||||||
@@ -19,6 +20,28 @@ import {
|
|||||||
/** WebSocket path where a teapot exposes its mesh control channel. */
|
/** WebSocket path where a teapot exposes its mesh control channel. */
|
||||||
export const MESH_CONTROL_PATH = '/__mesh__/control';
|
export const MESH_CONTROL_PATH = '/__mesh__/control';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How long an unauthenticated peer may hold the control channel open before it is hung up on.
|
||||||
|
*
|
||||||
|
* The teacup has always bounded its side of the handshake; the teapot had no equivalent, so a peer
|
||||||
|
* could connect and simply never send `hello`, holding a socket indefinitely without proving
|
||||||
|
* anything. Generous on purpose — this is a deadline against silence, not a latency budget.
|
||||||
|
*/
|
||||||
|
const HANDSHAKE_TIMEOUT_MS = 10_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Largest control frame the teapot will parse, in characters.
|
||||||
|
*
|
||||||
|
* `decode` runs `JSON.parse` on peer-controlled input, and until the handshake succeeds that peer
|
||||||
|
* is *unauthenticated* — so without a cap, anyone who can reach the port can make the process parse
|
||||||
|
* as much as its WebSocket layer will accept (100 MiB under the `ws` package's defaults, and no
|
||||||
|
* documented ceiling on the platform sockets Deno and Bun provide).
|
||||||
|
*
|
||||||
|
* Sized above the 1 MB default body limit an RPC can legitimately carry, with room for the JSON
|
||||||
|
* overhead of the envelope around it.
|
||||||
|
*/
|
||||||
|
const MAX_FRAME_CHARS = 4_000_000;
|
||||||
|
|
||||||
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
|
/** Assemble a {@link Manifest} from exported provider/step tokens and buffered routes. */
|
||||||
export function buildManifest(args: {
|
export function buildManifest(args: {
|
||||||
providers: string[]; // exported provider tokens (app-scope)
|
providers: string[]; // exported provider tokens (app-scope)
|
||||||
@@ -133,6 +156,19 @@ async function handleRpc(
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes);
|
const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes);
|
||||||
|
// Checked here, on the side that still holds the real value. Past `encode` the evidence is
|
||||||
|
// gone: JSON turns a pool into `{}`, which arrives looking alive and fails at the call site.
|
||||||
|
const offender = untransportable(result);
|
||||||
|
|
||||||
|
if (offender) {
|
||||||
|
const error: any = new Error(
|
||||||
|
`mesh cannot transport '${name}': ${offender.path} is ${offender.what}. ` +
|
||||||
|
'The wire is JSON, so a mesh export carries data, never behaviour — export what the ' +
|
||||||
|
'handle produces rather than the handle.',
|
||||||
|
);
|
||||||
|
error.status = 500;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
|
socket.send(encode({ type: 'rpc-res', id, ok: true, result }));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -151,19 +187,34 @@ async function serveFrames(
|
|||||||
exportedRoutes: Set<string>,
|
exportedRoutes: Set<string>,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
let authed = false;
|
let authed = false;
|
||||||
|
// Armed before the loop, and cleared by the handshake. An unauthenticated peer that simply
|
||||||
|
// says nothing is indistinguishable from a slow one until this fires.
|
||||||
|
const handshakeTimer = setTimeout(() => {
|
||||||
|
if (!authed) socket.close(1008, 'mesh handshake timeout');
|
||||||
|
}, HANDSHAKE_TIMEOUT_MS);
|
||||||
|
handshakeTimer.unref?.();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for await (const data of socket.inbound) {
|
for await (const data of socket.inbound) {
|
||||||
|
const raw = String(data);
|
||||||
|
|
||||||
|
// Checked before `decode`, because decoding is the expensive part being defended.
|
||||||
|
if (raw.length > MAX_FRAME_CHARS) {
|
||||||
|
socket.close(1009, 'mesh frame too large');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
let frame: Frame;
|
let frame: Frame;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
frame = decode(String(data));
|
frame = decode(raw);
|
||||||
} catch {
|
} catch {
|
||||||
continue; // undecodable frames are ignored, as before
|
continue; // undecodable frames are ignored, as before
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!authed) {
|
if (!authed) {
|
||||||
authed = handleHandshake(socket, frame, deps);
|
authed = handleHandshake(socket, frame, deps);
|
||||||
|
if (authed) clearTimeout(handshakeTimer);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,6 +234,7 @@ async function serveFrames(
|
|||||||
} catch {
|
} catch {
|
||||||
/* socket failed; the disconnect emit below is the same signal a clean close gives */
|
/* socket failed; the disconnect emit below is the same signal a clean close gives */
|
||||||
} finally {
|
} finally {
|
||||||
|
clearTimeout(handshakeTimer);
|
||||||
deps.bus?.emit('mesh:disconnect', { name: 'teapot' });
|
deps.bus?.emit('mesh:disconnect', { name: 'teapot' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
// Reconnection under the real Bun runtime.
|
||||||
|
//
|
||||||
|
// Separate from the Node and Deno suites deliberately. Bun's WebSocket lifecycle is a third
|
||||||
|
// implementation — its socket events land on a server-level handler rather than the socket — and a
|
||||||
|
// link that swaps its socket underneath a live graph is precisely where three implementations
|
||||||
|
// stop behaving the same. Defining this on Node and hoping is not enough.
|
||||||
|
//
|
||||||
|
// Run with: npm run test:bun
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { test, expect } from 'bun:test';
|
||||||
|
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||||
|
import { serveBun } from '../../src/bun.ts';
|
||||||
|
|
||||||
|
const SECRET = 's3cr3t';
|
||||||
|
|
||||||
|
@Provider({ provides: 'config', export: true })
|
||||||
|
class Config {
|
||||||
|
provide() {
|
||||||
|
return { config: { runtime: 'bun' } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Step({ provides: 'auth', needs: [], export: true })
|
||||||
|
class Auth {
|
||||||
|
run(ctx: any) {
|
||||||
|
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
@Route('/local')
|
||||||
|
class LocalCtl {
|
||||||
|
@Get('/who')
|
||||||
|
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||||
|
return { config, auth };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
/** A port nobody is on, so the teapot can be killed and brought back at the same address. */
|
||||||
|
function freePort(): number {
|
||||||
|
const probe = Bun.serve({ port: 0, fetch: () => new Response('') });
|
||||||
|
const { port } = probe;
|
||||||
|
probe.stop(true);
|
||||||
|
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Boot a teapot on a fixed port; the handle kills it and leaves the port free again. */
|
||||||
|
function startTeapot(port: number) {
|
||||||
|
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
|
const server = serveBun(app, { port });
|
||||||
|
|
||||||
|
return {
|
||||||
|
stop: async () => {
|
||||||
|
server.stop(true);
|
||||||
|
await app.close();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
|
||||||
|
test('mesh on Bun: a teacup reconnects to a teapot that came back', async () => {
|
||||||
|
const port = freePort();
|
||||||
|
let teapot = startTeapot(port);
|
||||||
|
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
mesh: {
|
||||||
|
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
|
||||||
|
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
|
||||||
|
heartbeatMs: 50,
|
||||||
|
timeoutMs: 2000,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const before = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
|
||||||
|
expect(before.status).toBe(200);
|
||||||
|
|
||||||
|
await teapot.stop();
|
||||||
|
await settle(100);
|
||||||
|
|
||||||
|
// the down window answers immediately rather than waiting out timeoutMs
|
||||||
|
const down = await teacup.fetch(new Request('http://x/api/local/who'));
|
||||||
|
expect(down.status).toBe(503);
|
||||||
|
|
||||||
|
teapot = startTeapot(port);
|
||||||
|
await settle(400);
|
||||||
|
|
||||||
|
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
|
||||||
|
expect(after.status).toBe(200);
|
||||||
|
expect((await after.json()).auth).toEqual({ token: 'xyz' });
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
await teapot.stop();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
// The teapot's frame loop under Deno, driven by a raw client rather than by another green-tea.
|
||||||
|
//
|
||||||
|
// The two guards here are close-code behaviour, and close codes are exactly where the runtimes
|
||||||
|
// have already differed once — a client may only send 1000 or 3000-4999, which is why the mesh
|
||||||
|
// heartbeat uses 4011 instead of 1011. Server-side closes deserve the same suspicion.
|
||||||
|
//
|
||||||
|
// Run with: npm run test:deno
|
||||||
|
import 'npm:reflect-metadata';
|
||||||
|
import { assertEquals } from 'jsr:@std/assert';
|
||||||
|
import { createApp, Step, Module } from '../../src/index.ts';
|
||||||
|
import { serveDeno } from '../../src/deno.ts';
|
||||||
|
|
||||||
|
@Step({ provides: 'auth', needs: [], export: true })
|
||||||
|
class Auth {
|
||||||
|
run() {
|
||||||
|
return { auth: { ok: true } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', steps: [Auth] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
async function startTeapot() {
|
||||||
|
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||||
|
let port = 0;
|
||||||
|
const server = serveDeno(app, { port: 0, onListen: (addr) => (port = addr.port) });
|
||||||
|
await new Promise((r) => setTimeout(r, 50));
|
||||||
|
|
||||||
|
return { port: () => port, stop: async () => { await server.shutdown(); await app.close(); } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Opens a raw control-channel socket and resolves with how it ended. */
|
||||||
|
function rawClient(port: number, send: string): Promise<{ code: number }> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${port}/__mesh__/control`);
|
||||||
|
ws.onopen = () => ws.send(send);
|
||||||
|
ws.onclose = (event) => resolve({ code: event.code });
|
||||||
|
ws.onerror = () => reject(new Error('socket errored'));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: the teapot hangs up on an oversized control frame', async () => {
|
||||||
|
const teapot = await startTeapot();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// over the 4,000,000-character cap, and sent by a peer that has not authenticated
|
||||||
|
const oversized = `{"type":"hello","v":1,"secret":"${'a'.repeat(4_000_001)}"}`;
|
||||||
|
const { code } = await rawClient(teapot.port(), oversized);
|
||||||
|
|
||||||
|
assertEquals(code, 1009);
|
||||||
|
} finally {
|
||||||
|
await teapot.stop();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
// Reconnection under the real Deno runtime.
|
||||||
|
//
|
||||||
|
// This exists separately from the Node suite because the teacup's WebSocket client is a different
|
||||||
|
// implementation here — Deno's global `WebSocket`, not the `ws` package — and a link that swaps its
|
||||||
|
// socket underneath a live graph is exactly the kind of thing that works on one and not the other.
|
||||||
|
//
|
||||||
|
// Run with: npm run test:deno
|
||||||
|
import 'npm:reflect-metadata';
|
||||||
|
import { assertEquals } from 'jsr:@std/assert';
|
||||||
|
import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index.ts';
|
||||||
|
import { serveDeno } from '../../src/deno.ts';
|
||||||
|
|
||||||
|
const SECRET = 's3cr3t';
|
||||||
|
|
||||||
|
@Provider({ provides: 'config', export: true })
|
||||||
|
class Config {
|
||||||
|
provide() {
|
||||||
|
return { config: { runtime: 'deno' } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Step({ provides: 'auth', needs: [], export: true })
|
||||||
|
class Auth {
|
||||||
|
run(ctx: any) {
|
||||||
|
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
@Route('/local')
|
||||||
|
class LocalCtl {
|
||||||
|
@Get('/who')
|
||||||
|
who(@needs('config') config: any, @needs('auth') auth: any) {
|
||||||
|
return { config, auth };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
/** A port nobody is on, so the teapot can be killed and brought back at the same address. */
|
||||||
|
function freePort(): number {
|
||||||
|
const probe = Deno.listen({ port: 0 });
|
||||||
|
const { port } = probe.addr as Deno.NetAddr;
|
||||||
|
probe.close();
|
||||||
|
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Boot a teapot on a fixed port; the returned handle can kill it and leave the port free again. */
|
||||||
|
async function startTeapot(port: number) {
|
||||||
|
const app = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } });
|
||||||
|
const server = serveDeno(app, { port });
|
||||||
|
await new Promise((r) => setTimeout(r, 50));
|
||||||
|
|
||||||
|
return {
|
||||||
|
stop: async () => {
|
||||||
|
await server.shutdown();
|
||||||
|
await app.close();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
|
||||||
|
Deno.test('mesh on Deno: a teacup reconnects to a teapot that came back', async () => {
|
||||||
|
const port = freePort();
|
||||||
|
let teapot = await startTeapot(port);
|
||||||
|
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
mesh: {
|
||||||
|
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: SECRET }],
|
||||||
|
reconnect: { initialDelayMs: 20, maxDelayMs: 60 },
|
||||||
|
heartbeatMs: 50,
|
||||||
|
timeoutMs: 2000,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const before = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'abc' } }));
|
||||||
|
assertEquals(before.status, 200);
|
||||||
|
|
||||||
|
await teapot.stop();
|
||||||
|
await settle(100);
|
||||||
|
|
||||||
|
// the down window answers immediately rather than waiting out timeoutMs
|
||||||
|
const down = await teacup.fetch(new Request('http://x/api/local/who'));
|
||||||
|
assertEquals(down.status, 503);
|
||||||
|
|
||||||
|
teapot = await startTeapot(port);
|
||||||
|
await settle(400);
|
||||||
|
|
||||||
|
const after = await teacup.fetch(new Request('http://x/api/local/who', { headers: { 'x-token': 'xyz' } }));
|
||||||
|
assertEquals(after.status, 200);
|
||||||
|
assertEquals((await after.json()).auth, { token: 'xyz' });
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
await teapot.stop();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
||||||
|
|
||||||
|
@Step({ provides: 'auth', needs: [], export: true })
|
||||||
|
class Auth {
|
||||||
|
run() {
|
||||||
|
return { auth: { ok: true } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', steps: [Auth] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
@Route('/local')
|
||||||
|
class LocalCtl {
|
||||||
|
@Get('/who')
|
||||||
|
who(@needs('auth') auth: any) {
|
||||||
|
return { auth };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
const collect = () => {
|
||||||
|
const lines: string[] = [];
|
||||||
|
return { lines, logger: { debug() {}, info() {}, warn: (m: string) => lines.push(m), error: (m: string) => lines.push(m) } };
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('mesh boot retry', () => {
|
||||||
|
it('waits for a teapot that starts late, rather than failing the deploy', async () => {
|
||||||
|
const port = await new Promise<number>((resolve) => {
|
||||||
|
const probe = require('node:net').createServer();
|
||||||
|
probe.listen(0, () => {
|
||||||
|
const { port: p } = probe.address();
|
||||||
|
probe.close(() => resolve(p));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const { lines, logger } = collect();
|
||||||
|
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
logger,
|
||||||
|
mesh: {
|
||||||
|
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }],
|
||||||
|
timeoutMs: 500,
|
||||||
|
bootTimeoutMs: 4000,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// the teapot arrives *after* the teacup has already started trying
|
||||||
|
const pending = teacup.fetch(new Request('http://x/api/local/who'));
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||||
|
await new Promise((r) => setTimeout(r, 300));
|
||||||
|
const server = await teapot.listen(port);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await pending;
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(lines.some((l) => l.includes('of boot budget left'))).toBe(true);
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
await teapot.close();
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
}, 15_000);
|
||||||
|
|
||||||
|
it('still fails the boot once the budget is spent — a needed provider is not optional', async () => {
|
||||||
|
const { lines, logger } = collect();
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
logger,
|
||||||
|
mesh: {
|
||||||
|
teapots: [{ url: 'ws://127.0.0.1:1/__mesh__/control', secret: 'good' }],
|
||||||
|
timeoutMs: 200,
|
||||||
|
bootTimeoutMs: 600,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
|
||||||
|
expect(lines.some((l) => l.includes('giving up after'))).toBe(true);
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
}
|
||||||
|
}, 15_000);
|
||||||
|
|
||||||
|
it('does not retry a wrong secret — the teapot refused, and it will refuse again', async () => {
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||||
|
const server = await teapot.listen(0);
|
||||||
|
const port = (server.address() as { port: number }).port;
|
||||||
|
const { lines, logger } = collect();
|
||||||
|
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
logger,
|
||||||
|
mesh: {
|
||||||
|
teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'WRONG' }],
|
||||||
|
timeoutMs: 500,
|
||||||
|
bootTimeoutMs: 30_000,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const started = Date.now();
|
||||||
|
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
|
||||||
|
// with a 30s budget, retrying would have taken 30s to reach the same error
|
||||||
|
expect(Date.now() - started).toBeLessThan(3000);
|
||||||
|
expect(lines.some((l) => l.includes('refused this peer'))).toBe(true);
|
||||||
|
expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
await teapot.close();
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
}, 40_000);
|
||||||
|
|
||||||
|
it('bootTimeoutMs: 0 makes one attempt, as before', async () => {
|
||||||
|
const { lines, logger } = collect();
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
logger,
|
||||||
|
mesh: {
|
||||||
|
teapots: [{ url: 'ws://127.0.0.1:1/__mesh__/control', secret: 'good' }],
|
||||||
|
timeoutMs: 200,
|
||||||
|
bootTimeoutMs: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(/mesh/);
|
||||||
|
expect(lines.filter((l) => l.includes('of boot budget left'))).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
}
|
||||||
|
}, 15_000);
|
||||||
|
});
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { WebSocketServer } from 'ws';
|
||||||
|
import { connectLink } from '../../src/mesh/link';
|
||||||
|
import { envelopeFrom } from '../../src/mesh/teacup';
|
||||||
|
import { createMeshControl } from '../../src/mesh/teapot';
|
||||||
|
import { encode, decode, MESH_PROTOCOL_VERSION, type RequestEnvelope } from '../../src/mesh/protocol';
|
||||||
|
import { Bus } from '../../src/bus';
|
||||||
|
import { createApp, Step, Route, Get, Module, needs } from '../../src/index';
|
||||||
|
|
||||||
|
@Step({ provides: 'auth', needs: [], export: true })
|
||||||
|
class Auth {
|
||||||
|
run(ctx: any) {
|
||||||
|
return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', steps: [Auth] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
@Route('/local')
|
||||||
|
class LocalCtl {
|
||||||
|
@Get('/who')
|
||||||
|
who(@needs('auth') auth: any) {
|
||||||
|
return { auth };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
const V = MESH_PROTOCOL_VERSION;
|
||||||
|
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
|
||||||
|
|
||||||
|
/** Drives a control handler with a scripted socket, capturing what it sends and how it closes. */
|
||||||
|
function fakeSocket() {
|
||||||
|
const queue: string[] = [];
|
||||||
|
let push: ((v: string) => void) | undefined;
|
||||||
|
let done = false;
|
||||||
|
const sent: string[] = [];
|
||||||
|
const closes: Array<{ code?: number; reason?: string }> = [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
sent,
|
||||||
|
closes,
|
||||||
|
feed: (frame: string) => (push ? push(frame) : queue.push(frame)),
|
||||||
|
end: () => {
|
||||||
|
done = true;
|
||||||
|
push?.('');
|
||||||
|
},
|
||||||
|
socket: {
|
||||||
|
get isOpen() {
|
||||||
|
return !done;
|
||||||
|
},
|
||||||
|
abort: new AbortController().signal,
|
||||||
|
send: (data: string) => sent.push(data),
|
||||||
|
close: (code?: number, reason?: string) => {
|
||||||
|
closes.push({ code, reason });
|
||||||
|
done = true;
|
||||||
|
},
|
||||||
|
terminate: () => undefined,
|
||||||
|
inbound: {
|
||||||
|
async *[Symbol.asyncIterator]() {
|
||||||
|
while (!done) {
|
||||||
|
if (queue.length) {
|
||||||
|
yield queue.shift()!;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const next = await new Promise<string>((resolve) => (push = resolve));
|
||||||
|
if (done) return;
|
||||||
|
yield next;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
describe('envelopeFrom', () => {
|
||||||
|
it('carries the url and the caller correlation off ctx.req', () => {
|
||||||
|
const envelope = envelopeFrom({
|
||||||
|
req: { method: 'POST', url: '/orders/7?x=1', requestId: 'req-1', traceId: 'trace-1' },
|
||||||
|
params: { id: '7' },
|
||||||
|
query: { x: '1' },
|
||||||
|
headers: { 'x-token': 'abc' },
|
||||||
|
body: { total: 10 },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(envelope.url).toBe('/orders/7?x=1');
|
||||||
|
expect(envelope.correlation).toEqual({ requestId: 'req-1', traceId: 'trace-1' });
|
||||||
|
expect(envelope.method).toBe('POST');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits correlation entirely when the caller has none, rather than sending an empty one', () => {
|
||||||
|
expect(envelopeFrom({ req: { method: 'GET', url: '/x' } })).not.toHaveProperty('correlation');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('mesh rpc errors', () => {
|
||||||
|
it('reports the token that failed, not the wire id', async () => {
|
||||||
|
const wss = new WebSocketServer({ port: 0 });
|
||||||
|
wss.on('connection', (ws) => {
|
||||||
|
let authed = false;
|
||||||
|
ws.on('message', (data) => {
|
||||||
|
const frame = decode(data.toString());
|
||||||
|
if (!authed && frame.type === 'hello') {
|
||||||
|
authed = true;
|
||||||
|
ws.send(encode({ type: 'manifest', v: V, scopes: [{ token: 'billing', scope: 'request' }], routes: [] }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (frame.type === 'rpc-req') {
|
||||||
|
ws.send(encode({ type: 'rpc-res', id: frame.id, ok: false, error: { message: 'nope', status: 403 } }));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
const port = (wss.address() as { port: number }).port;
|
||||||
|
const bus = new Bus();
|
||||||
|
const seen: string[] = [];
|
||||||
|
bus.on('mesh:rpc:error', (payload) => seen.push(String(payload.name)));
|
||||||
|
|
||||||
|
const link = await connectLink({ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'x', bus });
|
||||||
|
await expect(link.rpc('scope', 'billing', env)).rejects.toMatchObject({ status: 403 });
|
||||||
|
|
||||||
|
// used to be "0" — the per-link counter — which no operator could match to anything
|
||||||
|
expect(seen).toEqual(['billing']);
|
||||||
|
link.close();
|
||||||
|
wss.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('teapot hardening', () => {
|
||||||
|
const control = () =>
|
||||||
|
createMeshControl({
|
||||||
|
secret: 'good',
|
||||||
|
manifest: { scopes: [{ token: 'auth', scope: 'request' }], routes: [] },
|
||||||
|
resolveScope: async () => 'value',
|
||||||
|
resolveRoute: async () => ({ status: 200, headers: {}, body: '' }),
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hangs up on an oversized frame before parsing it', async () => {
|
||||||
|
const fake = fakeSocket();
|
||||||
|
const running = control().handle(fake.socket as never);
|
||||||
|
|
||||||
|
fake.feed(`{"type":"hello","v":${V},"secret":"${'a'.repeat(4_000_001)}"}`);
|
||||||
|
await running;
|
||||||
|
|
||||||
|
expect(fake.closes[0]?.code).toBe(1009);
|
||||||
|
// never answered: the frame died before decode, so no manifest went out
|
||||||
|
expect(fake.sent).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serves normally when a frame is under the cap', async () => {
|
||||||
|
const fake = fakeSocket();
|
||||||
|
const running = control().handle(fake.socket as never);
|
||||||
|
|
||||||
|
fake.feed(encode({ type: 'hello', v: V, secret: 'good' }));
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
fake.end();
|
||||||
|
await running;
|
||||||
|
|
||||||
|
expect(JSON.parse(fake.sent[0]).type).toBe('manifest');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('correlation across the mesh', () => {
|
||||||
|
it("the teapot's own events carry the caller's request id, not one it opened itself", async () => {
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||||
|
const server = await teapot.listen(0);
|
||||||
|
const port = (server.address() as { port: number }).port;
|
||||||
|
|
||||||
|
// what the teapot reports about its *own* work — the far end of the trace
|
||||||
|
const far: Array<string | undefined> = [];
|
||||||
|
teapot.bus.on('request:step:leave', (payload) => far.push(payload.requestId));
|
||||||
|
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }] },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// the id a gateway would have set; core adopts it rather than minting a new one
|
||||||
|
const res = await teacup.fetch(
|
||||||
|
new Request('http://x/api/local/who', { headers: { 'x-request-id': 'from-the-gateway' } }),
|
||||||
|
);
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
|
expect(far.length).toBeGreaterThan(0);
|
||||||
|
// before this change the teapot saw no id at all, so a request crossing the mesh
|
||||||
|
// became two unrelated investigations
|
||||||
|
expect(new Set(far)).toEqual(new Set(['from-the-gateway']));
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
await teapot.close();
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('cleartext secret warning', () => {
|
||||||
|
it('warns for a remote ws:// teapot, and stays quiet for loopback', async () => {
|
||||||
|
const remote: string[] = [];
|
||||||
|
const logger = { debug() {}, info() {}, warn: (m: string) => remote.push(m), error() {} };
|
||||||
|
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
|
||||||
|
const server = await teapot.listen(0);
|
||||||
|
const port = (server.address() as { port: number }).port;
|
||||||
|
|
||||||
|
// loopback: there is no network path, so nothing to warn about
|
||||||
|
const local = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
logger,
|
||||||
|
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'good' }] },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await local.fetch(new Request('http://x/api/local/who'));
|
||||||
|
expect(remote.filter((m) => m.includes('not encrypted'))).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
await local.close();
|
||||||
|
await teapot.close();
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('warns when the secret would cross a network in cleartext', async () => {
|
||||||
|
const warned: string[] = [];
|
||||||
|
const logger = { debug() {}, info() {}, warn: (m: string) => warned.push(m), error() {} };
|
||||||
|
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
logger,
|
||||||
|
// unreachable on purpose: the warning is emitted before the connection is attempted,
|
||||||
|
// because it is about what would be sent, not about what succeeded
|
||||||
|
mesh: { teapots: [{ url: 'ws://10.255.255.1:9/__mesh__/control', secret: 'good' }], timeoutMs: 300 },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow();
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(warned.some((m) => m.includes('not encrypted') && m.includes('wss://'))).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { WebSocketServer } from 'ws';
|
||||||
|
import { connectLink, missingFromManifest } from '../../src/mesh/link';
|
||||||
|
import { encode, decode, MESH_PROTOCOL_VERSION, type Manifest } from '../../src/mesh/protocol';
|
||||||
|
|
||||||
|
const V = MESH_PROTOCOL_VERSION;
|
||||||
|
const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A teapot bound to a fixed port so it can be killed and restarted at the same URL — which is the
|
||||||
|
* whole point here: reconnection means returning to the *same* teapot, not finding another one.
|
||||||
|
* Its manifest is swappable so a restart can come back exporting something different.
|
||||||
|
*/
|
||||||
|
function teapotOn(port: number, manifest: Manifest, answer: unknown = { ok: true }) {
|
||||||
|
const wss = new WebSocketServer({ port });
|
||||||
|
wss.on('connection', (ws) => {
|
||||||
|
let authed = false;
|
||||||
|
ws.on('message', (d) => {
|
||||||
|
const frame = decode(d.toString());
|
||||||
|
if (!authed) {
|
||||||
|
if (frame.type === 'hello' && frame.secret === 'good') {
|
||||||
|
authed = true;
|
||||||
|
ws.send(encode({ type: 'manifest', v: V, scopes: manifest.scopes, routes: manifest.routes }));
|
||||||
|
} else ws.close(1008);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (frame.type === 'ping') ws.send(encode({ type: 'pong' }));
|
||||||
|
if (frame.type === 'rpc-req') ws.send(encode({ type: 'rpc-res', id: frame.id, ok: true, result: answer }));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Promise<{ close: () => Promise<void> }>((resolve) => {
|
||||||
|
wss.on('listening', () =>
|
||||||
|
resolve({
|
||||||
|
close: () =>
|
||||||
|
new Promise<void>((done) => {
|
||||||
|
for (const client of wss.clients) client.terminate();
|
||||||
|
wss.close(() => done());
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A free port, taken by opening and immediately closing a server on port 0. */
|
||||||
|
async function freePort(): Promise<number> {
|
||||||
|
const probe = new WebSocketServer({ port: 0 });
|
||||||
|
await new Promise((r) => probe.on('listening', r));
|
||||||
|
const port = (probe.address() as { port: number }).port;
|
||||||
|
await new Promise((r) => probe.close(r));
|
||||||
|
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const url = (port: number) => `ws://127.0.0.1:${port}/__mesh__/control`;
|
||||||
|
const SCOPES: Manifest = { scopes: [{ token: 'auth', scope: 'app' }], routes: [] };
|
||||||
|
const fast = { initialDelayMs: 20, maxDelayMs: 60 };
|
||||||
|
|
||||||
|
describe('mesh reconnection', () => {
|
||||||
|
it('reconnects to the same teapot and serves again', async () => {
|
||||||
|
const port = await freePort();
|
||||||
|
let teapot = await teapotOn(port, SCOPES);
|
||||||
|
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
|
||||||
|
|
||||||
|
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: true });
|
||||||
|
|
||||||
|
await teapot.close();
|
||||||
|
await settle(50);
|
||||||
|
// the window where the link is down answers immediately rather than after timeoutMs
|
||||||
|
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||||
|
|
||||||
|
teapot = await teapotOn(port, SCOPES, { ok: 'again' });
|
||||||
|
await settle(300);
|
||||||
|
|
||||||
|
expect(await link.rpc('scope', 'auth', env)).toEqual({ ok: 'again' });
|
||||||
|
link.close();
|
||||||
|
await teapot.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuses a returning teapot whose manifest lost a token the graph needs', async () => {
|
||||||
|
const port = await freePort();
|
||||||
|
let teapot = await teapotOn(port, SCOPES);
|
||||||
|
const warnings: string[] = [];
|
||||||
|
const logger = { debug() {}, info() {}, warn: (m: string) => warnings.push(m), error() {} };
|
||||||
|
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50, logger });
|
||||||
|
|
||||||
|
await teapot.close();
|
||||||
|
await settle(50);
|
||||||
|
|
||||||
|
// comes back exporting nothing — the graph was validated against 'auth' at boot
|
||||||
|
teapot = await teapotOn(port, { scopes: [], routes: [] });
|
||||||
|
await settle(300);
|
||||||
|
|
||||||
|
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||||
|
expect(warnings.some((w) => w.includes("app-scope 'auth'") && w.includes('refusing to reconnect'))).toBe(true);
|
||||||
|
// logged once per distinct manifest, not once per attempt
|
||||||
|
expect(warnings.filter((w) => w.includes('refusing to reconnect')).length).toBe(1);
|
||||||
|
|
||||||
|
link.close();
|
||||||
|
await teapot.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops reconnecting once the application closes the link', async () => {
|
||||||
|
const port = await freePort();
|
||||||
|
const teapot = await teapotOn(port, SCOPES);
|
||||||
|
const link = await connectLink({ url: url(port), secret: 'good', reconnect: fast, heartbeatMs: 50 });
|
||||||
|
|
||||||
|
await teapot.close();
|
||||||
|
link.close();
|
||||||
|
|
||||||
|
// if close() were not terminal, the link would reconnect to the teapot that comes back here —
|
||||||
|
// which is what would leave app.close() with a process that cannot exit
|
||||||
|
const revived = await teapotOn(port, SCOPES, { ok: 'revived' });
|
||||||
|
await settle(300);
|
||||||
|
|
||||||
|
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||||
|
await revived.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reconnect: false keeps the old fail-once behaviour', async () => {
|
||||||
|
const port = await freePort();
|
||||||
|
let teapot = await teapotOn(port, SCOPES);
|
||||||
|
const link = await connectLink({ url: url(port), secret: 'good', reconnect: false, heartbeatMs: 50 });
|
||||||
|
|
||||||
|
await teapot.close();
|
||||||
|
teapot = await teapotOn(port, SCOPES);
|
||||||
|
await settle(300);
|
||||||
|
|
||||||
|
await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 503 });
|
||||||
|
link.close();
|
||||||
|
await teapot.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('missingFromManifest', () => {
|
||||||
|
const booted: Manifest = {
|
||||||
|
scopes: [
|
||||||
|
{ token: 'auth', scope: 'request' },
|
||||||
|
{ token: 'config', scope: 'app' },
|
||||||
|
],
|
||||||
|
routes: [{ method: 'GET', pattern: '/svc/:id' }],
|
||||||
|
};
|
||||||
|
|
||||||
|
it('accepts an identical manifest', () => {
|
||||||
|
expect(missingFromManifest(booted, booted)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts extra exports — the graph is fixed at boot and nothing new is spliced', () => {
|
||||||
|
const wider: Manifest = {
|
||||||
|
scopes: [...booted.scopes, { token: 'billing', scope: 'app' }],
|
||||||
|
routes: [...booted.routes, { method: 'POST', pattern: '/svc/new' }],
|
||||||
|
};
|
||||||
|
expect(missingFromManifest(booted, wider)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts a route parameter that was only renamed', () => {
|
||||||
|
const renamed: Manifest = { scopes: booted.scopes, routes: [{ method: 'GET', pattern: '/svc/:name' }] };
|
||||||
|
expect(missingFromManifest(booted, renamed)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports a token whose lifetime changed, since the graph resolved it under the old one', () => {
|
||||||
|
const flipped: Manifest = {
|
||||||
|
scopes: [
|
||||||
|
{ token: 'auth', scope: 'app' },
|
||||||
|
{ token: 'config', scope: 'app' },
|
||||||
|
],
|
||||||
|
routes: booted.routes,
|
||||||
|
};
|
||||||
|
expect(missingFromManifest(booted, flipped)).toEqual(["request-scope 'auth'"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reports a missing route by method and pattern', () => {
|
||||||
|
const routeless: Manifest = { scopes: booted.scopes, routes: [] };
|
||||||
|
expect(missingFromManifest(booted, routeless)).toEqual(["route 'GET /svc/:id'"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { createApp, Provider, Route, Get, Module, needs } from '../../src/index';
|
||||||
|
import { untransportable } from '../../src/mesh/protocol';
|
||||||
|
|
||||||
|
describe('untransportable', () => {
|
||||||
|
it('passes the shapes JSON actually round-trips', () => {
|
||||||
|
expect(untransportable({ a: 1, b: 'x', c: true, d: null, e: [1, { f: 2 }] })).toBeUndefined();
|
||||||
|
expect(untransportable([])).toBeUndefined();
|
||||||
|
expect(untransportable('plain')).toBeUndefined();
|
||||||
|
expect(untransportable(Object.create(null))).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('names the class whose identity JSON would discard, and where it sits', () => {
|
||||||
|
class RemotePool {
|
||||||
|
query() {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(untransportable({ db: new RemotePool() })).toEqual({ path: 'result.db', what: 'a RemotePool instance' });
|
||||||
|
expect(untransportable({ seen: new Map() })).toEqual({ path: 'result.seen', what: 'a Map instance' });
|
||||||
|
// refused rather than quietly delivered as a string, which is the same silent difference smaller
|
||||||
|
expect(untransportable({ at: new Date() })).toEqual({ path: 'result.at', what: 'a Date instance' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('finds behaviour nested in arrays and objects', () => {
|
||||||
|
expect(untransportable({ list: [1, { run: () => 1 }] })).toEqual({
|
||||||
|
path: 'result.list[1].run',
|
||||||
|
what: 'a function',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives up rather than rejecting a payload too large to check', () => {
|
||||||
|
const huge: Record<string, unknown> = {};
|
||||||
|
for (let i = 0; i < 11_000; i++) huge[`k${i}`] = i;
|
||||||
|
huge.late = () => 1; // past the budget: assumed fine rather than turned into an error
|
||||||
|
|
||||||
|
expect(untransportable(huge)).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
class Pool {
|
||||||
|
query(sql: string) {
|
||||||
|
return `ran:${sql}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provider({ provides: 'db', export: true })
|
||||||
|
class Db {
|
||||||
|
provide() {
|
||||||
|
return { db: new Pool() };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', providers: [Db] })
|
||||||
|
class TeapotModule {}
|
||||||
|
|
||||||
|
@Route('/local')
|
||||||
|
class Ctl {
|
||||||
|
@Get('/use')
|
||||||
|
use(@needs('db') db: any) {
|
||||||
|
return { got: typeof db };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/api', controllers: [Ctl] })
|
||||||
|
class TeacupModule {}
|
||||||
|
|
||||||
|
describe('exporting a handle over the mesh', () => {
|
||||||
|
it('fails with a message naming the token, instead of delivering an empty object', async () => {
|
||||||
|
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'x' } });
|
||||||
|
const server = await teapot.listen(0);
|
||||||
|
const port = (server.address() as { port: number }).port;
|
||||||
|
|
||||||
|
const teacup = createApp({
|
||||||
|
modules: [TeacupModule],
|
||||||
|
experimental: true,
|
||||||
|
mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'x' }] },
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// before this guard: HTTP 200 with `{}` — an object that passes any truthiness check and
|
||||||
|
// then throws "db.query is not a function" somewhere else entirely
|
||||||
|
await expect(teacup.fetch(new Request('http://x/api/local/use'))).rejects.toThrow(
|
||||||
|
/mesh cannot transport 'db'[\s\S]*Pool instance/,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await teacup.close();
|
||||||
|
await teapot.close();
|
||||||
|
server.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user