feat(app): app.fetch — Web-Standards handler over the neutral core

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-09 14:15:26 -05:00
1 parent fc75cc05e5
commit 93a4246de5
5 files changed
+249 -10

No files matched your search

+92 -9
View File
@@ -5,6 +5,8 @@ import { topoSort, subgraphFor, GraphNode, nearest } from '../graph';
import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
import { runPipeline, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http';
import { buildFetch } from '../http/web';
import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
@@ -119,6 +121,33 @@ export function createApp(opts: {
const providedSeed = (plan: RoutePlan) => seedProviders(container, plan);
const planSteps = (plan: RoutePlan) => compilePlanSteps(runners, plan);
// Boots app-scope providers exactly once, however first triggered (app.fetch or listen()); calling
// both never double-boots (which would re-run provider factories and their side effects).
const bootAppProviders = makeProviderBooter(
registry,
opts.overrides,
() => orderedProviders,
{ runners, container, providerMeta, bus },
degradedProviders,
);
const fetchOpts: HttpOptions = {
limits: opts.limits,
tls: opts.tls,
trustProxy: opts.trustProxy,
security: opts.security ?? true,
cors: opts.cors,
bodyDuplicates: opts.bodyDuplicates,
onError: opts.onError,
};
const fetchFn = buildAppFetch(
booted,
routePlans,
{ providedSeed, planSteps, bus, onError: opts.onError },
fetchOpts,
bootAppProviders,
);
const listen = async (port: number): Promise<http.Server> => {
const deps: PipelineDeps = { providedSeed, planSteps, bus, onError: opts.onError };
@@ -133,15 +162,7 @@ export function createApp(opts: {
finalize();
}
applyOverrides(opts.overrides, registry);
degradedProviders.length = 0;
degradedProviders.push(...(await bootProviders(orderedProviders, { runners, container, providerMeta, bus })));
if (degradedProviders.length) {
console.warn(
`[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
);
}
await bootAppProviders();
const meshControl = buildMeshControl(opts.mesh, registry, {
container,
@@ -181,6 +202,7 @@ export function createApp(opts: {
return {
listen,
close,
fetch: fetchFn,
inspect,
graph,
toMermaid: () => toMermaid(graph()),
@@ -450,6 +472,43 @@ async function bootProviders(
return degraded;
}
/**
* Returns a memoized boot function: applies overrides and boots app-scope providers exactly once,
* however first triggered — {@link buildAppFetch}'s handler or `listen()` may both call it, and the
* memoization guarantees only the first call actually runs (and warns about) the boot sequence.
*/
function makeProviderBooter(
registry: Registry,
overrides: Record<string, unknown> | undefined,
getOrderedProviders: () => GraphNode[],
deps: {
runners: Map<string, Runner>;
container: Container;
providerMeta: Map<string, { optional: boolean }>;
bus: Bus;
},
degradedProviders: string[],
): () => Promise<void> {
let bootPromise: Promise<void> | undefined;
const runBoot = async (): Promise<void> => {
applyOverrides(overrides, registry);
degradedProviders.length = 0;
degradedProviders.push(...(await bootProviders(getOrderedProviders(), deps)));
if (degradedProviders.length) {
console.warn(
`[green-tea] started with ${degradedProviders.length} degraded optional provider(s): ${degradedProviders.join(', ')} — routes that need them will fail at request time.`,
);
}
};
return (): Promise<void> => {
if (!bootPromise) bootPromise = runBoot();
return bootPromise;
};
}
/**
* Builds the mesh control gateway that exposes this node's declared exports over the control channel.
* Returns undefined when there is nothing to export; throws if exports are declared without a gating secret.
@@ -555,6 +614,30 @@ function buildHttpRoutes(routePlans: RoutePlan[], remoteRoutes: RouteDef[], deps
return [...local, ...remoteRoutes];
}
/**
* Builds `app.fetch`: a Web-Standards handler over the same route table `listen()` uses, so
* `Deno.serve(app.fetch)` / `Bun.serve({ fetch: app.fetch })` work without ever calling `listen()`.
* Non-mesh apps finalize eagerly, so `booted` is already `true` and the route table is ready
* immediately. Mesh apps defer finalize to `listen()` (remote scopes must splice into the graph
* first), so the returned function throws until then — mirroring the explain()/graph()/inspect()
* "unavailable before listen()" guard.
*/
function buildAppFetch(
booted: boolean,
routePlans: RoutePlan[],
deps: PipelineDeps,
fetchOpts: HttpOptions,
ensureBooted: () => Promise<void>,
): (request: Request) => Promise<Response> {
const handler = booted ? buildFetch(buildHttpRoutes(routePlans, [], deps), fetchOpts) : undefined;
return async (request: Request): Promise<Response> => {
if (!handler) throw new Error('fetch() unavailable before listen() for mesh apps');
await ensureBooted(); // idempotent: no-op if listen() already booted the providers
return handler(request);
};
}
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
function devGraphRoute(graph: () => GraphView): RouteDef {
return {
+2
View File
@@ -35,6 +35,8 @@ export interface Explain {
export interface App {
listen(port: number): Promise<http.Server>;
close(): Promise<void>;
/** Web-Standards handler: run a Fetch API Request through the graph and return a Response (Node/Deno/Bun/edge). WS not included. */
fetch(request: Request): Promise<Response>;
inspect(routePath: string): InspectLine[];
graph(): GraphView;
toMermaid(): string;
+1 -1
View File
@@ -179,7 +179,7 @@ type ParseResult = { body: unknown } | { error: string; status?: number };
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
*/
async function parseRequestBody(
export async function parseRequestBody(
buf: Buffer | undefined,
contentType: string,
duplicates: 'array' | 'last',
+107
View File
@@ -1,4 +1,11 @@
import type { StreamEncoder } from '../encoders';
import { handle, type HandleResult } from './core';
import { mergeInjectedHeaders } from './headers';
import { parseRequestBody } from './server';
import { matchRoute } from './router';
import { HttpError } from '../signals';
import { renderError, type ErrorRequest, type ErrorResponse } from '../transformers';
import type { RouteDef, HttpOptions, MatchedRoute } from './types';
/** Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream cancel. */
export function asReadableStream(source: AsyncIterable<unknown>, encoder: StreamEncoder): ReadableStream<Uint8Array> {
@@ -26,3 +33,103 @@ export function asReadableStream(source: AsyncIterable<unknown>, encoder: Stream
},
});
}
/** Converts a web `Headers` into the plain record shape the neutral core and body parser expect. */
function headersToRecord(headers: Headers): Record<string, string> {
const out: Record<string, string> = {};
headers.forEach((value, key) => {
out[key] = value;
});
return out;
}
/** Turns a rendered error (or any {status, headers, body}) into a web `Response`. */
function errorResponse(rendered: ErrorResponse): Response {
return new Response(rendered.body, { status: rendered.status, headers: rendered.headers });
}
/**
* Reads and parses a matched request's body (enforcing `maxBodyBytes` → 413), mirroring the Node
* adapter's `acquireBody`. Returns `{ body }` on success, or a ready-to-send `{ response }` on failure.
*/
async function acquireFetchBody(
request: Request,
matched: MatchedRoute,
headers: Record<string, string>,
path: string,
maxBody: number,
opts: HttpOptions | undefined,
): Promise<{ body: unknown } | { response: Response }> {
const errReq: ErrorRequest = { method: request.method, url: path, headers };
let buf: Buffer | undefined;
if (request.body) {
const arrayBuffer = await request.arrayBuffer();
const bodyLimit = matched.def.maxBodyBytes ?? maxBody;
if (arrayBuffer.byteLength > bodyLimit) {
return { response: errorResponse(renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError)) };
}
buf = arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer);
}
const contentType = headers['content-type'] ?? '';
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const maxParts = matched.def.maxParts ?? opts?.limits?.maxParts ?? 1000;
const parsed = await parseRequestBody(buf, contentType, duplicates, maxParts);
if ('error' in parsed) {
return {
response: errorResponse(renderError(new HttpError(parsed.status ?? 400, parsed.error), errReq, opts?.onError)),
};
}
return { body: parsed.body };
}
/** Converts a {@link HandleResult}'s outcome into a web `Response`, buffered or streamed. */
function outcomeToResponse(result: HandleResult): Response {
const headers = mergeInjectedHeaders(result.outcome.headers, result.injected) as Record<string, string>;
if (result.outcome.kind === 'stream') {
return new Response(asReadableStream(result.outcome.stream, result.outcome.encoder), { headers });
}
return new Response(result.outcome.body, { status: result.outcome.status, headers });
}
/**
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
* reads the body (enforcing `maxBodyBytes` → 413), parses it by content type, runs it through the
* runtime-neutral {@link handle}, and converts the outcome to a `Response` (buffered or streamed).
*/
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
return async (request: Request): Promise<Response> => {
const url = new URL(request.url);
const path = url.pathname + url.search;
const headers = headersToRecord(request.headers);
const matched = matchRoute(routes, request.method, url.pathname);
let body: unknown;
if (matched) {
const acquired = await acquireFetchBody(request, matched, headers, path, maxBody, opts);
if ('response' in acquired) return acquired.response;
body = acquired.body;
}
const result = await handle(routes, opts, {
method: request.method,
url: path,
headers,
body,
secure: url.protocol === 'https:',
ip: headers['x-forwarded-for'] ?? '',
});
if ('preflight' in result) return new Response(null, { status: 204, headers: result.preflight });
return outcomeToResponse(result);
};
}
+47
View File
@@ -0,0 +1,47 @@
import { describe, it, expect } from 'vitest';
import { createApp, Provider, Route, Get, Post, Module, needs, body } from '../src/index';
@Provider({ provides: 'store' })
class Store {
provide() {
return { store: { hi: 'ok' } };
}
}
@Route('/api')
class Ctl {
@Get('/hello') hello(@needs('store') s: any) {
return { store: s.hi };
}
@Post('/echo') echo(@body() b: any) {
return { got: b };
}
}
@Module({ mountpoint: '/', providers: [Store], controllers: [Ctl] })
class M {}
const app = createApp({ modules: [M] });
describe('app.fetch', () => {
it('handles GET and returns JSON 200', async () => {
const res = await app.fetch(new Request('http://x/api/hello'));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ store: 'ok' });
});
it('parses a POST body', async () => {
const res = await app.fetch(
new Request('http://x/api/echo', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ a: 1 }),
}),
);
expect(await res.json()).toEqual({ got: { a: 1 } });
});
it('404s an unknown route', async () => {
const res = await app.fetch(new Request('http://x/nope'));
expect(res.status).toBe(404);
});
it('sets secure-by-default headers', async () => {
const res = await app.fetch(new Request('http://x/api/hello'));
expect(res.headers.get('x-content-type-options')).toBe('nosniff');
});
});