Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import starlightLlmsTxt from 'starlight-llms-txt';
* not. It is shown on every page because a reader arriving from a search result has no other way
* to tell whether what they are reading matches what they installed.
*/
export const documentsCoreVersion = '26.11.0-rc.1';
export const documentsCoreVersion = '26.11.0-rc.2';

// Docs site for @green-tea/core. Content lives in src/content/docs/**.
export default defineConfig({
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "green-tea-docs",
"type": "module",
"private": true,
"version": "26.11.0-rc.1",
"version": "26.11.0-rc.2",
"scripts": {
"dev": "astro dev",
"clean": "rm -rf dist .astro node_modules/.astro",
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/guides/ai-agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ It matches the installed version and overrides what you know about Express-style
**Deno (JSR).** There is no `node_modules`; link the copy on JSR for your version:

```md
https://jsr.io/@green-tea/core/26.11.0-rc.1/llms.txt
https://jsr.io/@green-tea/core/26.11.0-rc.2/llms.txt
```

**Chat tools with no file access.** Paste the file in, or give it this URL if the tool can fetch:
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/guides/arguments.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ graph.
in, plus built-ins. Use it to read values like `ctx.protocol` and `ctx.ip`.

`ctx.ip` is the client address: the socket peer, or, when `trustProxy` is on and the request has
an `X-Forwarded-For` header, that header's first hop. On the edge, under `trustProxy`,
an `X-Forwarded-For` header, that header's last (right-most) entry: the address your proxy saw. On the edge, under `trustProxy`,
`cf-connecting-ip` wins over both, because Cloudflare sets it itself. A bare `app.fetch(request)`
from your own code has no socket, so there it is `''` unless a trusted header supplies it.

Expand Down
2 changes: 2 additions & 0 deletions src/content/docs/guides/html.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ const app4 = createApp({ modules: [ApiModule], static: { dir: 'assets', cacheCon
- Files are served at their URL path; content-type is inferred from the extension.
- `/` (and any directory-shaped path) resolves to `index.html`.
- Only `GET` and `HEAD` are handled — other methods fall through.
- **Dotfiles are never served.** A path with any segment starting with `.` (`/.env`, `/.git/config`)
is a `404`. Under `/.well-known/` the directory is served, but a dotfile inside it still is not.
- **Declared routes always win.** Static is only consulted when nothing matched, so `@Get('/api/ping')` is never shadowed by a file at `public/api/ping`.
- Path traversal (`../`, encoded or not) is rejected — a request can't escape the static root.
- Symlinks are confined to the root too. A file, or a directory's `index.html`, is served only if
Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/guides/introspection.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ const app = createApp({ modules: [ApiModule], health: true });
|---|---|
| booting — until `boot()` resolves | `503 {"status":"booting"}` |
| ready | `200 {"status":"ok"}` |
| ready, with degraded optional providers | `200 {"status":"degraded","degraded":["cache"]}` (from `app.degraded()`) |
| ready, with degraded optional providers | `200 {"status":"degraded"}`. The names are in the boot log and `app.degraded()`, not in a public probe. |
| draining — from the moment `close()` starts | `503 {"status":"draining"}` |

The state only moves forward: a boot that finishes after `close()` started stays draining.
Expand Down
76 changes: 73 additions & 3 deletions src/content/docs/guides/mesh.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Exports are opt-in (`export: true`) on **steps and routes** — a provider canno

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.
**Edge (Cloudflare Workers) is not supported.** The teapot's secret comparison uses `node:crypto`'s `timingSafeEqual`, which workerd's `nodejs_compat` does not provide, and a teacup's links are long-lived outbound sockets a Worker cannot hold. `createApp` with `mesh` throws inside a Worker, and so does `edgeHandler` given such an app, so the mistake surfaces at startup rather than on some later request.

You do **not** need `listen()`. `serveDeno` and `serveBun` boot the graph before they bind, so a teacup has reached its teapots — or spent its `bootTimeoutMs` grace trying — by the time the port opens:

Expand Down Expand Up @@ -63,7 +63,7 @@ class TeacupModule {}
const teacup = createApp({
modules: [TeacupModule],
experimental: true,
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
mesh: { teapots: [{ url: 'wss://A-host:3002/__mesh__/control', secret: 'shh' }] },
});
await teacup.listen(3003);
// GET B:3003/api/local/who (x-token: abc)
Expand All @@ -76,8 +76,78 @@ await teacup.listen(3003);

That is also why a **provider cannot be exported**. A provider is a factory whose value *is* the object it builds — a pool, a client, a `db` — and an object is not what a JSON wire carries. What used to cross was whatever half of it survived serialization, cached app-scope on the teacup for the life of the process, out of a cache the teapot no longer stood behind. Export a `@Step` that returns what the provider's value carried instead; the [next section](#what-can-cross-data-never-behaviour) has the shape.

On the teapot, a call runs the exported step and only what that step needs: the providers and steps in its own closure, sliced once at boot the way a route's are. A step nobody asked for does not run, and one that throws cannot break an export that does not depend on it.

A route is exported per method: `@Get('/items/:id', { export: true })` exports the `GET`, and a teacup asking for a `DELETE` on the same pattern is refused unless that handler is exported too. When a remote step fails, its client sees what it would see locally: an `HttpError`'s status and message, or `500 Internal Server Error` for anything else. The full error stays on the teapot, in its `mesh:rpc:error` event.

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.

## A complete example: one REST API on two processes

The core repository has a runnable version of all of this in [`example/mesh/`](https://github.com/Expressive-Tea/green-tea/tree/develop/example/mesh): a small shop split across two nodes, with a test that runs it as two real processes.

- **`billing.ts`** is the teapot. It owns a ledger, which it never exports, and exports a step, `balance`, plus its REST routes under `/billing`.
- **`shop.ts`** is the teacup. Its checkout route needs `balance` exactly as it would need a local step, and it serves billing's routes as if they were its own.

The two halves that matter:

```typescript
// billing.ts: computed on billing, per request, from the caller's route params
@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((i) => !i.paid).reduce((sum, i) => sum + i.amount, 0);
return { balance: { customer, due } };
}
}

@Route('/billing')
class BillingController {
@Get('/invoices/:customer', { export: true })
list(@needs('ledger') ledger: Ledger, @param('customer') customer: string) { /* … */ }

@Post('/invoices/:customer', { export: true })
create(@needs('ledger') ledger: Ledger, @param('customer') customer: string, @body() data: { amount?: unknown }) { /* … */ }
}
```

```typescript
// shop.ts: nothing here says where `balance` lives; only the mesh config does
@Route('/shop')
class CheckoutController {
@Get('/checkout/:customer')
checkout(@needs('balance') balance: { customer: string; due: number }) {
return { customer: balance.customer, due: balance.due, canCheckout: balance.due === 0 };
}
}

createApp({
modules: [ShopModule],
experimental: true,
mesh: {
teapots: [{ url: 'ws://127.0.0.1:3401/__mesh__/control', secret }],
reconnect: { initialDelayMs: 100, maxDelayMs: 1_000 },
},
});
```

Run it from a checkout of the core repository. 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, in a second terminal
```

```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
```

Now stop billing. The shop keeps running, and everything that needs billing answers `503` with `retry-after`: the checkout, and billing's own routes. Start billing again and the shop reconnects on its own within about a second. The ledger lives in memory, so it starts over. That is the whole failure story of a teapot that [goes away](#when-a-teapot-goes-away) and [comes back](#reconnecting), on your machine, in four commands.

## Inspecting a mesh graph

`inspect()`, `graph()` and `explain()` are synchronous, but a mesh graph is not knowable until its teapots have been asked — so on a mesh app they throw until the graph is resolved. `await app.ready()` resolves it:
Expand Down Expand Up @@ -282,7 +352,7 @@ The channel is authenticated, but an unauthenticated peer still gets to send byt
On Node a peer that sends more than 64 KiB before its `hello` is dropped before `ws` assembles the frame. Bun and Deno offer no per-socket limit to hold that to, so there an unauthenticated peer can still make the teapot receive one frame up to the post-`hello` bound before it is refused. If untrusted peers can reach a Bun or Deno teapot's `/__mesh__/control`, limit frame size at the proxy in front of it.

:::caution[The secret travels in the handshake]
The shared secret is sent verbatim in the `hello` frame. Over `ws://` that puts it in front of anyone on the path, so **use `wss://`** unless the link already runs inside an encrypted network. green-tea warns at boot for a `ws://` teapot that is not on loopback — a warning rather than a refusal, because a private network doing its own mutual TLS is a real deployment and the framework cannot tell the two apart.
The shared secret is sent verbatim in the `hello` frame. Over `ws://` that puts it in front of anyone on the path, so **use `wss://`**. `createApp` refuses a `ws://` teapot that is not on loopback (`localhost`, `127.0.0.0/8`, `[::1]`), before anything connects. A private network that already encrypts the link, such as a service mesh doing mutual TLS, is a real deployment the framework cannot tell apart from an exposed one, so it can opt in with `mesh: { allowInsecure: true }`; each such teapot is still logged as a warning.
:::

## Protocol version
Expand Down
12 changes: 9 additions & 3 deletions src/content/docs/guides/runtimes.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ Same API is not the same behaviour in every detail. The differences this page co
`<= 0` leave Node's connection count unlimited. Positive values map to Node's
`server.maxConnections` when the app runs through `app.listen()`. When the cap is reached, Node
destroys excess sockets without sending an HTTP response. `Deno.serve` and `Bun.serve` expose no
equivalent active-socket cap, so `serveDeno` and `serveBun` cannot enforce this option. Apply the
equivalent active-socket cap, so `serveDeno` and `serveBun` cannot enforce this option. They, and
`edgeHandler`, warn through the app's logger at startup, naming each Node-only limit the app set
(`maxConnections`, `requestTimeoutMs`, `headersTimeoutMs`, `keepAliveTimeoutMs`). Apply the
connection limit at the deployment platform or reverse proxy on those runtimes.

`limits.maxConcurrentRequests` is separate from the connection limit and applies per server or Fetch adapter instance, so an app using both `app.listen()` and `app.fetch` has two independent request budgets. It bounds concurrently executing handlers; a handler that never returns continues to hold its slot, while on Node a client disconnect releases that slot. Excess requests receive `503 Service Unavailable` with `Retry-After: 1`.
Expand Down Expand Up @@ -285,7 +287,8 @@ A `@Ws` handler's outbound iterator is pulled only while the socket's send buffe

`serveDeno()` and `serveBun()` give `app.fetch` the socket peer, so `ctx.ip` is populated on Deno and
Bun as it is on Node. All three follow one rule: with `trustProxy` on and an `X-Forwarded-For`
header present, `ctx.ip` is the header's first hop; otherwise it is the socket peer. That includes
header present, `ctx.ip` is the header's right-most entry, the one your proxy appended; otherwise it
is the socket peer. That includes
`trustProxy` with no `X-Forwarded-For`, which falls back to the peer.

`ctx.ip` is resolved the first time a step, a handler or a plugin reads it, and kept for the rest of
Expand All @@ -299,7 +302,10 @@ the request; a route that never reads it pays nothing. What reading it costs dep
| edge | the `cf-connecting-ip` header, under `trustProxy` | negligible |

Behind a proxy that sets `X-Forwarded-For`, `trustProxy: true` takes the address from the header on
every runtime and never asks the socket. Inside a stream body `ctx.ip` is `''` unless a step or the
every runtime and never asks the socket. It takes the right-most entry because the client writes
everything to the left of it: up to RC.1 core took the left-most, so a client that sent
`X-Forwarded-For: 6.6.6.6` got that address in `ctx.ip`. Behind a chain of several proxies, the
right-most entry is the address the last proxy saw. Inside a stream body `ctx.ip` is `''` unless a step or the
handler read it before returning the stream, because the socket may already be gone by then.

Addresses are passed through as each runtime reports them. The IPv6 loopback is `::1` on all three,
Expand Down
30 changes: 23 additions & 7 deletions src/content/docs/guides/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ const app = createApp({ modules: [App], trustProxy: true });
```

Behind a reverse proxy, reads `X-Forwarded-Proto` / `X-Forwarded-For` to populate
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`). Off by default —
`ctx.protocol` (`'http' | 'https'`) and `ctx.ip` (read via `@ctx()`), on every runtime. `ctx.ip` is
the **right-most** `X-Forwarded-For` entry, the one your proxy appended; the entries to its left are
whatever the client sent. Off by default —
forwarded headers are ignored (and spoofable) until you opt in. It trusts the immediate hop
unconditionally; there's no CIDR allowlist yet.

Expand All @@ -62,6 +64,9 @@ route or the router's automatic `204` + `Allow` response.

- With `credentials: true`, the server **never** sends `Access-Control-Allow-Origin: *` — it
echoes the concrete allowed origin (or blocks the request).
- `origins: '*'` with `credentials: true` **fails `createApp`**. Together they would let any site
make credentialed reads. List the trusted origins, or, if an open credentialed API is really the
intent, write it as a predicate (`origins: () => true`) so the decision is visible in the code.

### When `origins` is a predicate

Expand All @@ -79,11 +84,6 @@ that failed has not said yes, and a backing store being briefly unavailable must
allowlist. Watch the logs for it — from the outside, a broken lookup and a genuinely disallowed
origin look the same to the caller, which is the price of failing closed.

:::caution[Reflect-any foot-gun]
`origins: '*'` together with `credentials: true` reflects *any* origin with credentials
attached. Only combine them if you truly intend an open credentialed API; prefer an explicit
allowlist.
:::

## `security` (headers, ON by default)

Expand All @@ -108,6 +108,19 @@ const app = createApp({ modules: [App], security: { csp: "default-src 'self'" }
WebSocket handshake (101/upgrade) response.
:::

## WebSocket origins

CORS does not apply to WebSockets: a browser opens one from any page and sends the user's cookies
with it. So every adapter checks the upgrade's `Origin` itself, and refuses with `403` unless:

- there is no `Origin` header (not a browser: a server, a CLI, a test client),
- the `Origin` is on the same host as the request, or
- `cors.origins` allows it.

`Origin: null` is refused. The mesh control channel is exempt, since it authenticates with its
secret. A browser client served from another origin, or an app behind a proxy that rewrites `Host`,
needs that origin in `cors.origins`.

:::caution[TLS + trustProxy]
HSTS is emitted only when the connection is judged secure. With `trustProxy: true` that
judgement trusts the incoming `X-Forwarded-Proto` header — so a client that spoofs
Expand All @@ -126,7 +139,10 @@ These hold by default, with nothing to turn on:
(`maxWsMessageBytes`, `maxWsQueue`), closing with `1009` / `1013`:
[streaming](/docs/guides/streaming/#inbound-limits).
- **Static files** never resolve outside the static root, through `../` or through a symlink, and
an escape is a `404`, not a `403`: [HTML & views](/docs/guides/html/#static-files--createapp-static-).
an escape is a `404`, not a `403`. Dotfiles (`/.env`, `/.git/config`) are never served: [HTML & views](/docs/guides/html/#static-files--createapp-static-).
- **Slow clients** cannot hold Node's connection slots: a socket still sending headers past
`headersTimeoutMs` is closed within a second, and a WebSocket peer that stops answering pings is
dropped within a minute.
- **`ctx.ip`** is the client address on Node and through `serveDeno()` / `serveBun()`, so anything
keyed on it, such as a rate limiter, does not put every client in one bucket:
[runtimes](/docs/guides/runtimes/#the-client-address--ctxip).
Expand Down
11 changes: 9 additions & 2 deletions src/content/docs/guides/streaming.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,16 @@ So decide which kind of source you have, and say so:
### When a stream fails part-way

A source that throws mid-stream is reported the same way on every runtime: the framework writes the
encoder's error frame — `event: error` with the message, for SSE — and then closes the response
encoder's error frame (`event: error`, for SSE) and then closes the response
cleanly, and emits `stream:error` on the [bus](/docs/guides/observability/). A consumer that received
an `error` event knows what happened; a connection that merely dropped tells it nothing, which is why
the frame comes first.

The frame carries an `HttpError`'s message, and `Internal Server Error` for anything else, as a
buffered route would. The full error, message and stack, goes to `stream:error` only. Up to RC.1 the
frame carried the raw `err.message`, so a database error's connection string could reach the
client.

### `ctx.ip` inside a stream body

`ctx.ip` is worked out the first time something reads it, not on every request. A stream body runs
Expand Down Expand Up @@ -152,7 +157,9 @@ class ChatController {
}
```

`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and a bounded buffer per subscriber: 1024 values by default, dropping the oldest. Set it with
`channel({ buffer: 100 })`; `channel({ buffer: Infinity })` restores the unbounded buffer RC.1 had,
which lets one slow client grow server memory without limit.

:::note[WebSocket needs the `ws` peer]
`@Ws` (and mesh) require the optional [`ws`](https://github.com/websockets/ws) peer dependency — `npm i ws`. SSE, ndjson, and plain HTTP need nothing extra.
Expand Down
Loading