Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f9e6b19d6 | ||
|
|
7be26fda5c | ||
|
|
e540752f1e | ||
|
|
e86051382d | ||
|
|
b8cb684a6b | ||
|
|
2c838c8753 | ||
|
|
46342a0aa2 |
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
-78
@@ -8,86 +8,15 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
### Changed
|
## [26.8.0-beta.1] - 2026-08-19
|
||||||
|
|
||||||
- **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.
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
|
|
||||||
- **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.
|
|
||||||
|
|
||||||
## [26.8.0-beta.1] - 2026-08-17
|
|
||||||
|
|
||||||
### 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`,
|
||||||
@@ -128,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
|
||||||
@@ -139,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`
|
||||||
@@ -151,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 ▸
|
||||||
@@ -170,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
|
||||||
@@ -193,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
|
||||||
@@ -228,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.
|
||||||
@@ -252,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
|
||||||
@@ -271,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()`,
|
||||||
@@ -293,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.
|
||||||
@@ -115,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);
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -155,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) {
|
||||||
|
|||||||
@@ -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