docs(observability): document the contract, and retire the sentence that denied it
Task 8. README.md led its Honest scope section with "No observability layer, either." — the single most load-bearing sentence in the CTO assessment, and now false. It says what exists instead, and keeps being explicit about what does not: no metrics registry and no OpenTelemetry exporter in core, because core has one runtime dependency and intends to keep it. Adds a guide covering the parts that are contracts rather than implementation details, since those are the ones a reader gets wrong: route labels carry the pattern and never the concrete path (labelling metrics on raw URLs is how you take down a metrics backend), request:end fires when the handler returns rather than when a stream closes, and streams emit lifecycle events only. The plugins guide was titled "Plugins & observability" and carried a partial event list that had already drifted. It now covers plugins and points at the guide for the vocabulary, with the correlation note it was missing. Includes the measured cost, because a performance claim without a number is marketing: -3.9% on JSON hello, -2.1% on a three-step pipeline, and the reason the shallower route loses more. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
5 files changed
+163
-6
No files matched your search
@@ -110,6 +110,7 @@ Beta shipped the parts a real API needs, without growing the runtime dependency
|
||||
- **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.
|
||||
- **Ceilings that are already on.** `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. 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. Configurable, and safe before you configure anything.
|
||||
- **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 })`. `app.close()` is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
|
||||
- **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line.
|
||||
- **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations.
|
||||
@@ -243,7 +244,9 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
|
||||
|
||||
**Bring your own auth (and friends).** green-tea ships transport security — TLS/wss, secure-by-default headers, CORS — but **not** authentication, authorization, rate-limiting, CSRF, or sessions. You compose those as steps and plugins (the `Authenticate` step in the quick look is the pattern). Unlike Express/Fastify, there is no off-the-shelf plugin ecosystem for them yet.
|
||||
|
||||
**No observability layer, either.** There is no built-in logger, no metrics export, and no tracing hooks; core does not depend on a logging library and does not intend to. Today you compose those as steps and providers like anything else. A first-class contract — an injectable logger, structured output, and hooks an OpenTelemetry exporter can attach to — is [tracked as one design](https://github.com/Expressive-Tea/green-tea/issues/10), because doing it piecemeal produces three mechanisms that don't fit together. If your team's definition of production-ready includes shipping traces on day one, this is the gap to know about.
|
||||
**Observability is a contract, not an integration.** Core emits a correlated lifecycle event stream — every request gets an id (an incoming `x-request-id` is adopted, not replaced), every event carries it, and each step reports its own duration. `createApp({ logger })` takes any logger; the default writes structured JSON, or a readable line on a TTY. Nothing in core writes to `console`, which is enforced by a lint rule rather than a promise. `createApp({ logRequests: true })` logs a line per request, off by default.
|
||||
|
||||
**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 ≥ 18, 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.
|
||||
|
||||
@@ -276,6 +279,7 @@ npm run docs:dev # the documentation site (website/)
|
||||
- ✅ **runs everywhere** — Node, Deno, Bun, and Cloudflare Workers over web-standard `Request`/`Response`, with identical WebSocket behaviour on all four. Every CI run exercises all four; the Deno, Bun, and workerd suites gate a merge exactly as the Node one does.
|
||||
- ✅ **HTML** — `@Html` (string / file / template), a built-in template engine with a bring-your-own `viewEngine` hook, and `static` serving.
|
||||
- ✅ **router completeness for beta** — safe constrained params, deterministic precedence, explicit/automatic HEAD and OPTIONS, strict path validation, and ambiguity checks across local and mesh routes.
|
||||
- ✅ **observability** — a correlated lifecycle event stream (request id, trace id, route pattern, per-step timings) and an injectable `Logger`. Exporters live outside core.
|
||||
- **next** — API freeze + first published release, mesh sub-specs (discovery, load-balancing, failover), official plugins, and a radix-tree matcher for very large route tables.
|
||||
|
||||
## Versioning
|
||||
|
||||
@@ -55,7 +55,8 @@ export default defineConfig({
|
||||
{ label: 'File uploads', slug: 'guides/uploads' },
|
||||
{ label: 'HTML & views', slug: 'guides/html' },
|
||||
{ label: 'Transport security', slug: 'guides/security' },
|
||||
{ label: 'Plugins & observability', slug: 'guides/plugins' },
|
||||
{ label: 'Plugins', slug: 'guides/plugins' },
|
||||
{ label: 'Observability', slug: 'guides/observability' },
|
||||
{ label: 'Graph introspection', slug: 'guides/introspection' },
|
||||
{ label: 'OpenAPI', slug: 'guides/openapi' },
|
||||
{ label: 'Runtimes', slug: 'guides/runtimes' },
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
---
|
||||
title: Observability
|
||||
description: A correlated lifecycle event stream, an injectable logger, and where exporters go.
|
||||
---
|
||||
|
||||
green-tea does not integrate with an observability vendor. It emits a **correlated event stream** and
|
||||
lets you read it. A logger, a metrics exporter and a tracing bridge are three consumers of that one
|
||||
stream — not three features, which is why they are one design.
|
||||
|
||||
The rule that shapes all of it: core has one runtime dependency, `reflect-metadata`, and keeps it.
|
||||
Nothing here imports an exporter.
|
||||
|
||||
## Correlation
|
||||
|
||||
Every request gets an id. Every event it causes carries that id.
|
||||
|
||||
```ts
|
||||
app.bus.on('request:step:leave', (event) => {
|
||||
event.requestId; // "9f0c…" — the same value on every event of this request
|
||||
event.route; // "/users/:id" — the pattern, never the concrete path
|
||||
event.durationMs; // how long this step took
|
||||
});
|
||||
```
|
||||
|
||||
Without that id the stream is unusable under any concurrency: two requests interleave their step
|
||||
events and nothing tells you which is which.
|
||||
|
||||
**An incoming `x-request-id` is adopted, not replaced.** A service behind a gateway must not open a
|
||||
second identity for a request that already has one.
|
||||
|
||||
**A `traceparent` header is carried through untouched** as `traceId`. Core parses nothing and
|
||||
implements no propagation spec — W3C Trace Context belongs to the exporter that understands it.
|
||||
|
||||
### `route` is the pattern, always
|
||||
|
||||
`route` is `/users/:id`, never `/users/42`. This is a contract, not an implementation detail: a
|
||||
metrics consumer that labels a counter with the concrete path gets one label per distinct URL, and
|
||||
unbounded label cardinality takes down the metrics backend rather than the application.
|
||||
|
||||
## The events
|
||||
|
||||
| Event | When |
|
||||
|---|---|
|
||||
| `request:start` / `request:end` | a request enters and leaves the handler |
|
||||
| `request:failed` | the request produced an error |
|
||||
| `route:matched` / `route:unmatched` | a route matched, or none did (covers **404 and 405**) |
|
||||
| `request:step:enter` / `:leave` / `:error` | one step of the pipeline |
|
||||
| `boot:provider:start` / `:ok` / `:fail` | a provider booting |
|
||||
| `stream:open` / `:close` / `:error` | an SSE, ndjson or WebSocket connection |
|
||||
| `mesh:connect` / `:disconnect` / `:rpc:error` | mesh links |
|
||||
| `plugin:mounted` | a plugin registered |
|
||||
|
||||
### Where a streaming request ends
|
||||
|
||||
`request:end` fires **when the handler returns**, not when a stream it produced finishes.
|
||||
|
||||
A streaming route returns in milliseconds while its connection may live for hours. Ending the
|
||||
request span at stream close would put hour-long SSE connections and 2 ms buffered replies in one
|
||||
latency distribution, ruining both. The connection is described by `stream:open` / `stream:close`,
|
||||
which carry the same `requestId` — so you can join the two yourself, and you get a meaningful
|
||||
latency histogram either way.
|
||||
|
||||
### Streams do not emit per message
|
||||
|
||||
Lifecycle only. A per-message event on a high-rate stream is a firehose that costs more than it
|
||||
reports, and the cost lands on the workload least able to absorb it. Instrument your own handler if
|
||||
you need it, where you know what the messages mean.
|
||||
|
||||
## The logger
|
||||
|
||||
```ts
|
||||
const app = createApp({ modules: [AppModule], logger: myLogger });
|
||||
```
|
||||
|
||||
Any object with `debug`, `info`, `warn` and `error` — each taking a message and optional structured
|
||||
fields. Bridging `pino` or `winston` is a few lines in either direction; core defines the shape it
|
||||
needs rather than adopting anyone's.
|
||||
|
||||
Given none, the default writes structured JSON, or a human-readable line when the process is
|
||||
attached to a TTY — decided once at boot, not per record.
|
||||
|
||||
**Nothing in core writes to `console`.** That is enforced by a lint rule, not by good intentions, so
|
||||
every framework diagnostic is redirectable.
|
||||
|
||||
The logger is also injectable:
|
||||
|
||||
```ts
|
||||
@Step({ provides: 'user', needs: ['db'] })
|
||||
class LoadUser {
|
||||
run(@needs('logger') log: Logger) { … }
|
||||
}
|
||||
```
|
||||
|
||||
Same object, two access paths. It is registered rather than declared as a provider because it has to
|
||||
outlive the graph on both ends: a provider cannot report its own boot failing, and shutdown warnings
|
||||
happen after the graph is gone.
|
||||
|
||||
## Request logging
|
||||
|
||||
Off by default. A framework that writes to stdout uninvited is one you have to configure before you
|
||||
can use it.
|
||||
|
||||
```ts
|
||||
createApp({ modules: [AppModule], logRequests: true });
|
||||
```
|
||||
|
||||
It is an ordinary subscriber, so you can do it by hand and take it back:
|
||||
|
||||
```ts
|
||||
import { logRequests } from '@green-tea/core';
|
||||
|
||||
const stop = logRequests(app.bus, app.logger);
|
||||
stop(); // removable, not merely optional
|
||||
```
|
||||
|
||||
A logger that throws does **not** silently stop writing: the subscriber is wrapped so failures fall
|
||||
back to `console`. `Bus.emit` isolates listener failures by design — an observer must never break a
|
||||
request — and the wrapper keeps that guarantee without paying for it in silence.
|
||||
|
||||
## Metrics and tracing
|
||||
|
||||
There is no metrics registry in core and no OpenTelemetry exporter in core. Both read the stream
|
||||
above from outside:
|
||||
|
||||
```ts
|
||||
app.bus.on('request:end', (e) => histogram.observe(e.durationMs, { route: e.route, status: e.status }));
|
||||
```
|
||||
|
||||
Per-step timings are already on the events, so a per-node timing breakdown needs no extra
|
||||
instrumentation — the graph already knows every node.
|
||||
|
||||
## What it costs
|
||||
|
||||
Measured, not asserted, on the box that produced [BENCHMARKS.md](https://github.com/Expressive-Tea/green-tea/blob/main/BENCHMARKS.md):
|
||||
|
||||
| Scenario | Before | After | |
|
||||
|---|---:|---:|---:|
|
||||
| JSON hello | 78,118 req/s | 75,075 req/s | −3.9% |
|
||||
| Pipeline (3 steps) | 70,671 req/s | 69,164 req/s | −2.1% |
|
||||
|
||||
The cost is **per request, not per step** — which is why the route with *fewer* steps loses more.
|
||||
Most of it is generating the request id; per-step timing and payload construction are skipped
|
||||
entirely when nothing is subscribed.
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Plugins & observability
|
||||
title: Plugins
|
||||
description: "Extending the app safely via bus.on and scope.add."
|
||||
---
|
||||
|
||||
@@ -45,14 +45,20 @@ api.bus.on('request:step:enter', (p: any) => { /* ... */ });
|
||||
api.bus.on('request:step:leave', (p: any) => { /* ... */ });
|
||||
```
|
||||
|
||||
The full event vocabulary:
|
||||
The full event vocabulary, what each payload carries, and how requests are correlated across
|
||||
them live in [Observability](/docs/guides/observability/). The short version:
|
||||
|
||||
- `request:start | request:end | request:failed` — the request itself
|
||||
- `route:matched | route:unmatched` — routing (`unmatched` covers both 404 and 405)
|
||||
- `request:step:*` — a step entering/exiting/failing, with its own `durationMs`
|
||||
- `boot:provider:*` — provider lifecycle during boot
|
||||
- `request:step:*` — a step entering/exiting during a request
|
||||
- `stream:open | stream:close | stream:error` — SSE/WS stream lifecycle
|
||||
- `mesh:connect | mesh:disconnect | mesh:rpc:error` — mesh link and RPC activity
|
||||
- `plugin:mounted` — a plugin finished mounting
|
||||
|
||||
Every per-request payload carries a `requestId`, so a plugin can attribute events to the request
|
||||
that caused them — which matters the moment two requests overlap.
|
||||
|
||||
Observation is read-only: handlers see the event payload but can't alter control flow. To
|
||||
change behavior, contribute a node to your scope — see
|
||||
[Dependency injection](/docs/guides/dependency-injection/).
|
||||
@@ -26,6 +26,8 @@ const app = createApp(options);
|
||||
| `views` | `string` | `process.cwd()` | base dir `@Html('file.html')` paths resolve against — relative paths join it, absolute paths are used as-is ([HTML & views](/docs/guides/html/)) |
|
||||
| `viewEngine` | `(source: string, data: unknown) => string` | built-in `render` | swap in your own template engine for `@Html(..., { template: true })`; template mode only ([HTML & views](/docs/guides/html/)) |
|
||||
| `static` | `boolean \| string` | — | serve a directory as a `GET`/`HEAD` fallback (after declared routes, before `404`); `true` → `./public`, a string → that dir; path-traversal-safe; needs a filesystem — Node/Deno/Bun only ([HTML & views](/docs/guides/html/)) |
|
||||
| `logger` | `Logger` | structured JSON (readable on a TTY) | where every framework diagnostic is written; also injectable as `@needs('logger')` ([observability](/docs/guides/observability/)) |
|
||||
| `logRequests` | `boolean` | `false` | log one line per completed request and per failure; a removable Bus subscriber, not a middleware ([observability](/docs/guides/observability/)) |
|
||||
| `shutdownTimeoutMs` | `number` | `10_000` | how long `close()` gives in-flight work before forcing the rest shut; `close({ timeoutMs })` still wins per call. Set it here when `close()` is reached from a signal handler or shutdown hook you do not own ([runtimes](/docs/guides/runtimes/)) |
|
||||
| `mesh` | `MeshConfig` | — | distributed DI — **requires `experimental: true`** ([mesh](/docs/guides/mesh/)) |
|
||||
| `experimental` | `boolean` | `false` | opt in to alpha features (currently gates `mesh`) |
|
||||
@@ -75,7 +77,8 @@ const app = createApp(options);
|
||||
| `toMermaid()` / `toDOT()` | `string` | render the graph |
|
||||
| `openapi(info?)` | `OpenApiDoc` | structural OpenAPI 3.1 document ([details](/docs/guides/openapi/)) |
|
||||
| `degraded()` | `string[]` | optional providers running degraded (empty until providers boot through `fetch`, `upgrade`, or `listen`) |
|
||||
| `bus` | `Bus` | lifecycle + request event bus |
|
||||
| `bus` | `Bus` | lifecycle + request event bus ([observability](/docs/guides/observability/)) |
|
||||
| `logger` | `Logger` | the app's logger — the one passed in, or the default |
|
||||
|
||||
:::note
|
||||
On mesh apps, `graph` / `explain` / `inspect` / `degraded` are only available after `ready()` or the first serving call — the graph is finalized once remote scopes connect.
|
||||
|
||||
Reference in new issue
Block a user