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:
chrnx committed 2026-08-16 15:06:54 -05:00
1 parent e052d5ba8f
commit 92987d0a24
5 files changed
+163 -6

No files matched your search

+2 -1
View File
@@ -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.
+9 -3
View File
@@ -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.