diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 762ef32..4eef83f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,7 +48,8 @@ jobs: - run: npm run format:check - run: npm run complexity:check - run: npm run typecheck - - run: npm test + # The suite, with v8 coverage printed in the log (#79). Reported only: no threshold gates it yet. + - run: npm run coverage - run: npm run build # The committed reports in api/ are the frozen surface (CARD-22, D20). A PR that changes a # public type fails here until it regenerates them with `npm run api`, so the change shows up diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e1bc6b5..5be9728 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -23,8 +23,14 @@ jobs: with: node-version: '22' registry-url: 'https://registry.npmjs.org' - - run: npm install -g npm@latest # npm >= 11.5.1 is required for OIDC trusted publishing + # Pinned (#78): a permanent publish must not run on whatever npm shipped this morning. >= 11.5.1 + # is required for OIDC trusted publishing. Bump it on purpose, in its own commit. + - run: npm install -g npm@11.21.3 - run: npm ci + # The CI gates that `prepublishOnly` does not run (#78). A tag on a commit that never passed CI + # must not reach a registry, and `main` alone cannot promise that it did. + - run: npm run format:check + - run: npm run api:check # Same scoped gate as ci.yml: only what we ship blocks a publish. With `reflect-metadata` # as the sole runtime dependency, a blocking advisory here is rare and genuinely reaches # users; a build-tooling one never does. The full audit still reports. @@ -42,6 +48,10 @@ jobs: # types, module analysis — and learning about them after npm has published leaves the tag # half-shipped. Seconds, against a failure mode with no clean recovery. - run: deno publish --dry-run + - uses: oven-sh/setup-bun@v2 + - run: npm run test:deno + - run: npm run test:bun + - run: npm run test:edge # A publish sets exactly one dist-tag, and it is the only npm write this workflow can make: # Trusted Publishing's OIDC exchange lives inside `npm publish` and nowhere else, so the token # it produces is rejected by `npm dist-tag` (E401, learned on v26.8.0-beta.1). So the one tag diff --git a/.github/workflows/soak.yml b/.github/workflows/soak.yml new file mode 100644 index 0000000..a533a7f --- /dev/null +++ b/.github/workflows/soak.yml @@ -0,0 +1,29 @@ +name: Soak +# Long-running stability (#80): scripts/soak.mts drives the built app with JSON load, SSE and +# WebSocket churn and a slow SSE subscriber for SOAK_SECONDS, then closes it under load. Fails on +# heap growth, an unhandled rejection or a close() that does not exit 0. Nightly and on demand: +# too slow for every push, and run before a release with workflow_dispatch. +on: + schedule: + - cron: '17 4 * * *' + workflow_dispatch: + inputs: + seconds: + description: Load duration in seconds + default: '300' + +jobs: + soak: + if: ${{ github.server_url == 'https://github.com' }} + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: '22' + - run: npm ci + - run: npm run build + - run: npm run soak + env: + SOAK_SECONDS: ${{ inputs.seconds || '300' }} diff --git a/.github/workflows/stage.yml b/.github/workflows/stage.yml deleted file mode 100644 index 297746b..0000000 --- a/.github/workflows/stage.yml +++ /dev/null @@ -1,51 +0,0 @@ -name: Stage → Verdaccio - -# Staging publish. Runs on GITEA ONLY (the `if` guards against GitHub). Publishes to the -# internal Verdaccio under the `stg` dist-tag, from a `release/**` branch or from a `v*` tag. -# Staging versions are intentionally mutable: an existing prerelease is removed before -# publishing the updated release candidate under the same version. -# -# The tag trigger is what makes creating a tag on Gitea safe. It runs the real publish path — -# the same `prepublishOnly` gate, the same tarball, the same commit — against a registry we -# can overwrite, so the release is proven before the tag is promoted to GitHub, where npm -# allows 72 hours to unpublish and JSR allows nothing at all. -on: - push: - branches: ['release/**'] - tags: ['v*'] - -jobs: - publish-stg: - if: ${{ github.server_url != 'https://github.com' }} - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 - with: - node-version: '22' - - run: npm ci - # Same scoped gate as ci.yml: only what we ship blocks a publish. A `tsup` advisory - # reaches nobody, and holding a release candidate for one is how staging stalls on work - # that has nothing to do with the package. The full audit still reports. - - run: npm audit --omit=dev - - run: npm audit - continue-on-error: true - - name: Validate release candidate - run: npm run prepublishOnly - - name: Publish prerelease to Verdaccio - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }} - run: | - npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN" - VER=$(node -p "require('./package.json').version") - # Staging overwrites the version it publishes, and a stable number that changes - # under an internal consumer is worse than no staging at all. This will need - # revisiting at the first stable release, which is exactly the one most worth - # staging: the answer is probably to stage it under a suffixed version rather - # than to drop the guard. - case "$VER" in - *-*) ;; - *) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;; - esac - npm unpublish "@green-tea/core@$VER" --registry https://npm.svc.zoit.services --force 2>/dev/null || true - npm publish --ignore-scripts --registry https://npm.svc.zoit.services --tag stg diff --git a/AGENTS.md b/AGENTS.md index 9a024a1..76e34af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,21 +29,22 @@ Run the first four before proposing anything as finished. The runtime suites sta ## Two forges -Development lives on GitHub: `develop`, feature branches, pull requests, CI and new issues. A -private Gitea instance keeps only `main` and release tags, pushed there by hand, so a release can -be staged on the internal Verdaccio before it goes public. Issues opened on Gitea before -2026-11-17 stay there until they close; new ones go to GitHub. +Development and releases live on GitHub: `develop`, feature branches, pull requests, CI, new +issues, and the `v*` tags that publish. A private Gitea instance is an archive of `main` and its +tags, copied from GitHub after a release; nothing flows from Gitea to GitHub. Issues opened on +Gitea before 2026-11-17 stay there until they close; new ones go to GitHub. ``` feature/* → develop → main (GitHub, pull requests) │ - v* tag ──┼── GitHub: [release.yml] → npm + JSR - └── Gitea, pushed by hand when staging: [stage.yml] → Verdaccio + v* tag ──── GitHub: [release.yml] → npm + JSR + │ + └── Gitea: archive copy of main and tags, after the release ``` - **`develop`** — active development, and the base of every pull request, outside contributions included. - **`main`** — released code, advanced only by fast-forward from `develop`. -- **Gitea `main` and tags** — a staging copy. Nothing is developed there. A `v*` tag pushed there publishes to Verdaccio, never to a public registry. +- **Gitea `main` and tags** — an archive. Nothing is developed, staged or released from there. Remotes: `origin` is GitHub, `gitea` is the Gitea instance. @@ -99,18 +100,16 @@ Bumping `package.json` and `deno.json` ahead of the tag is fine and necessary *next* publish will be called, and the docs repo's `verify:release` compares the tag against them. A version number is a plan; a changelog heading is a receipt. -**Stage on Verdaccio first when a release warrants it.** Pushing a `v*` tag to GitHub publishes it -to npm and JSR, and JSR never gives a version number back. Pushing the same tag to Gitea first runs -the real publish path against Verdaccio, where a mistake costs only a re-tag: +**The tag is the publish, and JSR never gives a version number back.** Pushing a `v*` tag to +GitHub runs `release.yml`: the CI gates, `deno publish --dry-run`, then npm, then JSR last. There is +no staging registry any more (Verdaccio staging through Gitea ended 2026-11-22), so run +`npm run test:all` on the exact commit you tag before you push it: ```bash -git push gitea main v # optional: Gitea → Verdaccio, reversible git push origin v # GitHub → npm + JSR, permanent on JSR +git push gitea main v # afterwards: archive copy only ``` -The split exists because a mistake caught on Verdaccio costs a re-tag, and the same mistake -caught on JSR costs the version number forever. - **After a beta release, move the channel tag by hand.** A publish sets exactly one dist-tag, and it is the only npm write the release workflow can make — Trusted Publishing's OIDC exchange lives inside `npm publish`, so the token it hands back is rejected by `npm dist-tag` (`E401`, learned the hard way diff --git a/CHANGELOG.md b/CHANGELOG.md index bcf4794..0ec1fd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,162 @@ npm treats versions as semver and semver forbids leading zeros. ## [Unreleased] +## [26.11.0-rc.2] - 2026-11-23 + +### Added + +- **A runnable mesh demo: one REST API across two processes** (#88). `example/mesh/` has a billing + teapot (a private ledger, an exported `balance` step and REST routes) and a shop teacup whose + checkout `@needs('balance')` like a local step and which serves billing's routes. The walkthrough + is in `example/README.md`, and `test/examples/mesh.test.ts` runs it with billing in a real child + process that it kills and restarts: `503` with `retry-after` while billing is down, then automatic + recovery. + +### Security + +- **Mesh: a teapot checks the HTTP method of a route RPC, not just its pattern** + (GHSA-4q43-x4fp-c273). Exporting `GET /items/:id` let an authenticated teacup run an unexported + `DELETE /items/:id`, because the gate matched the pattern and the route ran for whatever method + the peer sent. Mesh is `@experimental`; no API change. + +- **Mesh: an internal error on a teapot no longer reaches the teacup's client verbatim** + (GHSA-gm9h-7577-x57w). A remote step that threw a plain `Error` sent its message across the hop, + and the teacup rendered it in a `500`, so a message holding a connection string or a host reached + the end client; the same throw handled locally renders `Internal Server Error`. The teapot now + sends the real message only for an `HttpError` or a status below 500, and keeps the full error in + its `mesh:rpc:error` event. The "cannot transport" diagnostic is still delivered. No wire change. + +- **A stream's error frame no longer shows the raw error message** (GHSA-235j-fx64-w9p9). When an + SSE or ndjson source threw mid-stream, the client received `err.message` verbatim, while the same + throw on a buffered route renders `Internal Server Error`. The frame now carries an `HttpError`'s + message and `Internal Server Error` for anything else; `stream:error` still gets the full error. + **Behaviour change** for clients that read the text of a non-HTTP error frame. No API change. + +- **With `trustProxy`, `ctx.ip` is the right-most `X-Forwarded-For` entry** (GHSA-53g8-83jp-gvw4), on + every adapter. It was the left-most, which the client writes: a proxy appends the real address, so + a client that sent `X-Forwarded-For: 6.6.6.6` got `ctx.ip === '6.6.6.6'`, defeating per-IP rate + limits, allowlists and audit logs. **Behaviour change** behind a chain of several proxies, where + `ctx.ip` is now the address the last one saw; `cf-connecting-ip` on the edge is unchanged. No API + change. + +- **`cors: { origins: '*', credentials: true }` fails `createApp`** (GHSA-fccm-q62j-48hr). The spec + forbids `*` with credentials, so core echoed every request origin, `null` included, with + `Access-Control-Allow-Credentials: true`, and any site could make credentialed reads. **Breaking** + for an app that set this combination: list the trusted origins, or write the intent as a + predicate (`origins: () => true`) so it is visible. The option type is unchanged. + +- **`static` no longer serves dotfiles** (GHSA-hjcj-hr8v-rfg4). `GET /.env` returned the file, and so + would `/.git/config` or `/.htpasswd` in a public root. A path with any segment starting with `.` is + now a miss (`404`), except under `/.well-known/` (RFC 8615), where only dotfiles stay hidden. + **Behaviour change** for an app that served dotfiles on purpose. No API change. + +- **Node reaps slow-header sockets and dead WebSocket peers promptly** (GHSA-g96c-wq2v-87vc). Node + checks `headersTimeout`/`requestTimeout` only every 30 seconds by default, so a slow-header socket + lived up to 40 seconds, and a WebSocket peer that vanished without closing held its slot forever: a + few hundred of either filled the default `maxConnections` and locked everyone else out. The check + now runs every second, and each Node WebSocket is pinged every 30 seconds and terminated if it + missed the previous ping. Browsers and `ws` clients answer pings on their own. No API change. + +- **Mesh: a `ws://` teapot off loopback fails `createApp` unless `mesh.allowInsecure`** (#86). The + handshake sends the teapot's secret verbatim, and a cleartext link to another machine only logged + a warning. Use `wss://`, or set the new `MeshConfig.allowInsecure: true` when the network already + encrypts the link (a service mesh with mutual TLS); such a teapot is still logged as a warning. + Loopback (`localhost`, `127.0.0.0/8`, `[::1]`) is unaffected. Mesh is `@experimental`: the change + stays within `MeshConfig` (D19). + +- **Mesh on the edge fails with an error that says so** (#87). Mesh cannot run on Cloudflare + Workers, but an app that configured it booted there and failed later, elsewhere. `createApp` with + `mesh` now throws when it detects a Workers isolate, and `edgeHandler` throws for such an app + whatever detection saw. Mesh is `@experimental`; no API change. + +- **The built-in template engine no longer renders what `{{{ }}}` inserted** (GHSA-g86h-3r98-qm66). + It ran `{{ }}` over the output of `{{{ }}}`, so raw content holding `{{ user.passwordHash }}` + rendered the hash. Both forms are now matched in one pass, and keys resolve to own properties only, + so `{{ constructor }}` renders empty instead of a function's source. No API change. + +- **A form field or file named `__proto__` is an ordinary key** (GHSA-g86h-3r98-qm66). With + `bodyDuplicates: 'array'`, `__proto__=a&__proto__=b` replaced the parsed body's prototype, and a + multipart file part with that name did the same to `body.files`. Fields and files are now read and + written as own properties. The effect never reached `Object.prototype`. No API change. + +- **`@query`, `@body`, `@param`, `@header` and `@cookie` read own keys only** + (GHSA-g86h-3r98-qm66). A key the request did not send resolved through the prototype, so + `@query('constructor')` returned `Object.prototype.constructor` instead of `undefined`. No API + change. + +- **Deno, Bun and `app.fetch` honour `X-Forwarded-Proto` under `trustProxy`** + (GHSA-g86h-3r98-qm66), as Node always has. Behind a TLS-terminating proxy they reported + `ctx.protocol === 'http'` and never sent HSTS. No API change. + +- **The README says that a decoded route param can hold `/` and `..`** (GHSA-g86h-3r98-qm66). + `/files/..%2F..%2Fetc` gives `name = "../../etc"`, as in Express. Nothing changes in routing; a + handler that builds a filesystem path from a param must contain it, or constrain the param. + +- **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, + Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket + with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket + hijacking); CORS does not apply to WebSockets. An upgrade is now accepted when it carries no + `Origin` (not a browser), an `Origin` on the same host as the request, or one `cors.origins` + allows. `Origin: null` is refused. The mesh control channel is exempt: it authenticates with its + secret. **Behaviour change:** a browser client served from another origin, or an app behind a proxy + that rewrites `Host`, now needs that origin in `cors.origins`. No API change. + +### Changed + +- **`channel()` buffers 1024 values per subscriber by default, dropping the oldest** (#82). The + default was unbounded, so a slow SSE or WebSocket client on a busy channel or room grew server + memory without limit. Pass `channel({ buffer: Infinity })` for the old behaviour. **Behaviour + change** for a subscriber that falls more than 1024 values behind. WebSocket inbound queues are + unchanged (bounded per frame by `limits`). No API change. + +- **`/__ready__` no longer lists degraded provider names** (#83). The body is + `{"status":"degraded"}`; the names stay in the boot log and `app.degraded()`. **Behaviour + change** for a probe client that read `degraded`. No API change. + +### Security + +- **`/__graph__` pins its three CDN scripts with Subresource Integrity** (#83). A compromised or + altered CDN copy of Cytoscape or dagre is refused by the browser instead of running on the dev + graph page. No API change. + +### Documentation + +- **README: Kubernetes `preStop` drain** (#81), **a BREACH note for `compression`** and the + corrected matcha release line (#84). + +### Fixed + +- **A long-lived SSE or ndjson stream no longer grows the heap with every event** (found by the soak + job, #80). Each event raced the source's `next()` against the connection's close with + `Promise.race`, which leaves a reaction on the close promise per call until the client + disconnects: about 0.4 MB/s of heap on a 1 kHz stream, on Node, Deno, Bun and the edge. One + reaction per stream now. No API change. + +- **Mesh: a remote step call runs only that step and what it needs** (#85). The teapot ran every one + of its steps on each call, so an unexported step's side effects fired once per RPC, and any + unrelated step that threw broke every export. A call now runs the exported step's own closure of + providers and steps, sliced once at boot like a route's. Mesh is `@experimental`; no API change. + +- **Deno, Bun and the edge say when they ignore a Node-only limit** (#76). `limits.maxConnections`, + `requestTimeoutMs`, `headersTimeoutMs` and `keepAliveTimeoutMs` apply only to Node's `listen()`, + and the other adapters ignored them without a word. `serveDeno`, `serveBun` and `edgeHandler` + now warn through the app's logger, naming each one the app set. No API change. + +- **A bus listener that throws is logged once** (#77). `Bus.emit` isolated a failing listener without + a word, so a broken metrics or logger plugin produced nothing and gave no signal. The app's + `logger` now warns the first time a listener throws or rejects, naming the event; that listener's + later failures stay quiet. The `Bus` type is unchanged. + +- **An async bus listener that rejects no longer exits the Node process** (#70). `Bus.emit` isolated + a listener that threw, but an `async` listener fails by rejecting, and that rejection went + unhandled, so a plugin's `on('request:end', async () => { throw … })` killed the process on the + first request. A rejection is now swallowed like a throw. + +- **Bun no longer drops an SSE or ndjson stream that goes quiet for 10 seconds** (#71). `Bun.serve` + cuts a request idle for `idleTimeout` (10s by default), which is shorter than the 15s keep-alive + ping, so the client got `ECONNRESET`. `serveBun` now lifts the idle timeout for stream responses + only; buffered requests keep it. + ## [26.11.0-rc.1] - 2026-11-17 ### Breaking @@ -1228,7 +1384,8 @@ change before the stable release. - **Benchmarks** — reproducible `npm run bench` harness vs Express 5, Fastify 5, NestJS, and raw `http`; results in [BENCHMARKS.md](./BENCHMARKS.md). -[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.11.0-rc.1...HEAD +[Unreleased]: https://github.com/Expressive-Tea/green-tea/compare/v26.11.0-rc.2...HEAD +[26.11.0-rc.2]: https://github.com/Expressive-Tea/green-tea/compare/v26.11.0-rc.1...v26.11.0-rc.2 [26.11.0-rc.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.9.0-beta.2...v26.11.0-rc.1 [26.9.0-beta.2]: https://github.com/Expressive-Tea/green-tea/compare/v26.9.0-beta.1...v26.9.0-beta.2 [26.9.0-beta.1]: https://github.com/Expressive-Tea/green-tea/compare/v26.8.0-beta.1...v26.9.0-beta.1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3159bed..9cf527e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -148,10 +148,15 @@ npm audit --omit=dev # only what ships blocks; CI reports the rest plus the runtime suite for whatever your change touches (see *Local setup* above). CI runs Deno, Bun and the edge in its `runtimes` job. +`npm run coverage` is the Node suite with v8 coverage over `src/`. CI prints its summary in the +`build` job and does not gate on it yet. Baseline (2026-11-20): statements 94.55%, branches 89.68%, +functions 93.87%, lines 95.57%. The Deno, Bun and edge suites run outside Vitest and are not +counted. If your change drops a number noticeably, say why in the pull request. + - Write tests for new behavior (TDD welcome). We use Vitest. - `complexity:check` caps the cognitive complexity of every function in `src/`. What it measures is how much you have to hold in your head to follow a function from top to bottom, and it charges nesting more heavily than branching: a condition inside a closure inside a function costs several times what the same condition costs at the top level. Going over the threshold is not a verdict on your code — it means one function has grown to ask too much of whoever reads it next. The fix is nearly always to lift a nested closure out to module scope, where its branches are charged once instead of three times over. Raising `COMPLEXITY_MAX` is not the fix, even though the script suggests it. - Keep runtime dependencies at zero beyond `reflect-metadata`. -- **The public API is frozen from RC.1, and `api/` is its record.** `api/*.api.md` holds one report per export-map entry, and `npm run api:check` fails when the build declares something they do not. If you meant to change the API, run `npm run build && npm run api` and commit the regenerated report with your change, so the reviewer reads the API change as a diff rather than finding it after release. From RC.1 to stable, releases are fixes only, so a pull request that changes a report needs the owner to reopen the freeze first. The policy is in the README under [API stability](./README.md#api-stability). The check also fails when a public signature names a type its entry point does not export, because a user would have no way to name it. Mesh is alpha, `@experimental` and outside the freeze. Mesh adapts to the stable API and never changes it. Its own surface is the exports tagged `@experimental`, the shape of `MeshConfig` behind the `mesh` option, and the `mesh:*` lifecycle events. A mesh change may alter those and nothing else. It cannot add a `createApp` option, an `App` method or a decorator, and it cannot change a stable type. If mesh needs something the stable API does not offer, it builds on what is there. It is still in the report, so a reviewer can confirm a mesh change touched only mesh. +- **The public API is frozen from RC.1, and `api/` is its record.** `api/*.api.md` holds one report per export-map entry, and `npm run api:check` fails when the build declares something they do not. If you meant to change the API, run `npm run build && npm run api` and commit the regenerated report with your change, so the reviewer reads the API change as a diff rather than finding it after release. From RC.1 to stable, releases are fixes only, so a pull request that changes a report needs the owner to reopen the freeze first. The policy is in the README under [API stability](./README.md#api-stability). After stable, only the year breaks: a pull request that removes or breaks a public API targets the next `YY.1.0` and waits for it, however long that is, unless it is a security fix that cannot be made any other way. The check also fails when a public signature names a type its entry point does not export, because a user would have no way to name it. Mesh is alpha, `@experimental` and outside the freeze. Mesh adapts to the stable API and never changes it. Its own surface is the exports tagged `@experimental`, the shape of `MeshConfig` behind the `mesh` option, and the `mesh:*` lifecycle events. A mesh change may alter those and nothing else. It cannot add a `createApp` option, an `App` method or a decorator, and it cannot change a stable type. If mesh needs something the stable API does not offer, it builds on what is there. It is still in the report, so a reviewer can confirm a mesh change touched only mesh. - A new option or method on a public interface has to change that interface too. An implementation that grows a parameter without `src/app/types.ts` growing it as well is unreachable for anyone consuming the package. - New public API needs a doc note in `README.md`, **and a companion pull request to [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) updating the page that documents it.** It is a second pull request because a pull request cannot span two repositories — link the two to each other so a reviewer can see both. The documentation site used to be built by this repository's CI, so a stale page broke the build; it is now a separate repository that imports nothing from here, and nothing fails when the two disagree. Issue #18 happened when the two still lived together, which is the reason this line exists rather than a hope. If you would rather not write the docs change, say so in your pull request and a maintainer will — an unmentioned API change is the failure this line exists to prevent, not an unwritten page. - If your change only works on one runtime, say so in the pull request. green-tea runs on Node, Deno, Bun and the edge, and behavior that quietly differs between them is treated as a bug — an explicit "not available here" is fine, silence is not. diff --git a/README.md b/README.md index fb0ed1a..32c7ec6 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ The primitive never changes — it's always an `AsyncIterable`. What changes is **Your wire contract is what you declared, never what you happened to return.** A buffered route that returns an iterable, or a streaming route that returns a plain value, fails loudly with a `TransportMismatchError` — green-tea will not quietly switch a route's transport because of a return type. Refactoring a handler's internals can't change how it talks to the client. -Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it. +Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest: 1024 values per subscriber unless you pass `channel({ buffer })`) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it. ```typescript @Route('/live') @@ -136,17 +136,18 @@ Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a s The parts a real API needs, owned by the framework rather than assembled in your application — and without growing the runtime dependency tree past `reflect-metadata`: -- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`). +- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`). `ctx.ip` is the right-most `X-Forwarded-For` entry, the one your proxy appended: everything left of it came from the client. `trustProxy` assumes one proxy in front of the app; behind a chain (a CDN, then a load balancer), make the outermost hop set a header the app can trust, as Cloudflare does with `cf-connecting-ip`. - **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag. -- **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you. +- **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you: `origins: '*'` with `credentials: true` fails `createApp`, since honouring both means trusting every site with your users' cookies. Write the rule as a predicate if that is really what you want. +- **WebSocket upgrades from another site are refused** with `403`. A browser sends cookies with any page's upgrade and CORS does not cover WebSockets, so an upgrade carrying an `Origin` must come from the same host or from an origin `cors.origins` allows. Clients that send no `Origin` (servers, CLIs) are unaffected. Behind a proxy that rewrites `Host`, list your public origin in `cors.origins`. - **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed. - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. -- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. -- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses, and `createApp({ compression: true })` compresses text responses and event streams with gzip or br. It uses `node:zlib` on Node, Deno and Bun, and leaves encoding to the platform on the edge. -- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. +- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. A stream that fails after it started has already sent its status, so it ends with an error frame instead (`event: error` on SSE, a last `{"error"}` line on ndjson): it carries an `HttpError`'s message, and `Internal Server Error` for anything else. +- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. It never serves a dotfile or anything under a dot directory (`/.env`, `/.git/config`), except under `/.well-known/`. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses, and `createApp({ compression: true })` compresses text responses and event streams with gzip or br. It uses `node:zlib` on Node, Deno and Bun, and leaves encoding to the platform on the edge. Mind BREACH: a compressed response that reflects request input next to a secret (a CSRF token, a session id) leaks that secret byte by byte to an attacker who can send requests and see response sizes. Leave such routes uncompressed, or put the secret somewhere the input never sits beside it. +- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Node checks the headers and request timeouts every second, so a slow-header socket is closed (`408`) about when its timeout runs out, and pings each WebSocket every 30 seconds, terminating one that missed the previous ping. A connection cap is still one global number: put per-IP connection limits at the proxy. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. The connection cap and the three timeouts are Node-only: `serveDeno`, `serveBun` and `edgeHandler` log a warning naming any of them the app set, rather than ignore them silently. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. - **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core. - **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`. -- **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers that failed) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`. +- **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers failed; their names go to the boot log and `app.degraded()`, never to the public body) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`. On Kubernetes, an endpoint stays in rotation for a few seconds after the pod is told to stop, so give the pod a `preStop` hook that sleeps (`lifecycle.preStop.exec.command: ["sleep", "5"]`, or `lifecycle.preStop.sleep.seconds: 5` on Kubernetes 1.30+) before `SIGTERM` reaches `close()`, keep `terminationGracePeriodSeconds` above that sleep plus `shutdownTimeoutMs`, and point the `readinessProbe` at `/__ready__` with a short `periodSeconds`. - **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook. - **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck. - **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line. @@ -273,6 +274,8 @@ Patterns match by segment: static, constrained params such as `:id(\d+)`, plain @Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png" ``` +**Params arrive decoded, and a decoded param can hold `/` and `..`.** The path is split into segments first and each segment decoded after, so `/files/..%2F..%2Fetc` matches `:name` with `name = "../../etc"`, and a catch-all can hold `a/../../etc/passwd`. That is what Express does too, and it is correct for an id or a slug. It matters the moment a param becomes a filesystem path: resolve it against its base directory and check the result is still inside, the way `static` does, or constrain it (`:name([\w-]+)`). + `@Head` and `@Options` provide explicit handlers. Otherwise a buffered GET can serve HEAD without a body, and OPTIONS on an existing path returns `204` with canonical `Allow`; other method mismatches return `405`. `/path` and `/path/` are equivalent, while repeated slashes and malformed encoding return `400` rather than being normalized ambiguously. Constraints use a deliberately safe regex subset. See the full [routing guide](https://green-tea.expressive-tea.io/docs/guides/routing/). Because that subset is linear, constraints are also compared at boot. Two routes that branch at the same segment, under the same prefix and method, fail `createApp`: @@ -307,13 +310,13 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h **What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists. -**Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag. Native TLS (`createApp({ tls })`) is Node's `listen()` only: `serveDeno()` and `serveBun()` reject an app that sets it rather than serve it as plain HTTP, so configure TLS on that runtime's server or at a proxy, as you would on the edge. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip. +**Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide): `createApp` with `mesh` fails inside a Worker, and so does `edgeHandler` given such an app. Workers also require the `nodejs_compat` flag. Native TLS (`createApp({ tls })`) is Node's `listen()` only: `serveDeno()` and `serveBun()` reject an app that sets it rather than serve it as plain HTTP, so configure TLS on that runtime's server or at a proxy, as you would on the edge. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip. **mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet. **What a teapot exports: steps and routes, and nothing else.** A `@Provider` marked `export: true` fails the boot with an error that says why — a provider's value *is* the object it builds, a pool or a client or a `db`, and the mesh moves data, not objects. Export a `@Step` instead: it runs on the teapot, per request, and its result is what comes back. That is also what lets a teacup boot without its teapot: a remote step holds nothing between requests, so a teacup whose teapot never answers still starts once the `bootTimeoutMs` grace runs out — it warns and carries on. Be precise about what that means, because it is narrower than it sounds. A teapot that never connected sent no manifest, so nothing of it reached the graph: its routes **404** rather than `503`, since nothing was registered to match, and a local step that `@needs` one of its tokens **still fails the boot**, naming the teapot that did not connect. That failure is deliberate — it is the check that catches a typo in a token name, which no amount of waiting will fix. `503` is what you get from a teapot that connected and *later* died, where the link and its exports do exist. So what the change buys is the teacup that does *not* depend on that teapot starting anyway, rather than refusing over a dependency it never had. Keeping a *needed* token serving while its teapot is legitimately away is a known gap, not an oversight: the intended answer is a per-teapot `expects` list that declares what a teapot would export, which is planned and not built. -**What is settled, and what is frozen.** From RC.1 the public surface of the four entry points (`@green-tea/core`, `/deno`, `/bun`, `/edge`) is frozen. Between RC.1 and the first stable release, releases are fixes only: nothing is added, removed, renamed or narrowed. Nothing published in `26.9.0-beta.2` was removed to reach the freeze. [API stability](#api-stability) has the full policy. That covers the graph (`needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key), the decorators and handler shapes, the plugin API (`{ name, mount }` with `onShutdown`), the runtime entry points (`serveDeno()` and `serveBun()` are async so they boot before they bind), `createApp`'s options, and the pipeline context, which is one object mutated in place, so a step sees what earlier steps wrote. **Outside the freeze:** mesh, marked `@experimental` and described above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI ships from its own repository on its own version line, so nothing here speaks for it. +**What is settled, and what is frozen.** From RC.1 the public surface of the four entry points (`@green-tea/core`, `/deno`, `/bun`, `/edge`) is frozen. Between RC.1 and the first stable release, releases are fixes only: nothing is added, removed, renamed or narrowed. Nothing published in `26.9.0-beta.2` was removed to reach the freeze. [API stability](#api-stability) has the full policy. That covers the graph (`needs`/`provides`, the order derived from them, and the boot-time failure when nothing provides a key), the decorators and handler shapes, the plugin API (`{ name, mount }` with `onShutdown`), the runtime entry points (`serveDeno()` and `serveBun()` are async so they boot before they bind), `createApp`'s options, and the pipeline context, which is one object mutated in place, so a step sees what earlier steps wrote. **Outside the freeze:** mesh, marked `@experimental` and described above. Legacy decorators are a standing *external* risk rather than a green-tea one — see [Why legacy decorators](#why-legacy-decorators). The [matcha](https://github.com/Expressive-Tea/matcha) CLI lives in its own repository and, since RC.1, is released with core under the same version. ## Docs & development @@ -362,7 +365,9 @@ consumer would have received. ## Versioning -green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first release cut in August 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md). +green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first release cut in August 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. + +**After the first stable release, only the year breaks.** A release inside a year (`26.12.0`, `27.3.1`) never removes or breaks a public API, so the range npm writes by default, `^26.12.0`, is safe to take. Breaking changes ship only in the first release of a year (`27.1.0`, `28.1.0`), and that is the only kind of release you have to read before upgrading. npm reads the year as the major version, so a `^` range never crosses into it on its own. Every breaking change is called out under `### Breaking` in the [CHANGELOG](./CHANGELOG.md). Which releases get fixes, and for how long, is in [SECURITY.md](./SECURITY.md#supported-versions). **Before the first stable release**, versions carry a pre-release suffix on the calendar version, and each one publishes under the npm dist-tag of its channel: release candidates (`-rc.N`, e.g. `26.11.0-rc.1`) under `rc`, betas (`-beta.N`) under `beta`. The `beta` tag stays on the last beta, `26.9.0-beta.2`. Until a stable release exists there is nothing else to install, so `latest` follows the newest prerelease too — today `npm install @green-tea/core` and `@green-tea/core@rc` resolve to the same version. Install with the explicit `@rc` tag anyway: the day a stable ships, `latest` moves to it and your installs stay on the channel you meant. @@ -371,7 +376,7 @@ green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first **From the first release candidate (RC.1) the public API is frozen.** The public API is everything exported from the four entry points: `@green-tea/core`, `/deno`, `/bun` and `/edge`. - **RC.1 to stable: fixes only.** No release in that window adds, removes, renames or narrows a public API. It also deprecates nothing. If a fix needs an API change, the freeze is reopened, and the change is called out under `### Breaking` in the CHANGELOG. -- **After stable, deprecations come before removals.** A deprecated API keeps working for at least two monthly releases. It carries JSDoc `@deprecated` naming its replacement. Where it has a runtime path, it warns once per process through `app.logger`, never `console`. It is removed only in a release whose CHANGELOG lists the removal under `### Breaking`. +- **After stable, deprecations come before removals, and removals wait for the year.** A deprecated API keeps working for at least two monthly releases. It carries JSDoc `@deprecated` naming its replacement. Where it has a runtime path, it warns once per process through `app.logger`, never `console`. It is removed only in the first release of a year (`YY.1.0`), whose CHANGELOG lists the removal under `### Breaking`. So something deprecated in `26.4.0` goes in `27.1.0`, and something deprecated in `26.12.0`, too late for two monthly releases before January, goes in `28.1.0`. The one exception is a security fix that cannot be made without breaking an API: it ships when it is ready, under both `### Security` and `### Breaking`. - **Every API change shows up in review.** [`api/`](./api) holds the committed API report for each entry point, and CI fails when the build no longer matches it. A deliberate change regenerates the report in the same pull request. - **Mesh is alpha and outside the promise.** It is `@experimental` and gated behind `createApp({ experimental: true })`, so it may change in any release. Mesh adapts to the stable API and never changes it. Its own surface is the exports tagged `@experimental`, the shape of `MeshConfig` behind the `mesh` option, and the `mesh:*` lifecycle events. A mesh change may alter those and nothing else. It cannot add a `createApp` option, an `App` method or a decorator, and it cannot change a stable type. If mesh needs something the stable API does not offer, it builds on what is there. Its exports still appear in the reports, so those changes still show up in review. diff --git a/SECURITY.md b/SECURITY.md index c6ed18e..1109ce7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -48,8 +48,21 @@ out after the work. ## Supported versions -While the package is in beta, only the most recent `26.x.y-beta.N` receives fixes. There is no -backport channel yet; when the first stable ships, this section gets the real table. +| Version | Bug fixes | Security fixes | +| --- | --- | --- | +| The latest monthly release (`YY.M.x`) | Yes | Yes | +| The monthly release before it | No | For 3 months after the latest one ships | +| Anything older | No | No | +| Pre-releases (`-beta.N`, `-rc.N`) | Only the latest, until the stable release that follows it | Same | + +A fix lands in the latest release first. A security fix is also backported, as a patch release of +the previous month's line, while that line is inside its three months. Features are never +backported. This is deliberately small: the project is one person, and a promise that only holds +in a good month is worse than a short one that holds. There is no long-term support line. + +Breaking changes ship only in the first release of a year (see +[Versioning](./README.md#versioning)), so moving to the latest release within a year is meant to be +safe, and is the expected way to stay supported. ## Scope diff --git a/api/index.api.md b/api/index.api.md index 8be4257..e5243d9 100644 --- a/api/index.api.md +++ b/api/index.api.md @@ -567,6 +567,7 @@ export const MESH_CONTROL_PATH = "/__mesh__/control"; // @public export interface MeshConfig { + allowInsecure?: boolean; bootTimeoutMs?: number; heartbeatMs?: number; onManifestChange?: 'refuse'; @@ -1039,7 +1040,7 @@ export class ValidationError extends HttpError { } // @public -export const VERSION = "26.11.0-rc.1"; +export const VERSION = "26.11.0-rc.2"; // @public export function withConsoleFallback(logger: Logger): Logger; diff --git a/bench/compare-results.json b/bench/compare-results.json new file mode 100644 index 0000000..94d0961 --- /dev/null +++ b/bench/compare-results.json @@ -0,0 +1,109 @@ +{ + "rounds": 5, + "duration": 6, + "conns": 100, + "rows": [ + { + "name": "param", + "base": 91040, + "head": 91882.67, + "delta": 0.925604130052722, + "separated": false, + "samples": { + "base": [ + 91424, + 90837.34, + 90250.67, + 91040, + 91861.34 + ], + "head": [ + 91498.67, + 91904, + 93749.34, + 91050.67, + 91882.67 + ] + } + }, + { + "name": "validate (POST)", + "base": 71210.67, + "head": 70272, + "delta": -1.3181592028273266, + "separated": false, + "samples": { + "base": [ + 71008, + 70933.34, + 71210.67, + 71274.67, + 71605.34 + ], + "head": [ + 69962.67, + 71989.34, + 71765.34, + 70272, + 70090.67 + ] + } + }, + { + "name": "param, 50 routes", + "base": 90005.34, + "head": 92256, + "delta": 2.5005849652920635, + "separated": false, + "samples": { + "base": [ + 90005.34, + 91210.67, + 89856, + 92949.34, + 89781.34 + ], + "head": [ + 91904, + 92501.34, + 92256, + 92832, + 91808 + ] + } + }, + { + "name": "param, 200 routes", + "base": 91349.34, + "head": 90944, + "delta": -0.44372515444555655, + "separated": false, + "samples": { + "base": [ + 89866.67, + 91445.34, + 91157.34, + 91349.34, + 91434.67 + ], + "head": [ + 91221.34, + 87104, + 90634.67, + 90944, + 91818.67 + ] + } + } + ], + "cors": { + "base": { + "get": 1, + "preflight": 1 + }, + "head": { + "get": 1, + "preflight": 1 + } + } +} \ No newline at end of file diff --git a/bench/compare.ts b/bench/compare.ts index 4af6ff3..e2238fa 100644 --- a/bench/compare.ts +++ b/bench/compare.ts @@ -16,7 +16,7 @@ * not moved between the two revisions — check that first, or the comparison is measuring a * dependency bump. * - * Env: `AB_BASE` (required), `AB_DURATION` (10), `AB_ROUNDS` (3), `AB_CONNS` (100), + * Env: `AB_BASE` (required), `AB_RUNTIME` (node | deno | bun), `AB_DURATION` (10), `AB_ROUNDS` (3), `AB_CONNS` (100), * `AB_ONLY` (comma-separated substrings of case names), `AB_OUT` (bench/compare-results.json). */ import autocannon from 'autocannon'; @@ -27,6 +27,9 @@ const DURATION = Number(process.env.AB_DURATION ?? 10); const ROUNDS = Number(process.env.AB_ROUNDS ?? 3); const CONNS = Number(process.env.AB_CONNS ?? 100); +// The runtime both sides' servers run on. The harness itself always runs on Node. +const RUNTIME = process.env.AB_RUNTIME ?? 'node'; + const HEAD = process.cwd(); // Per side, so "the bundle we publish vs the source we test" is one run rather than two tables. const BASE_SERVER = process.env.AB_BASE_SERVER ?? 'compare'; @@ -84,6 +87,11 @@ const CASES: Case[] = [ { name: 'json 8KB + compression, identity', path: '/big', env: { GT_COMPRESS: '1' } }, { name: 'json 8KB + gzip', path: '/big', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'gzip' } }, { name: 'json 8KB + br', path: '/big', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'br' } }, + // Streams (#26): one request is 100 SSE events, so req/s here is events/s / 100. The gzip case + // takes the compressed frame sink, whose drain wait is a different emitter. + { name: 'static 2KB file', path: '/app.js', env: { GT_STATIC: '1' } }, + { name: 'sse 100 events', path: '/sse' }, + { name: 'sse 100 events + gzip', path: '/sse', env: { GT_COMPRESS: '1' }, headers: { 'accept-encoding': 'gzip' } }, ]; const ONLY = process.env.AB_ONLY; @@ -94,7 +102,10 @@ function log(m: string): void { } async function boot(cwd: string, env: Record, server = 'compare'): Promise<{ port: number; kill: () => Promise }> { - const child = spawn(process.execPath, ['--import', 'tsx', `bench/servers/${server}.ts`], { + const file = `bench/servers/${server}.ts`; + const [cmd, args] = + RUNTIME === 'deno' ? ['deno', ['run', '-A', file]] : RUNTIME === 'bun' ? ['bun', [file]] : [process.execPath, ['--import', 'tsx', file]]; + const child = spawn(cmd, args, { cwd, env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json', ...env }, }); diff --git a/bench/public/app.js b/bench/public/app.js new file mode 100644 index 0000000..9770363 --- /dev/null +++ b/bench/public/app.js @@ -0,0 +1,41 @@ +// Static-serving bench fixture (~2 KB). +export const value0 = 'static bench fixture line 0 padding padding'; +export const value1 = 'static bench fixture line 1 padding padding'; +export const value2 = 'static bench fixture line 2 padding padding'; +export const value3 = 'static bench fixture line 3 padding padding'; +export const value4 = 'static bench fixture line 4 padding padding'; +export const value5 = 'static bench fixture line 5 padding padding'; +export const value6 = 'static bench fixture line 6 padding padding'; +export const value7 = 'static bench fixture line 7 padding padding'; +export const value8 = 'static bench fixture line 8 padding padding'; +export const value9 = 'static bench fixture line 9 padding padding'; +export const value10 = 'static bench fixture line 10 padding padding'; +export const value11 = 'static bench fixture line 11 padding padding'; +export const value12 = 'static bench fixture line 12 padding padding'; +export const value13 = 'static bench fixture line 13 padding padding'; +export const value14 = 'static bench fixture line 14 padding padding'; +export const value15 = 'static bench fixture line 15 padding padding'; +export const value16 = 'static bench fixture line 16 padding padding'; +export const value17 = 'static bench fixture line 17 padding padding'; +export const value18 = 'static bench fixture line 18 padding padding'; +export const value19 = 'static bench fixture line 19 padding padding'; +export const value20 = 'static bench fixture line 20 padding padding'; +export const value21 = 'static bench fixture line 21 padding padding'; +export const value22 = 'static bench fixture line 22 padding padding'; +export const value23 = 'static bench fixture line 23 padding padding'; +export const value24 = 'static bench fixture line 24 padding padding'; +export const value25 = 'static bench fixture line 25 padding padding'; +export const value26 = 'static bench fixture line 26 padding padding'; +export const value27 = 'static bench fixture line 27 padding padding'; +export const value28 = 'static bench fixture line 28 padding padding'; +export const value29 = 'static bench fixture line 29 padding padding'; +export const value30 = 'static bench fixture line 30 padding padding'; +export const value31 = 'static bench fixture line 31 padding padding'; +export const value32 = 'static bench fixture line 32 padding padding'; +export const value33 = 'static bench fixture line 33 padding padding'; +export const value34 = 'static bench fixture line 34 padding padding'; +export const value35 = 'static bench fixture line 35 padding padding'; +export const value36 = 'static bench fixture line 36 padding padding'; +export const value37 = 'static bench fixture line 37 padding padding'; +export const value38 = 'static bench fixture line 38 padding padding'; +export const value39 = 'static bench fixture line 39 padding padding'; diff --git a/bench/servers/compare.ts b/bench/servers/compare.ts index e8f4ac5..d425ade 100644 --- a/bench/servers/compare.ts +++ b/bench/servers/compare.ts @@ -2,7 +2,7 @@ // `src/`. Adds the two paths the standard bench server does not exercise and this release changed: // secure-by-default headers, and a `cors.origins` predicate. import 'reflect-metadata'; -import { createApp, Step, Route, Get, Post, Module, needs, param, body } from '../../src/index'; +import { createApp, Step, Route, Get, Post, Sse, Module, needs, param, body } from '../../src/index'; type Ctor = new (...args: any[]) => any; @@ -30,6 +30,11 @@ class Bench { @Post('/validate') validate(@body(emailSchema) b: any) { return { email: b.email }; } @Get('/big') big() { return BIG; } @Get('/steps/5') steps5(@needs('s5') s5: number) { return { hello: 'world', s5 }; } + // A finite stream, so autocannon can count it as one request: the per-event loop (next(), encode, + // write, drain) runs 100 times per request, which is the path a stream change touches (#26). + @Sse('/sse') sse() { + return (async function* () { for (let i = 0; i < 100; i++) yield { i }; })(); + } // Reads the counter without resetting it — the read itself carries no Origin, so it cannot // change what it reports. @Get('/cors-calls') corsCalls() { return { calls: corsCalls }; } @@ -79,13 +84,32 @@ const app = createApp({ security: process.env.GT_SECURE === '1', ...(cors ? { cors } : {}), ...(process.env.GT_COMPRESS === '1' ? { compression: true } : {}), + // Static serving: path checks (dotfiles, traversal) run on every request that reaches it. + ...(process.env.GT_STATIC === '1' ? { static: 'bench/public' } : {}), }); +// Each runtime through its own adapter, the way an app deploys there: Deno and Bun take the fetch +// path (`src/http/web.ts`), Node the `node:http` one. `AB_RUNTIME` in the harness picks the binary. +async function listen(): Promise { + const g = globalThis as { Deno?: unknown; Bun?: unknown }; + if (g.Deno) { + const { serveDeno } = await import('../../src/deno'); + return new Promise((resolve) => { + void serveDeno(app, { port: 0, hostname: '127.0.0.1', onListen: (a: { port: number }) => resolve(a.port) }); + }); + } + if (g.Bun) { + const { serveBun } = await import('../../src/bun'); + return (await serveBun(app, { port: 0, hostname: '127.0.0.1' })).port; + } + const server = await app.listen(0); + server.keepAliveTimeout = 5000; + return (server.address() as any).port; +} + async function main() { try { if (app.inspect('/hello').length === 0) throw new Error('empty'); } catch { console.error('DECORATORS_NOT_APPLIED'); process.exit(1); } - const server = await app.listen(0); - server.keepAliveTimeout = 5000; - console.log(`READY ${(server.address() as any).port}`); + console.log(`READY ${await listen()}`); } main().catch((e) => { console.error(e); process.exit(1); }); diff --git a/bench/servers/soak.mts b/bench/servers/soak.mts new file mode 100644 index 0000000..f3f4d8b --- /dev/null +++ b/bench/servers/soak.mts @@ -0,0 +1,53 @@ +import 'reflect-metadata'; +import { createApp, Route, Get, Sse, Ws, Module, inbound, channel } from '../../dist/index.mjs'; + +// The app `scripts/soak.ts` drives (#80): buffered JSON, SSE, WebSocket echo and a busy fan-out +// channel that a slow subscriber never reads. Built `dist/`, like the runtimes bench. +const gc = (globalThis as { gc?: () => void }).gc; +let unhandled = 0; +process.on('unhandledRejection', (e) => { + unhandled++; + console.error('unhandledRejection', e); +}); + +const hub = channel<{ t: number }>(); +setInterval(() => hub.push({ t: Date.now() }), 1).unref(); + +@Route('/') +class Soak { + @Get('/json') json() { + return { hello: 'world', at: Date.now() }; + } + @Sse('/ticks') ticks() { + return (async function* () { + for (let i = 0; ; i++) { + yield { i }; + await new Promise((r) => setTimeout(r, 10)); + } + })(); + } + @Sse('/hub') hub() { + return hub; + } + @Ws('/echo') echo(@inbound() inc: AsyncIterable) { + const out = channel(); + (async () => { + for await (const m of inc) out.push(m); + out.close(); + })(); + return out; + } + @Get('/__mem') mem() { + gc?.(); + const m = process.memoryUsage(); + const handles = (process as unknown as { _getActiveHandles(): unknown[] })._getActiveHandles().length; + return { rss: m.rss, heapUsed: m.heapUsed, handles, unhandled }; + } +} + +@Module({ mountpoint: '/', controllers: [Soak] }) +class SoakModule {} + +const app = createApp({ modules: [SoakModule], security: false, handleSignals: true }); +const server = await app.listen(0); +console.log(`READY ${(server.address() as { port: number }).port}`); diff --git a/deno.json b/deno.json index d0615c5..d9e03de 100644 --- a/deno.json +++ b/deno.json @@ -1,6 +1,6 @@ { "name": "@green-tea/core", - "version": "26.11.0-rc.1", + "version": "26.11.0-rc.2", "license": "MIT", // JSR serves TypeScript source, not the tsup build, so these point at `src/` where npm's // `exports` point at `dist/`. Same four entry points on purpose: a docs example that imports diff --git a/deno.lock b/deno.lock index 24cd71f..6e92689 100644 --- a/deno.lock +++ b/deno.lock @@ -30,6 +30,7 @@ "npm:@types/express@^5.0.6", "npm:@types/node@^22.20.5", "npm:@types/ws@^8.18.1", + "npm:@vitest/coverage-v8@^4.1.12", "npm:autocannon@8", "npm:busboy@^1.6.0", "npm:cognitive-complexity-ts@~0.8.2", diff --git a/example/README.md b/example/README.md index e98d837..be99c28 100644 --- a/example/README.md +++ b/example/README.md @@ -7,6 +7,8 @@ npx tsx example/server.ts # the tour, below npx tsx example/crud.ts # a CRUD API over an in-memory store, on :3300 npx tsx example/chat.ts # WebSocket rooms, on ws://localhost:4100/chat/:room?token=... npx tsx example/graphql.ts # GraphQL queries and subscriptions over SSE, on :4200/graphql +npx tsx example/mesh/billing.ts # mesh teapot on :3401; then, in a second terminal: +npx tsx example/mesh/shop.ts # mesh teacup on :3400 (see Mesh, below) ``` `server.ts` demonstrates the typed context contract, graph-derived order, `app.inspect()`, a @@ -16,3 +18,40 @@ teacup. Try it with: ```bash curl -H 'x-token: u1' http://localhost:3000/api/users/9 ``` + +## Mesh: one REST API across two processes + +`example/mesh/` splits a small shop across two nodes. Mesh is alpha and needs +`createApp({ experimental: true })`; don't ship it to production yet. + +- **`billing.ts`** is the teapot. It owns the ledger (never exported: a mesh export carries data, + not handles) and exports a step, `balance`, plus its REST routes under `/billing`. +- **`shop.ts`** is the teacup. Its `GET /shop/checkout/:customer` does `@needs('balance')` exactly + as it would a local step; only the mesh config says that `balance` lives on billing. It also + serves billing's routes as if they were its own. + +Start billing first: checkout needs `balance` at boot, and a teacup refuses to boot without a +producer for a token it needs. + +```bash +npx tsx example/mesh/billing.ts # teapot on :3401 +npx tsx example/mesh/shop.ts # teacup on :3400 +``` + +```bash +curl localhost:3400/shop/checkout/ada # {"customer":"ada","due":40,"canCheckout":false} +curl -X POST -H 'content-type: application/json' \ + -d '{"amount":10}' localhost:3400/billing/invoices/ada # served by billing, through the shop +curl localhost:3400/billing/invoices/ada # both invoices +``` + +Stop billing and the shop keeps running: anything that needs billing answers `503` with +`retry-after` while the link reconnects. Start billing again and the shop reconnects on its own +within about a second. The ledger is in memory, so it starts over. + +The secret is `demo-secret` unless `MESH_SECRET` is set on both sides. `BILLING_PORT`, `SHOP_PORT` +and `BILLING_URL` move things around. `ws://` works here because both nodes are on loopback; to +another machine use `wss://`, or `createApp` refuses the link. + +`test/examples/mesh.test.ts` runs this walkthrough with billing in a real child process, killed and +restarted, so the demo cannot drift from what core does. diff --git a/example/mesh/billing.ts b/example/mesh/billing.ts new file mode 100644 index 0000000..4ca2a67 --- /dev/null +++ b/example/mesh/billing.ts @@ -0,0 +1,88 @@ +// The teapot: the billing service. It owns the ledger and exports two things over the mesh: +// a step (`balance`) another node can `@needs`, and its REST routes, which a teacup serves as if +// they were its own. The ledger itself is never exported: a mesh export carries data, not handles. +// +// npx tsx example/mesh/billing.ts # on :3401, or BILLING_PORT +// +// Mesh is alpha and behind `experimental: true`. See example/README.md for the walkthrough. +import { createApp, Provider, Step, Route, Get, Post, Module, needs, param, body, HttpError } from '../../src/index'; + +export interface Invoice { + id: number; + amount: number; + paid: boolean; +} + +export interface Ledger { + invoices(customer: string): Invoice[]; + add(customer: string, amount: number): Invoice; +} + +/** In-memory, so a restarted billing node starts empty. A real one would hold a database pool here. */ +@Provider({ provides: 'ledger' }) +class LedgerProvider { + provide(): { ledger: Ledger } { + const byCustomer = new Map([['ada', [{ id: 1, amount: 40, paid: false }]]]); + let next = 2; + + return { + ledger: { + invoices: (customer) => byCustomer.get(customer) ?? [], + add: (customer, amount) => { + const invoice = { id: next++, amount, paid: false }; + byCustomer.set(customer, [...(byCustomer.get(customer) ?? []), invoice]); + return invoice; + }, + }, + }; + } +} + +/** + * Exported: computed here, per request, from the caller's route params. A teacup that + * `@needs('balance')` gets this result; it never sees the ledger. + */ +@Step({ provides: 'balance', needs: ['ledger'], export: true }) +class BalanceStep { + run(ctx: { ledger: Ledger; params: { customer?: string } }) { + const customer = ctx.params.customer ?? ''; + const due = ctx.ledger + .invoices(customer) + .filter((invoice) => !invoice.paid) + .reduce((sum, invoice) => sum + invoice.amount, 0); + + return { balance: { customer, due } }; + } +} + +@Route('/billing') +class BillingController { + @Get('/invoices/:customer', { export: true }) + list(@needs('ledger') ledger: Ledger, @param('customer') customer: string) { + return { customer, invoices: ledger.invoices(customer) }; + } + + @Post('/invoices/:customer', { export: true }) + create(@needs('ledger') ledger: Ledger, @param('customer') customer: string, @body() data: { amount?: unknown }) { + const amount = Number(data?.amount); + if (!Number.isFinite(amount) || amount <= 0) throw new HttpError(422, 'amount must be a positive number'); + + return ledger.add(customer, amount); + } +} + +@Module({ mountpoint: '/', providers: [LedgerProvider], steps: [BalanceStep], controllers: [BillingController] }) +class BillingModule {} + +/** The secret every teacup must present. Set MESH_SECRET outside a demo. */ +export const MESH_SECRET = process.env.MESH_SECRET ?? 'demo-secret'; + +export const billing = createApp({ modules: [BillingModule], experimental: true, mesh: { secret: MESH_SECRET } }); + +if (require.main === module) { + billing.listen(Number(process.env.BILLING_PORT ?? 3401)).then((server) => { + const { port } = server.address() as { port: number }; + // The test reads this line to learn the port. + console.log(`billing (teapot) on http://127.0.0.1:${port}`); + }); +} diff --git a/example/mesh/shop.ts b/example/mesh/shop.ts new file mode 100644 index 0000000..dcf4df9 --- /dev/null +++ b/example/mesh/shop.ts @@ -0,0 +1,53 @@ +// The teacup: the shop. It serves its own checkout route, which `@needs('balance')` exactly as it +// would a local step, and it serves billing's exported routes as if they were its own. Nothing in +// the controller says where `balance` lives; only the mesh config does. +// +// npx tsx example/mesh/billing.ts # start the teapot first: checkout needs `balance` at boot +// npx tsx example/mesh/shop.ts # on :3400, or SHOP_PORT; BILLING_URL points at the teapot +// +// Mesh is alpha and behind `experimental: true`. See example/README.md for the walkthrough. +import { createApp, Route, Get, Module, needs, MESH_CONTROL_PATH } from '../../src/index'; + +interface Balance { + customer: string; + due: number; +} + +@Route('/shop') +class CheckoutController { + @Get('/checkout/:customer') + checkout(@needs('balance') balance: Balance) { + return { customer: balance.customer, due: balance.due, canCheckout: balance.due === 0 }; + } +} + +@Module({ mountpoint: '/', controllers: [CheckoutController] }) +class ShopModule {} + +/** + * `billingUrl` is the teapot's control channel. `ws://` is fine on loopback; to another machine use + * `wss://`, or `createApp` refuses (mesh.allowInsecure exists for networks that already encrypt). + */ +export function createShop(billingUrl: string, secret = process.env.MESH_SECRET ?? 'demo-secret') { + return createApp({ + modules: [ShopModule], + experimental: true, + mesh: { + teapots: [{ url: billingUrl, secret }], + // Quick retries so the demo recovers in about a second after billing comes back. + reconnect: { initialDelayMs: 100, maxDelayMs: 1_000 }, + bootTimeoutMs: 5_000, + }, + }); +} + +if (require.main === module) { + const billingUrl = process.env.BILLING_URL ?? `ws://127.0.0.1:3401${MESH_CONTROL_PATH}`; + + createShop(billingUrl) + .listen(Number(process.env.SHOP_PORT ?? 3400)) + .then((server) => { + const { port } = server.address() as { port: number }; + console.log(`shop (teacup) on http://127.0.0.1:${port}, billing at ${billingUrl}`); + }); +} diff --git a/package-lock.json b/package-lock.json index eb15462..4207736 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@green-tea/core", - "version": "26.11.0-rc.1", + "version": "26.11.0-rc.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@green-tea/core", - "version": "26.11.0-rc.1", + "version": "26.11.0-rc.2", "license": "MIT", "dependencies": { "reflect-metadata": "0.2.2" @@ -24,6 +24,7 @@ "@types/express": "^5.0.6", "@types/node": "^22.20.5", "@types/ws": "^8.18.1", + "@vitest/coverage-v8": "^4.1.12", "autocannon": "^8.0.0", "busboy": "^1.6.0", "cognitive-complexity-ts": "^0.8.2", @@ -66,6 +67,66 @@ "dev": true, "license": "Apache-2.0" }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@borewit/text-codec": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.2.tgz", @@ -3078,6 +3139,37 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/@vitest/coverage-v8": { + "version": "4.1.12", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.12.tgz", + "integrity": "sha512-6S7/iVknKglLAxMFxQGNppBI0iqJS2NgM6FBxavitj7KaDq/vywOWGf6dGu7F2L1Qy0G6S3uTp7aGshHrzK8JA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.1.12", + "ast-v8-to-istanbul": "^1.0.0", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.2", + "obug": "^2.1.1", + "std-env": "^4.0.0-rc.1", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "4.1.12", + "vitest": "4.1.12" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, "node_modules/@vitest/expect": { "version": "4.1.12", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.12.tgz", @@ -3352,6 +3444,18 @@ "node": ">=12" } }, + "node_modules/ast-v8-to-istanbul": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.8.tgz", + "integrity": "sha512-lPdpagk13ANXV+HClJEpCZM7kUsl5XcvgqKzZhaj6Ve1ZFICcY2sGhAN1n1vT0tML6EclT7bfVgTxqL57Gkpow==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^10.0.0" + } + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -5122,6 +5226,13 @@ "dev": true, "license": "MIT" }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -5398,6 +5509,45 @@ "dev": true, "license": "ISC" }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", + "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/iterare": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/iterare/-/iterare-1.2.1.tgz", @@ -5470,6 +5620,13 @@ "dev": true, "license": "MIT" }, + "node_modules/js-tokens": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz", + "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==", + "dev": true, + "license": "MIT" + }, "node_modules/js-yaml": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", @@ -5745,6 +5902,34 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/magicast": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.5.tgz", + "integrity": "sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "source-map-js": "^1.2.1" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/manage-path": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/manage-path/-/manage-path-2.0.0.tgz", diff --git a/package.json b/package.json index fc389b9..2fdff61 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@green-tea/core", - "version": "26.11.0-rc.1", + "version": "26.11.0-rc.2", "description": "A zen, opinionated, type-safe framework — your API is a graph, not a middleware chain.", "license": "MIT", "author": "green-tea contributors ", @@ -91,6 +91,7 @@ "api:check": "node scripts/api-report.mjs --check", "test": "vitest run", "test:dev": "vitest", + "coverage": "vitest run --coverage", "test:deno": "deno test --allow-net --allow-read --allow-run --allow-env --no-check test/deno/", "test:bun": "bun test test/bun/", "test:edge": "tsx test/edge/run.ts && tsx test/edge/compression.ts && npm run build && tsx test/edge/dist.ts", @@ -107,6 +108,7 @@ "bench": "tsx bench/run.ts", "bench:compare": "tsx bench/compare.ts", "bench:lookup": "tsx bench/lookup.ts", + "soak": "tsx --tsconfig bench/tsconfig.json scripts/soak.mts", "parity:mutants": "tsx test/router-parity/mutants.ts", "prepublishOnly": "npm run lint && npm run complexity:check && npm run typecheck && npm test && npm run build", "prepare": "git config core.hooksPath .githooks || true" @@ -151,6 +153,7 @@ "@types/express": "^5.0.6", "@types/node": "^22.20.5", "@types/ws": "^8.18.1", + "@vitest/coverage-v8": "^4.1.12", "autocannon": "^8.0.0", "busboy": "^1.6.0", "cognitive-complexity-ts": "^0.8.2", diff --git a/scripts/soak.mts b/scripts/soak.mts new file mode 100644 index 0000000..9c4aa9a --- /dev/null +++ b/scripts/soak.mts @@ -0,0 +1,104 @@ +/** + * Soak job (#80): drives `bench/servers/soak.mts` (built `dist/`) with a fixed mix for SOAK_SECONDS + * (default 120): autocannon on a JSON route, SSE and WebSocket connections opened and dropped in a + * loop, and one SSE subscriber on a busy channel that never reads. Samples RSS, heap and handles + * every 5 s, then sends SIGTERM while traffic still flows. + * + * Fails on: heap growth between the first and last third of the run (> 25% and > 8 MB, after gc), + * any unhandled rejection in the server, or a close() under load that does not exit 0 within 20 s. + * Run `npm run build` first. + */ +import autocannon from 'autocannon'; +import { spawn } from 'child_process'; + +const SECONDS = Number(process.env.SOAK_SECONDS ?? 120); +const child = spawn(process.execPath, ['--expose-gc', '--import', 'tsx', 'bench/servers/soak.mts'], { + env: { ...process.env, TSX_TSCONFIG_PATH: 'bench/tsconfig.json' }, + stdio: ['ignore', 'pipe', 'inherit'], +}); +const exited = new Promise((r) => child.on('exit', r)); +const port = await new Promise((resolve, reject) => { + child.stdout.on('data', (d: Buffer) => { + const m = /READY (\d+)/.exec(String(d)); + if (m) resolve(Number(m[1])); + }); + setTimeout(() => reject(new Error('soak server did not start in 15 s')), 15_000).unref(); +}); +const base = `http://127.0.0.1:${port}`; +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +let stop = false; + +interface Mem { rss: number; heapUsed: number; handles: number; unhandled: number } +const mem = async (): Promise => (await fetch(`${base}/__mem`)).json() as Promise; + +async function sseChurn(): Promise { + while (!stop) { + const ac = new AbortController(); + const res = await fetch(`${base}/ticks`, { signal: ac.signal }).catch(() => null); + const reader = res?.body?.getReader(); + for (let i = 0; i < 5 && reader; i++) await reader.read().catch(() => {}); + ac.abort(); + } +} + +async function wsChurn(): Promise { + while (!stop) { + await new Promise((done) => { + const ws = new WebSocket(`ws://127.0.0.1:${port}/echo`); + let got = 0; + ws.onopen = () => { for (let i = 0; i < 10; i++) ws.send(`m${i}`); }; + ws.onmessage = () => { if (++got === 10) ws.close(); }; + ws.onclose = ws.onerror = () => done(); + }); + } +} + +// One subscriber that never reads: before #82 this grew the server without bound. +const slow = await fetch(`${base}/hub`); + +const samples: (Mem & { t: number })[] = []; +const sampler = (async () => { + while (!stop) { + samples.push({ t: samples.length * 5, ...(await mem()) }); + await sleep(5000); + } +})(); +const churn = [sseChurn(), sseChurn(), wsChurn(), wsChurn()]; +const load = await autocannon({ url: `${base}/json`, connections: 50, duration: SECONDS }); +stop = true; +await Promise.all([sampler, ...churn]); +const last = await mem(); + +// close() while traffic is still flowing +const tail = autocannon({ url: `${base}/json`, connections: 20, duration: 30 }); +await sleep(1000); +child.kill('SIGTERM'); +const code = await Promise.race([exited, sleep(20_000).then(() => 'timeout' as const)]); +tail.stop(); +void slow.body?.cancel().catch(() => {}); + +const third = Math.max(1, Math.floor(samples.length / 3)); +const median = (xs: number[]) => xs.sort((a, b) => a - b)[Math.floor(xs.length / 2)]; +const early = median(samples.slice(1, 1 + third).map((s) => s.heapUsed)); // skip the cold sample +const late = median(samples.slice(-third).map((s) => s.heapUsed)); +const growth = late - early; +const mb = (n: number) => (n / 2 ** 20).toFixed(1); + +console.table(samples.map((s) => ({ t: s.t, rssMB: mb(s.rss), heapMB: mb(s.heapUsed), handles: s.handles }))); +console.log( + `req/s ${load.requests.average}, p99 ${load.latency.p99} ms, errors ${load.errors}, non2xx ${load.non2xx}; ` + + `heap ${mb(early)} -> ${mb(late)} MB; unhandled ${last.unhandled}; close under load: exit ${code}`, +); + +const failures = [ + growth > 8 * 2 ** 20 && growth > early * 0.25 && `heap grew ${mb(growth)} MB`, + last.unhandled > 0 && `${last.unhandled} unhandled rejection(s)`, + load.non2xx > 0 && `${load.non2xx} non-2xx responses`, + code !== 0 && `close() under load: exit ${code}`, +].filter(Boolean); +if (code === 'timeout') child.kill('SIGKILL'); +if (failures.length) { + console.error(`SOAK FAILED: ${failures.join('; ')}`); + process.exit(1); +} +console.log('SOAK OK'); diff --git a/src/app/index.ts b/src/app/index.ts index 3b12075..9c1eb73 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -1,5 +1,5 @@ import type http from 'http'; -import { Bus, type Events } from '../bus'; +import { Bus, reportListenerErrors, type Events } from '../bus'; import { createDefaultLogger, logRequests, type Logger } from '../logger'; import { Container } from '../container'; import { topoSort, topoLevels, subgraphFor, GraphNode, nearest } from '../graph'; @@ -9,7 +9,7 @@ import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } fro import type { HttpOptions } from '../http'; import { trustedProxyClient } from '../http/peer'; import { answerFetchProbe, buildFetch } from '../http/web'; -import { resolveCompression, edgeMarker, MARK_EDGE, type CompressionOptions } from '../http/compression'; +import { resolveCompression, edgeMarker, isWorkerd, MARK_EDGE, type CompressionOptions } from '../http/compression'; import { boundInbound, controlBounds, @@ -45,7 +45,19 @@ import { getArgs, getHandlerNeeds, resolveArgs } from '../params'; import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; -import { TLS_REQUESTED, type TlsOptions, type SecurityOptions, type CorsOptions } from '../security'; +import { + TLS_REQUESTED, + WS_ORIGIN_CHECK, + assertCorsOptions, + MESH_REQUESTED, + NODE_ONLY_LIMITS, + nodeOnlyLimits, + MESH_ON_EDGE, + wsOriginAllowed, + type TlsOptions, + type SecurityOptions, + type CorsOptions, +} from '../security'; import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup'; import { buildManifest, @@ -135,7 +147,7 @@ export interface AppOptions { * * - `/__live__` answers `200 {"status":"ok"}` whenever the process answers. * - `/__ready__` answers `503 {"status":"booting"}` until `boot()` resolves, then - * `200 {"status":"ok"}` or `200 {"status":"degraded","degraded":[…]}` (see `app.degraded()`), + * `200 {"status":"ok"}` or `200 {"status":"degraded"}` (names in the boot log and `app.degraded()`), * and `503 {"status":"draining"}` from the moment `close()` starts. * * Probes skip the pipeline: no step, provider, plugin or `onError` runs and no lifecycle event is @@ -276,25 +288,43 @@ export interface AppOptions { warnGraphDepth?: number | false; } -/** - * Build an {@link App} from the given modules and options. - * Wires providers, steps, controllers and plugins into a dependency graph; for non-mesh apps - * the graph is finalized eagerly, otherwise finalization is deferred to {@link App.listen}. - */ -export function createApp(opts: AppOptions): App { +/** Throws for a `mesh` config this app cannot run: without the opt-in, or inside a Worker. */ +function assertMeshAllowed(opts: AppOptions): void { + if (!opts.mesh) return; + // mesh is alpha: its API and wire protocol may change. Require an explicit opt-in. - if (opts.mesh && !opts.experimental) { + if (!opts.experimental) { throw new Error( 'mesh is an alpha feature — pass `experimental: true` to createApp to enable it (its API may change between releases)', ); } + // Detected here so a bare `export default { fetch: app.fetch }` on a Worker fails too; `edgeHandler` + // refuses explicitly through MESH_REQUESTED for a Worker detection cannot see (#87). + if (isWorkerd()) throw new Error(MESH_ON_EDGE); +} + +/** + * Build an {@link App} from the given modules and options. + * Wires providers, steps, controllers and plugins into a dependency graph; for non-mesh apps + * the graph is finalized eagerly, otherwise finalization is deferred to {@link App.listen}. + */ +export function createApp(opts: AppOptions): App { + assertMeshAllowed(opts); validateWsLimits(opts.limits); const health = resolveHealth(opts.health, opts.shutdownTimeoutMs, opts.teardownTimeoutMs); assertEtagOption(opts.etag); + assertCorsOptions(opts.cors); const bus = new Bus(); const logger = opts.logger ?? createDefaultLogger(); + reportListenerErrors(bus, (event, error) => + logger.warn(`a listener on '${event}' threw and was skipped; further failures of that listener are not logged`, { + event, + err: error instanceof Error ? error.message : String(error), + }), + ); + assertTeapotTransport(opts.mesh, logger); if (opts.logRequests) logRequests(bus, logger); const container = new Container(); let server: http.Server | undefined; @@ -536,6 +566,17 @@ export function createApp(opts: AppOptions): App { // `serveDeno` and `serveBun` refuse an app that asked for TLS only Node's listener can give. [TLS_REQUESTED]: Boolean(opts.tls), + + // `serveDeno`, `serveBun` and `edgeHandler` warn that they ignore these (#76). + [NODE_ONLY_LIMITS]: nodeOnlyLimits(opts.limits), + + // `edgeHandler` refuses an app that configured mesh, which cannot run there (#87). + [MESH_REQUESTED]: Boolean(opts.mesh), + + // The fetch adapters refuse a cross-site upgrade before accepting it (GHSA-p697-fpqx-pgf3). The + // mesh control channel is exempt: it authenticates with its secret, not with cookies. + [WS_ORIGIN_CHECK]: (origin: string | null, host: string, path: string): boolean => + path === MESH_CONTROL_PATH || wsOriginAllowed(origin, host, opts.cors, logger), }); } @@ -1136,24 +1177,45 @@ async function connectUntilDeadline( } } +/** Whether `url` is a `ws://` link that leaves this machine. Loopback has no network path to read. */ +function crossesNetworkInCleartext(url: string): boolean { + if (!url.startsWith('ws://')) return false; + let host: string; + + try { + host = new URL(url).hostname; + } catch { + return true; // not ours to parse; treat it as the case that needs an explicit opt-in + } + + return !(host === 'localhost' || host === '[::1]' || /^127(\.\d{1,3}){3}$/.test(host)); +} + /** - * 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. + * Refuse a `ws://` teapot that is not on this machine, unless `allowInsecure` (#86). * - * 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. + * The `hello` frame carries the secret verbatim, so `ws://` to anywhere but loopback puts it on the + * wire for anyone in the path to read. Checked in `createApp`, before any connection, so the mistake + * is a boot error rather than a leak. A private network that already encrypts (a service mesh with + * mutual TLS) is a legitimate deployment green-tea cannot tell apart from an exposed one, so it can + * opt in, and is still warned about it. */ -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; +function assertTeapotTransport(mesh: MeshConfig | undefined, logger: Logger): void { + for (const { url } of mesh?.teapots ?? []) { + if (!crossesNetworkInCleartext(url)) continue; - 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.', - ); + if (!mesh?.allowInsecure) { + throw new Error( + `mesh: ${url} is not encrypted, and the shared secret is sent in the handshake. Use wss://, ` + + 'or set `mesh.allowInsecure: true` if the link already runs inside an encrypted network.', + ); + } + + logger.warn( + `mesh: ${url} is not encrypted, and the shared secret is sent in the handshake — ` + + 'allowed by `mesh.allowInsecure`; make sure the network encrypts it.', + ); + } } /** A route a teapot exported, and the teapot it came from. */ @@ -1468,7 +1530,6 @@ async function spliceRemoteScopes( try { for (const teapot of teapots) { - warnIfCleartext(teapot.url, logger); const holder: { link?: Link } = {}; const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => connectTeapot(ctx, teapot, holder)); @@ -1682,14 +1743,32 @@ function buildMeshControl( const { bus, providedSeed, planSteps, onError, logger } = deps.deps; const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes }); + // Each exported step runs with only what it needs: its own closure of providers and steps, sliced + // once here like a route's. Running every step on every call (#85) fired unexported side effects + // per RPC and let any unrelated step that threw break every export. Unlike a route, no always-on + // observer step is added: the teacup's own request already ran its observers. + const ordered = [...orderedProviders, ...orderedSteps]; + const slices = new Map( + exportedSteps.map((token) => { + const closure = new Set(subgraphFor([token], ordered)); + const providers = orderedProviders.filter((node) => closure.has(node)); + const steps = orderedSteps + .filter((node) => closure.has(node)) + .map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! })); + + return [token, { providers, steps }] as const; + }), + ); + const resolveScope = async (name: string, env: RequestEnvelope): Promise => { // context is intentionally `any`: providers and steps merge arbitrary keys into it const seed: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }; + // The teapot gates names before this runs, so an exported token always has a slice. + const { providers, steps } = slices.get(name)!; - for (const provider of orderedProviders) + for (const provider of providers) 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)! })); // 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. diff --git a/src/app/types.ts b/src/app/types.ts index e9ac091..bb0b045 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -194,6 +194,13 @@ export interface MeshConfig { * starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens. */ bootTimeoutMs?: number; + /** + * Allow `ws://` teapots that are not on this machine (default: `false`). The handshake sends the + * teapot's secret verbatim, so without this `createApp` refuses a cleartext link off loopback. Set + * it only when the network already encrypts the link, for example a service mesh with mutual TLS; + * each such teapot is still logged as a warning. + */ + allowInsecure?: boolean; } /** diff --git a/src/bun.ts b/src/bun.ts index b2d71d6..3ac6e57 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -1,7 +1,7 @@ import { channel } from './channel'; import type { Channel } from './channel'; import type { App } from './app/types'; -import { refuseTls } from './security'; +import { refuseTls, refuseWsOrigin, warnNodeOnlyLimits } from './security'; import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, @@ -120,13 +120,17 @@ export async function serveBun(app: App, options?: BunServeOptions): Promise void>(); + +/** Listeners already reported, so a broken one logs once rather than on every event (#77). */ +const reportedListeners = new WeakSet<(p: EventPayload) => void>(); + +/** Internal: route listener failures on `bus` to `report`, once per listener. Not in the public barrel. */ +export function reportListenerErrors(bus: Bus, report: (event: LifecycleEvent, error: unknown) => void): void { + listenerErrorReporters.set(bus, report); +} + /** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */ export class Bus { private readonly listeners = new Map void>>(); @@ -189,13 +203,35 @@ export class Bus { return listenerSet !== undefined && listenerSet.size > 0; } + private reportFailure(event: LifecycleEvent, listener: (p: EventPayload) => void, error: unknown): void { + const report = listenerErrorReporters.get(this); + if (!report || reportedListeners.has(listener)) return; + + reportedListeners.add(listener); + + try { + report(event, error); + } catch { + /* a broken logger must not break the pipeline either */ + } + } + /** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */ emit(event: LifecycleEvent, payload: EventPayload): void { for (const listener of this.listeners.get(event) ?? []) { try { - listener(payload); - } catch { - /* observers must never break the pipeline */ + // An async listener's failure arrives as a rejection, not a throw. Unhandled, it exits Node + // (#70), so it gets the same isolation as a sync throw. + const result: unknown = listener(payload); + + if (typeof (result as PromiseLike | undefined)?.then === 'function') { + (result as PromiseLike).then(undefined, (error: unknown) => + this.reportFailure(event, listener, error), + ); + } + } catch (error) { + // observers must never break the pipeline, but a silent failure hides a broken plugin (#77) + this.reportFailure(event, listener, error); } } } diff --git a/src/channel.ts b/src/channel.ts index 435856e..5ec0017 100644 --- a/src/channel.ts +++ b/src/channel.ts @@ -28,6 +28,43 @@ export function releaseIterator(iterator: AsyncIterator | undefined): v } } +/** + * Internal: races each promise it is given against one long-lived `stop`, without leaking. + * `Promise.race([p, stop])` leaves a reaction on `stop` per call, and they are only freed when + * `stop` settles, so a stream that sends for an hour kept one per event: the soak job measured + * ~0.4 MB/s of heap on a 1 kHz SSE stream (#80). Here `stop` holds a single reaction, which settles + * the call in flight. One call at a time, as the stream loops use it. Not exported from the package. + */ +export function raceUntil(stop: Promise): (p: Promise) => Promise { + // 0 pending, 1 resolved, 2 rejected. The resolvers of the call in flight are kept bare and passed + // straight to `then`, with no wrapper closure per call: this runs once per stream event. + let ended = 0; + let reason: unknown; + let wake: ((v: undefined) => void) | undefined; + let fail: ((e: unknown) => void) | undefined; + + stop.then( + () => { + ended = 1; + wake?.(undefined); + }, + (err: unknown) => { + ended = 2; + reason = err; + fail?.(err); + }, + ); + + return (p: Promise) => { + if (ended) return ended === 1 ? Promise.resolve(undefined) : Promise.reject(reason); + return new Promise((resolve, reject) => { + wake = resolve; // a stale resolver left here after p settles is harmless: settling twice is a no-op + fail = reject; + p.then(resolve, reject); + }); + }; +} + /** * Internal: reads a channel synchronously, inside `push`, rather than through an async iterator * that only drains once the event loop yields. `boundInbound` needs it to bound a WebSocket burst @@ -48,6 +85,12 @@ export interface TappableChannel extends Channel { [CHANNEL_TAP](sink: ChannelSink): () => void; } +/** + * Internal: the per-subscriber cap when `channel()` is given none (#82). Unbounded before, so a slow SSE + * client on a busy channel grew server memory without limit. Not exported from the package. + */ +export const DEFAULT_CHANNEL_BUFFER = 1024; + interface Sub { iterator: AsyncIterator; push(value: T, cap: number): void; @@ -116,10 +159,12 @@ function newSub(onReturn: () => void): Sub { /** * Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber. - * @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded). + * @param opts.buffer Per-subscriber queue cap; drops the oldest value when exceeded (default: + * {@link DEFAULT_CHANNEL_BUFFER}). Pass `Infinity` to never drop, at the cost of unbounded memory + * for a subscriber that stops reading. */ export function channel(opts: { buffer?: number } = {}): Channel { - const cap = opts.buffer ?? Infinity; + const cap = opts.buffer ?? DEFAULT_CHANNEL_BUFFER; const subs = new Set, 'iterator'>>(); let done = false; let closedFlag = false; diff --git a/src/deno.ts b/src/deno.ts index 4ee4bdf..b448164 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -1,5 +1,5 @@ import type { App } from './app/types'; -import { refuseTls } from './security'; +import { refuseTls, refuseWsOrigin, warnNodeOnlyLimits } from './security'; import { beginDrain } from './http/health'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { closeWithDeadline } from './http/shutdown'; @@ -69,6 +69,7 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { + const refused = refuseWsOrigin(app, request); + if (refused) return refused; + // Deno invalidates request connection metadata as soon as the upgrade is accepted. const wsRequest = toWsRequest(request, info.remoteAddr.hostname); const { socket, response } = Deno.upgradeWebSocket(request); diff --git a/src/edge.ts b/src/edge.ts index 8f141d4..28218c2 100644 --- a/src/edge.ts +++ b/src/edge.ts @@ -2,6 +2,7 @@ import type { App } from './app/types'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { setProxyClient } from './http/peer'; import { MARK_EDGE } from './http/compression'; +import { refuseMeshOnEdge, refuseWsOrigin, warnNodeOnlyLimits } from './security'; // Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types. // Declares only what we call; mirrors the real workerd signatures. @@ -32,10 +33,15 @@ declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } }; export function edgeHandler( app: App, ): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise { + refuseMeshOnEdge(app); + warnNodeOnlyLimits(app, 'edgeHandler'); (app as { [MARK_EDGE]?: () => void })[MARK_EDGE]?.(); return (request, _env, ctx) => { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { + const refused = refuseWsOrigin(app, request); + if (refused) return refused; + const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket]; server.accept(); // No peer address on the edge, so `ip` starts empty; the header only fills it under `trustProxy`. diff --git a/src/encoders.ts b/src/encoders.ts index 2e4d687..db730aa 100644 --- a/src/encoders.ts +++ b/src/encoders.ts @@ -1,3 +1,5 @@ +import { isHttpError } from './signals'; + /** * Serializes stream items into wire frames for a streaming transport (SSE, NDJSON). * `headers` is written once before the first frame; `ping` (if present) is sent periodically to keep the connection alive. @@ -9,7 +11,13 @@ export interface StreamEncoder { ping?(): string; } -const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error)); +/** + * The text a stream's error frame may show its client: an `HttpError`'s message, which the app wrote + * for the client, and a generic one for anything else, exactly as a buffered route's 500 does. A raw + * `err.message` can hold a connection string or a host (GHSA-235j-fx64-w9p9); the full error still + * goes to the `stream:error` event. + */ +const messageOf = (error: unknown): string => (isHttpError(error) ? error.message : 'Internal Server Error'); // Registered globally rather than module-local: this package ships twice — a bundle on npm and raw // source on JSR — so two copies in one dependency tree is a real shape, and a marker that stopped diff --git a/src/graph-viz.ts b/src/graph-viz.ts index 2169c03..aa64f5e 100644 --- a/src/graph-viz.ts +++ b/src/graph-viz.ts @@ -86,9 +86,9 @@ export function graphHtml(view: GraphView): string { return ` green-tea graph - - - + + +