diff --git a/CHANGELOG.md b/CHANGELOG.md index cd43a36..4418446 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,17 +13,41 @@ green-tea uses calendar versioning: `YY.MM.PATCH`. bring-your-own hook, and zero-config `static` directory serving (`createApp({ static: true })`). File and static serving require a filesystem (Node/Deno/Bun); string-mode `@Html` runs everywhere. - **`app.fetch(request): Promise`** — a Web-Standards handler so the - same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API - (WebSocket and mesh remain Node-only). + same app runs HTTP and SSE on Deno/Bun/edge runtimes via the Fetch API. - **Deno adapter** (`@green-tea/core/deno`): `serveDeno(app)` runs HTTP + SSE + WebSocket on Deno. - **Bun adapter** (`@green-tea/core/bun`): `serveBun(app)` runs HTTP + SSE + WebSocket on Bun, reusing the neutral `app.upgrade` / `WsSocket` capability. WebSocket, rooms, and channels behave identically to Node and Deno. - **Cloudflare Workers / edge adapter** (`@green-tea/core/edge`): `edgeHandler(app)` runs HTTP + SSE + WebSocket on workerd, reusing the neutral `app.upgrade` / `WsSocket` capability. Requires the `nodejs_compat` compatibility flag. Green Tea now runs on Node, Deno, Bun, and the edge — with identical WebSocket, rooms, and channel behaviour on all four. - **`app.upgrade(request, socket)`**: neutral WebSocket entry point for non-Node runtimes, built on a shared `WsSocket` capability. WebSocket logic is now runtime-agnostic (`src/http/ws-core.ts`). +- **Mesh (alpha) runs on Node, Deno and Bun** — teapot *and* teacup, in any combination + (a Deno teapot can serve a Node teacup). It no longer needs `app.listen()`: the graph boots on + first use, so `serveDeno`/`serveBun` work through `app.fetch`/`app.upgrade`. Edge is **not** + supported — the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which + `nodejs_compat` does not provide. +- **`MESH_PROTOCOL_VERSION`**: the mesh wire is versioned. Peers exchange it in the `hello`/`manifest` + frames and refuse a mismatch, naming both versions, instead of misreading each other's frames. + The teapot checks the version *before* the secret — a skewed peer is not an auth failure. +- **`HttpError` accepts `headers`**, so a custom error can carry its own response headers + (`retry-after`, `etag`, …) without a special case in the error renderer. ### Fixed - The opt-in dev routes `/__graph__` (graph viewer) and `/__openapi__` are now served over `app.fetch` too, so they work on every runtime (Deno/Bun/edge), not only the Node `app.listen()` path. +- **`request:step:enter`/`leave` are now emitted for `@Ws` and mesh routes.** Only HTTP routes + emitted them, so a logging plugin silently observed nothing on a WebSocket route — a gap in a + documented plugin API. All transports now run their steps through one path. +- **A mesh route exported by two teapots now fails the boot**, naming the route and both teapots, + instead of silently serving whichever connected first and leaving the other dead. There is no + load balancing to fall back on, so green-tea will not pick for you. +- **A local route shadowing a remote one now warns.** Local still takes precedence — that is how you + override a teapot — but a silently shadowed export used to look like a broken teapot. +- **`app.close()` closes mesh links even with no server**, so a mesh app booted through `app.fetch` + (every Deno/Bun deployment) no longer leaks its teapot connections. +- **WebSocket frames arriving during boot are no longer dropped.** `app.upgrade` awaited the boot + before handing the socket to a consumer, and the inbound channel is fan-out, so a peer that spoke + first lost those frames — for mesh, that was the handshake itself. +- The plugins guide documented a `request:step:exit` event that has never existed; the bus emits + `request:step:leave`. ### Changed - App-scope providers now boot exactly once (memoized): a second `app.listen()` diff --git a/src/app/index.ts b/src/app/index.ts index f6c34e5..98e967e 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -503,6 +503,19 @@ async function spliceRemoteScopes( } routeOwners.set(key, teapot.url); + + // Local routes are merged ahead of remote ones (see buildHttpRoutes), so a local twin + // wins. That precedence is deliberate — your own code beats an imported one, and it is + // how you override a teapot — but silently shadowing an export looks exactly like a + // broken teapot from the outside. Warn and let the developer decide. + if (registry.routePlans.some((plan) => plan.method === route.method && plan.pattern === route.pattern)) { + console.warn( + `[green-tea] mesh: route '${key}' is exported by teapot ${teapot.url} but also declared locally — ` + + 'the local route takes precedence and the remote one will not be reached. ' + + 'Remove one if that is not what you meant.', + ); + } + remoteRoutes.push({ method: route.method, pattern: route.pattern, diff --git a/test/mesh/integration.test.ts b/test/mesh/integration.test.ts index 3108417..f7321c9 100644 --- a/test/mesh/integration.test.ts +++ b/test/mesh/integration.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { createApp, Provider, Step, Route, Get, Module, needs } from '../../src/index'; const SECRET = 's3cr3t'; @@ -45,6 +45,17 @@ class PlainCtl { @Module({ mountpoint: '/', controllers: [PlainCtl] }) class PlainTeacupModule {} +// A teacup declaring a route locally at the same path a teapot exports it. +@Route('/dup') +class ShadowCtl { + @Get('/ping') + ping() { + return { from: 'local' }; + } +} +@Module({ mountpoint: '/api', controllers: [ShadowCtl] }) +class ShadowTeacupModule {} + describe('mesh skeleton integration', () => { it('teacup resolves remote app-scope + request-scope into a local handler', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); @@ -119,6 +130,59 @@ describe('mesh skeleton integration', () => { aServer.close(); }); + it('gives a local route precedence over a remote one, and says so', async () => { + // Local-wins is the design: your own code beats an imported one, and it is how you + // override a teapot. But it used to be an accident of [...local, ...remote] ordering + // with nothing said, so a shadowed export looked like a broken teapot. + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const teapot = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`; + + const teacup = createApp({ + modules: [ShadowTeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + try { + const res = await teacup.fetch(new Request('http://x/api/dup/ping')); + expect(await res.json()).toEqual({ from: 'local' }); // local wins, not the teapot's {pong:true} + + const warned = warn.mock.calls.map((c) => String(c[0])).join('\n'); + expect(warned).toMatch(/GET \/api\/dup\/ping/); + expect(warned).toMatch(/local/i); + expect(warned).toContain(url); // which teapot got shadowed + } finally { + warn.mockRestore(); + await teacup.close(); + tServer.close(); + } + }); + + it('does not warn when a remote route has no local twin', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const teapot = createApp({ modules: [DupTeapotModule], experimental: true, mesh: { secret: SECRET } }); + const tServer = await teapot.listen(0); + const url = `ws://127.0.0.1:${(tServer.address() as any).port}/__mesh__/control`; + + const teacup = createApp({ + modules: [PlainTeacupModule], + experimental: true, + mesh: { teapots: [{ url, secret: SECRET }] }, + }); + + try { + await teacup.fetch(new Request('http://x/c/ok')); + const shadowWarnings = warn.mock.calls.filter((c) => String(c[0]).includes('precedence')); + expect(shadowWarnings).toEqual([]); + } finally { + warn.mockRestore(); + await teacup.close(); + tServer.close(); + } + }); + it('rejects a bad secret (teacup boot fails)', async () => { const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: SECRET } }); const tServer = await teapot.listen(0); const tPort = (tServer.address() as any).port; diff --git a/website/src/content/docs/guides/mesh.md b/website/src/content/docs/guides/mesh.md index fe9bfae..c0cf60d 100644 --- a/website/src/content/docs/guides/mesh.md +++ b/website/src/content/docs/guides/mesh.md @@ -11,6 +11,19 @@ A **teacup** can depend on a token that physically lives on another node — a * Exports are opt-in (`export: true`) and the control channel is gated by a shared secret. +## What runs where + +Mesh runs on **Node, Deno and Bun**, as both teapot and teacup, in any combination — a Deno teapot can serve a Node teacup. The wire is JSON over a WebSocket, so peers only have to agree on the protocol version, not the runtime. + +**Edge (Cloudflare Workers) is not supported.** The teapot's secret comparison uses `node:crypto`'s `timingSafeEqual`, which workerd's `nodejs_compat` does not provide. + +You do **not** need `listen()`. The graph boots on first use, so `Deno.serve`/`Bun.serve` work through `app.fetch`/`app.upgrade` like any other route: + +```typescript +serveDeno(teapot, { port: 3002 }); // control channel served via app.upgrade +serveBun(teacup, { port: 3003 }); // teapots connected on the first request +``` + ## Node A — teapot (exposes `config`, `auth`, and a route) ```typescript @@ -60,7 +73,37 @@ await teacup.listen(3003); - A **provider** export is **app-scope** — resolved once and cached. - A **step** export is **request-scope** — one RPC per request, carrying the request envelope. -Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; mesh apps defer graph finalization to `listen()` so remote scopes can join first. +Remote tokens become synthetic nodes in the local graph with RPC-backed runners, so the rest of the pipeline is unchanged. For non-mesh apps `createApp` stays synchronous; a mesh app defers graph finalization until it boots — connecting to teapots is network I/O — and boots on whichever comes first: `app.fetch`, `app.upgrade` or `listen()`. Whoever triggers it, it happens once. + +## Buffered routes only + +Mesh proxies **buffered** endpoints. `@Sse`, `@Stream` and `@Ws` routes are not exportable: a remote route is registered as `transport: 'buffer'`, and a handler that returns an `AsyncIterable` over a mesh call fails with `cannot proxy a streaming route`. Streams are a live socket between client and server; there is no meaningful way to relay one through an RPC hop today. + +## One teapot per route + +A route must be exported by exactly **one** teapot. If two export the same `method + pattern`, the boot **fails**, naming the route and both teapots: + +``` +mesh: route 'GET /api/svc/ping' is exported by more than one teapot +(ws://a/__mesh__/control and ws://b/__mesh__/control) — load balancing across +teapots is not implemented yet, so green-tea will not choose one for you. +``` + +This is a hard error rather than a silent pick because there is no load balancing to fall back on: choosing one would be an arbitrary answer you could come to depend on. Scope tokens (`@Provider`/`@Step`) are unique for the same reason — and balancing them would be meaningless anyway, since an app-scope export is resolved once and cached. + +**Local routes win.** If you declare a route locally *and* import it from a teapot, yours takes precedence — that is how you override a teapot — and green-tea warns so a shadowed export doesn't look like a broken one: + +``` +[green-tea] mesh: route 'GET /api/svc/ping' is exported by teapot ws://a/… but also +declared locally — the local route takes precedence and the remote one will not be +reached. Remove one if that is not what you meant. +``` + +## Protocol version + +Peers are separate processes on separate deploy cadences, so the wire is versioned: `MESH_PROTOCOL_VERSION` travels in the `hello` and `manifest` frames, and a mismatch is refused on both sides with both versions named. A teapot checks the version **before** the secret — a skewed peer is not an authentication failure, and reporting it as one would send you hunting the wrong bug. + +Bump the version and old peers refuse the connection loudly instead of misreading a frame. :::note[Skeleton limitations (by design)] No discovery, load-balancing, or failover yet; app-scope remote values are not reconciled on reconnect; the request envelope omits `req.url`. diff --git a/website/src/content/docs/guides/runtimes.md b/website/src/content/docs/guides/runtimes.md index e2f8c73..6ce091e 100644 --- a/website/src/content/docs/guides/runtimes.md +++ b/website/src/content/docs/guides/runtimes.md @@ -27,8 +27,9 @@ and body for the same request (enforced by a parity test suite). **All four runtimes now have full WebSocket support:** Node, Deno, and Bun via `serveDeno` / `serveBun`, and Cloudflare Workers / edge via `edgeHandler` (see below) — same graph, same -`@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS, per-request timeouts, -and mesh remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. +`@Ws` handlers, same rooms/channels everywhere. `app.listen()`, TLS and per-request timeouts +remain Node-only; on Deno/Bun/edge you get `app.fetch` + the runtime's adapter. **Mesh (alpha) +runs on Node, Deno and Bun** — teapot and teacup, in any combination — but not on edge. **Body-size enforcement differs slightly:** on `app.fetch`, an oversized body is read in full before the `413` is returned, whereas Node aborts mid-stream once the limit is hit — so on @@ -58,8 +59,9 @@ Any runtime can build a `WsSocket` capability (`inbound`, `abort`, `isOpen`, `se `close`, `terminate`) and drive the graph — `serveBun` and `edgeHandler` build on the same primitive (see below). -**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Deno you -get `app.fetch` + `serveDeno`. +**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Deno you get +`app.fetch` + `serveDeno`. [Mesh](/guides/mesh/) works here: the control channel is +served through `app.upgrade` and the teacup connects with Deno's global `WebSocket`. ## WebSocket on Bun @@ -80,8 +82,8 @@ serveBun(app, { port: 8000 }); `app.upgrade` — the same graph, the same `@Ws` handlers, the same rooms/channels you run on Node and Deno. Behaviour matches the Node reference. -**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. On Bun you -get `app.fetch` + `serveBun`. +**Still Node-only:** `app.listen()`, TLS and per-request timeouts. On Bun you get +`app.fetch` + `serveBun`. [Mesh](/guides/mesh/) works here too. ## Cloudflare Workers / edge @@ -113,7 +115,9 @@ compatibility_date = "2024-09-23" # or later Green Tea's core statically imports Node built-ins that workerd only provides under this flag; without it, the Worker fails to load. -**Still Node-only:** `app.listen()`, TLS, per-request timeouts, and mesh. Cloudflare's +**Still Node-only:** `app.listen()`, TLS and per-request timeouts. [Mesh](/guides/mesh/) +is **not** supported on edge: the teapot's secret comparison needs `node:crypto`'s +`timingSafeEqual`, which `nodejs_compat` does not provide. Cloudflare's Durable Objects and WebSocket Hibernation are **not** used — `edgeHandler` accepts WebSockets with the standard `WebSocketPair` model, so a Worker holds the connection open for its lifetime rather than hibernating between messages.