Merge docs/overview: architecture map, quickstart, framework comparison

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-06-27 21:51:49 -05:00
commit 86cb473012
3 files changed
+396 -3

No files matched your search

+54 -3
View File
@@ -2,7 +2,12 @@
> A declarative, type-safe HTTP framework for Node. The request pipeline is an explicit **dependency graph**, not a mutable middleware chain.
`@green-tea/core` — **alpha**. Zero runtime dependencies beyond `reflect-metadata`.
`@green-tea/core` — **alpha**. Zero runtime dependencies beyond `reflect-metadata` (`ws` is an optional peer dep, only for WebSocket/mesh on Node).
## Documentation
- **[Quickstart](./docs/quickstart.md)** — install + concrete examples (routes/DI, `flow`, SSE, WebSocket, mesh, plugins).
- **[Architecture](./docs/architecture.md)** — the mental map (layers, request lifecycle, mesh) as diagrams.
## Why
@@ -14,6 +19,51 @@ Express/Fastify middleware is positional, untyped, and globally mutable: order d
- **Response = return value.** No `Response.json()`. Return data; a `@Transformer` serializes it in a leave phase. Cut a request by `throw`ing a typed signal.
- **Fail-fast boot.** A required provider that can't initialize (e.g. the DB) stops the server from serving — no 500s because a resource wasn't ready.
## How it compares
Every framework here can serve `/users/:id`. The difference is what happens when the app
grows: more dependencies, real-time, and more than one machine.
| | Express | Fastify | NestJS | expressive-tea | **green-tea** |
|---|---|---|---|---|---|
| **Pipeline model** | positional `app.use()` | hooks + encapsulated plugins | DI + interceptors/guards | decorators on Express + boot stages | **explicit dependency graph (topo-sorted)** |
| **Order is decided by** | the line you wrote it on | hook phase + registration order | module/provider wiring | boot-stage order | **what each step *needs/produces*** |
| **`req.user` exists?** | hope so | hope so | if the guard ran | if the middleware ran | **boot fails if nothing provides it** |
| **Type safety** | none | schemas (runtime) | decorator types (runtime DI) | runtime | **compile-time in `flow`** + boot-validated decorators |
| **Response** | `res.send()` (mutate) | `reply.send()` | return value | return value | **return value → `@Transformer`** |
| **Real-time** | bolt on `ws`/`sse` libs | plugins | separate Gateway + adapter | separate engine | **return an `AsyncIterable`** — same primitive |
| **Cross-service calls** | HTTP client / gRPC by hand | HTTP client / gRPC | Microservices transport + message patterns | — | **`@needs('x')` resolves on another node** |
| **Plugin can break your pipeline?** | yes (deletes your body parser) | encapsulated, but hooks are global | interceptor order matters | yes | **no** — plugins only `bus.on` + `scope.add` |
| **Runtime deps** | minimal | minimal | heavy (rxjs, reflect-metadata, …) | Express + InversifyJS | **`reflect-metadata` only** (`ws` optional) |
### Read it as a story
- **Express / Fastify** — fast and battle-tested, but the request is a *mutable bag* threaded
through positional middleware. Order is implicit, `req.x` is a leap of faith, and a careless
plugin can delete another's work. You wire types and DI yourself.
- **NestJS** — brings DI, decorators, and structure, but the DI is *runtime token resolution*,
it's a large opinionated dependency tree, and every new capability (WebSockets, gRPC,
microservices) is a **separate subsystem** with its own abstraction (Gateways, transports,
message patterns) to learn and glue.
- **expressive-tea** — the sibling this project grew from: decorators + InversifyJS DI + boot
stages on top of Express. green-tea keeps the ideas, drops Express and Inversify, and makes
the graph — not the middleware chain — the core.
- **green-tea** — one model answers three questions other stacks answer with three subsystems:
- *"what does this handler depend on?"* → the graph (boot-validated, `flow` checks it at compile time)
- *"how do I push data over time?"* → return an `AsyncIterable` (SSE / WebSocket, one primitive)
- *"how do I call another service?"* → `@needs` a token that lives on another node (mesh)
A remote dependency looks **identical** to a local one. There is no gRPC layer, no
message-pattern DSL, no separate WebSocket gateway — there is the graph, and some of its
nodes happen to live on another machine.
### Honest scope
green-tea is **alpha**. Express/Fastify have a decade of ecosystem; NestJS has enterprise
tooling and a huge plugin catalog. Mesh discovery, load-balancing, and failover are not built
yet (the [walking skeleton](./docs/quickstart.md#5-mesh--distributed-dependency-injection) is).
Pick green-tea for the model, not the ecosystem — *yet*.
## Quick look
```typescript
@@ -92,8 +142,9 @@ npm run build # emit dist/
## Roadmap
- **streams** — native WebSocket/SSE + reactive streams (steps that open an observed channel).
- **mesh** — `teapot`/`teacup`: distributed scopes over a persistent channel with auto-registration. Model: a BEAM/OTP-style cluster, *not* microservices. The core's `resolve()` is already async + transport-agnostic to allow this without a rewrite.
- ✅ **streams** — SSE / ndjson / WebSocket duplex over a multicast `AsyncIterable` channel. Return an `AsyncIterable` and the transport streams it (backpressure + cleanup). See the [quickstart](./docs/quickstart.md#3-streaming--sse).
- ✅ **mesh (walking skeleton)** — `teapot`/`teacup`: a consumer resolves a scope/step or proxies a route living on another node, over a secret-gated WS control channel, via one id-correlated RPC. Remote tokens become synthetic graph nodes. Model: a BEAM/OTP-style cluster, *not* microservices. See the [quickstart](./docs/quickstart.md#5-mesh--distributed-dependency-injection).
- **mesh sub-specs (next)** — discovery/auto-registration, 2-way load-balancing, failover/health.
- **runtime adapters** — factor the transport behind an adapter so the core stays runtime-agnostic; Node / Deno / Bun / edge become thin adapters over web-standard `Request`/`Response`. Only `src/http.ts` is runtime-specific today.
- official plugins (cors, body parsers, auth) — structurally unable to sabotage the global pipeline.
+115
View File
@@ -0,0 +1,115 @@
# green-tea — Architecture
> The request and boot are an explicit **dependency graph**, not a mutable middleware chain.
> You declare *what* you need; the framework computes the order. The graph can extend in
> **time** (streams) and across **machines** (mesh).
## The four layers
```mermaid
flowchart TB
subgraph L3["#3 MESH — the graph crosses machines"]
direction LR
teacup["teacup (consumer)"] -- "WS RPC" --> teapot["teapot (host)"]
end
subgraph L2["#2 STREAMS — the graph emits over time"]
sse["SSE / ndjson"]:::n
ws["WebSocket duplex"]:::n
end
subgraph L15["#1.5 ARG DECORATORS — the handler declares its deps"]
sig["handler signature = dependency declaration"]:::n
end
subgraph L1["#1 CORE — graph DI + boot + router + pipeline + flow"]
core["Providers · Steps · Routes · Transformers · Container · Bus"]:::n
end
L3 --> L2 --> L15 --> L1
classDef n fill:#f6f8fa,stroke:#aaa;
```
## Building blocks
```mermaid
flowchart LR
Provider["@Provider\n(app scope · singleton)"]:::p
Step["@Step\n(request scope · per call)"]:::s
Route["@Route + @Get/@Post/@Sse/@Ws/@Stream"]:::r
Transformer["@Transformer\nvalue → ResponseShape"]:::t
Container["Container.resolve()\nasync · transport-agnostic"]:::c
Bus["Bus\nlifecycle events"]:::b
Provider --> Container
Step --> Container
Route --> Transformer
Container -. "remote binding (mesh)" .-> Provider
classDef p fill:#e7f5ff,stroke:#4dabf7;
classDef s fill:#fff3bf,stroke:#f59f00;
classDef r fill:#ebfbee,stroke:#40c057;
classDef t fill:#f3f0ff,stroke:#7950f2;
classDef c fill:#fff0f6,stroke:#e64980;
classDef b fill:#f1f3f5,stroke:#868e96;
```
## Request lifecycle
```mermaid
sequenceDiagram
participant C as Client
participant H as http.ts (transport)
participant P as Pipeline
participant G as Graph (providers/steps)
participant T as Transformer
C->>H: HTTP request
H->>H: matchRoute(method, path)
H->>P: runPipeline(seed = req envelope)
P->>G: providers (cached) + steps (topo order)
Note over G: each step merges into ctx;<br/>throw = short-circuit, return = continue
P->>P: handler(args resolved from ctx)
alt returns a value
P->>T: transformer → {status, headers, body}
T-->>C: buffered response
else returns an AsyncIterable
P-->>C: stream (SSE / ndjson / WS), backpressure + cleanup
else @needs a remote token
G-->>C: RPC to teapot, value spliced into ctx
end
```
## The unifying rule
```mermaid
flowchart TD
Q{"what does the handler return /\nwhere does a token live?"}
Q -->|"a value"| A["buffered (transformer → JSON)"]
Q -->|"an AsyncIterable"| B["stream (SSE / WS)"]
Q -->|"a token with no local provider"| D["RPC to a teapot (mesh)"]
```
One question — *"what produces this token and where does it live?"* — answers local DI,
streaming, and distribution. That single seam is why green-tea isn't "Express with decorators":
**the graph is the product.**
## Mesh walking skeleton (spec #3)
```mermaid
flowchart LR
subgraph A["Node A — teapot"]
ea["@Provider({export:true})\n@Step({export:true})\n@Get('/x',{export:true})"]
mc["control channel\n/__mesh__/control\n(secret-gated)"]
end
subgraph B["Node B — teacup"]
bn["@needs('auth') with\nno local provider"]
lk["link: handshake → manifest\n→ synthetic graph nodes\nwith RPC runners"]
end
bn --> lk
lk -- "hello + secret" --> mc
mc -- "manifest {scopes, routes}" --> lk
lk -- "rpc-req {id, kind, name, ctx}" --> mc
mc -- "rpc-res {id, ok, result}" --> lk
```
- **Provider exported → app scope** (resolved once via RPC, cached).
- **Step exported → request scope** (RPC per request, carries the request envelope).
- **Route exported → proxy** (teacup forwards the request, teapot runs the full pipeline).
Deferred to mesh sub-specs: discovery/auto-registration, 2-way load-balancing, failover/health.
+227
View File
@@ -0,0 +1,227 @@
# green-tea — Quickstart
A type-safe HTTP framework where the request/boot pipeline is an explicit **dependency
graph**. You declare what you need; the framework computes the order, validates it at boot,
and can extend the graph over time (streams) and across machines (mesh).
See [architecture.md](./architecture.md) for the mental map.
## Install
```bash
npm install @green-tea/core reflect-metadata
# ws is an OPTIONAL peer dependency — only needed for WebSocket / mesh on Node:
npm install ws # optional
```
`tsconfig.json` must enable decorator metadata:
```jsonc
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "es2017",
"module": "commonjs"
}
}
```
Import `reflect-metadata` once at your entrypoint.
## 1. A route with dependency injection
A **provider** is an app-scope singleton. A **step** runs per request and transforms the
context. A handler's **argument decorators are its dependency declaration** — ask for what
you want, in any order. If you `@needs` a token nothing produces, you get a **boot error**,
not an `undefined` at runtime.
```typescript
import 'reflect-metadata';
import { createApp, Provider, Step, Route, Get, Module, Unauthorized, needs, param } from '@green-tea/core';
@Provider({ provides: 'db' })
class Database {
provide() { return { db: { find: (id: string) => ({ id, name: 'Diego' }) } }; }
}
@Step({ provides: 'user', needs: ['db', 'req'] })
class Authenticate {
run(ctx: any) {
const user = ctx.db.find(ctx.req.headers['x-token']);
if (!user) throw new Unauthorized('bad token'); // throw = short-circuit the pipeline
return { user }; // return = continue, merge into ctx
}
}
@Route('/users')
class UserController {
@Get('/:id')
getUser(@needs('user') user: any, @param('id') id: string) {
return { requested: id, you: user }; // auto-serialized as JSON
}
}
@Module({ mountpoint: '/api', providers: [Database], steps: [Authenticate], controllers: [UserController] })
class ApiModule {}
const app = createApp({ modules: [ApiModule] });
await app.listen(3000);
// GET /api/users/9 (header x-token) → { "requested": "9", "you": { "id": "...", "name": "Diego" } }
```
### Argument decorators
| Decorator | Reads from | Adds a graph dependency? |
|---|---|---|
| `@needs('user')` | a value produced by a provider/step | **yes** (boot-validated) |
| `@ctx()` | the whole accumulated context | no |
| `@param('id')` | route params | no |
| `@query('q')` | parsed query string | no |
| `@body()` | parsed JSON body | no |
| `@headers('x')` | request headers | no |
| `@inbound()` | the incoming WS message channel | no (WS only) |
| `@abort()` | an `AbortSignal` that fires on disconnect | no (stream/WS) |
Each envelope decorator has three forms: `@query()` (whole object), `@query('q')` (one key),
`@query(['q','date'])` (subset).
## 2. Compile-time guarantee with `flow`
The decorator layer validates the graph at boot. The functional core `flow` validates it in
the **type checker**:
```typescript
import { flow } from '@green-tea/core';
const pipeline = flow()
.step('db', () => ({ find: (id: string) => id }))
.step('user', (ctx) => ctx.db.find('u1')); // referencing a missing 'db' would not compile
```
## 3. Streaming — SSE
Return an `AsyncIterable` and the pipeline streams it (the transformer is bypassed; the
transport frames it, handles backpressure, and cleans up on disconnect).
```typescript
import { Route, Sse } from '@green-tea/core';
@Route('/feed')
class FeedController {
@Sse('/ticks')
ticks() {
return (async function* () {
for (let n = 1; n <= 3; n++) yield { tick: n };
})();
}
}
// GET /feed/ticks (Accept: text/event-stream)
// data: {"tick":1}
// data: {"tick":2}
// data: {"tick":3}
```
`@Stream(path)` negotiates the transport by header (`Accept: text/event-stream` → SSE,
`Upgrade: websocket` → WS, else ndjson chunked).
## 4. Streaming — WebSocket duplex
A WS handler receives the **inbound** channel and returns the **outbound** channel — a step
that consumes one channel and produces another.
```typescript
import { Route, Ws, inbound, channel } from '@green-tea/core';
@Route('/chat')
class ChatController {
@Ws('/echo')
echo(@inbound() incoming: AsyncIterable<string>) {
const out = channel<string>();
(async () => {
for await (const msg of incoming) out.push(`echo: ${msg}`);
out.close();
})();
return out;
}
}
```
`channel<T>()` is a multicast `AsyncIterable` with `push` / `close` / `fail` and an optional
bounded buffer (`channel({ buffer: 100 })`, drop-oldest).
## 5. Mesh — distributed dependency injection
A **teacup** can depend on a token that physically lives on a **teapot**. Exports are
opt-in (`export: true`) and the control channel is gated by a shared secret.
**Node A — teapot (exposes `config`, `auth`, and a route):**
```typescript
@Provider({ provides: 'config', export: true })
class Config { provide() { return { config: { region: 'mx', tier: 'pro' } }; } }
@Step({ provides: 'auth', needs: [], export: true })
class Auth { run(ctx: any) { return { auth: { token: ctx.headers?.['x-token'] ?? 'anon' } }; } }
@Route('/svc')
class Svc { @Get('/ping', { export: true }) ping() { return { pong: true }; } }
@Module({ mountpoint: '/api', providers: [Config], steps: [Auth], controllers: [Svc] })
class TeapotModule {}
const teapot = createApp({ modules: [TeapotModule], mesh: { secret: 'shh' } });
await teapot.listen(3002);
```
**Node B — teacup (uses `config` + `auth` with no local providers):**
```typescript
@Route('/local')
class LocalCtl {
@Get('/who')
who(@needs('config') config: any, @needs('auth') auth: any) {
return { config, auth }; // both resolved by RPC to the teapot
}
}
@Module({ mountpoint: '/api', controllers: [LocalCtl] })
class TeacupModule {}
const teacup = createApp({
modules: [TeacupModule],
mesh: { teapots: [{ url: 'ws://A-host:3002/__mesh__/control', secret: 'shh' }] },
});
await teacup.listen(3003);
// GET B:3003/api/local/who (x-token: abc)
// → { "config": { "region": "mx", "tier": "pro" }, "auth": { "token": "abc" } }
```
`@needs('config' | 'auth')` validates at boot because the teapot announced them in its
manifest on connect. A provider export is app-scope (resolved once, cached); a step export is
request-scope (RPC per request, carrying the request envelope).
> 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`.
## 6. Plugins & observability
```typescript
const logger = (api: any) => {
api.bus.on('request:step:enter', (p: any) => console.log(`→ ${p.name}`));
api.bus.on('stream:open', (p: any) => console.log(`stream open ${p.name}`));
api.bus.on('mesh:rpc:error', (p: any) => console.error('mesh rpc failed', p.error));
};
const app = createApp({ modules: [ApiModule], plugins: [logger] });
```
Lifecycle events: `boot:provider:*`, `request:step:*`, `stream:open|close|error`,
`mesh:connect|disconnect|rpc:error`, `plugin:mounted`.
## The one rule to remember
```
return a VALUE → buffered response (transformer → JSON)
return an AsyncIterable → stream (SSE / WS)
@needs a remote token → RPC to a teapot (mesh)
```