refactor(http): extract runtime-neutral handle() core
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
2 files changed
+137
-68
No files matched your search
@@ -0,0 +1,89 @@
|
|||||||
|
// src/http/core.ts — runtime-neutral request handling core, shared by the Node adapter and (later) app.fetch.
|
||||||
|
import { HttpError, NotFound } from '../signals';
|
||||||
|
import { renderError } from '../transformers';
|
||||||
|
import { isStreamResult, type PipelineResult } from '../pipeline';
|
||||||
|
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
|
||||||
|
import { matchRoute, allowedMethods, parseQuery } from './router';
|
||||||
|
import { pickEncoder } from './stream';
|
||||||
|
import type { RouteDef, HttpOptions } from './types';
|
||||||
|
import type { StreamEncoder } from '../encoders';
|
||||||
|
|
||||||
|
/** A runtime-neutral inbound request: body already parsed by the caller's ingress (Node stream, fetch Request, …). */
|
||||||
|
export interface NeutralRequest {
|
||||||
|
method: string;
|
||||||
|
url: string; // path + query, e.g. "/users/9?x=1"
|
||||||
|
headers: Record<string, string | string[] | undefined>;
|
||||||
|
body: unknown; // already-parsed body
|
||||||
|
secure: boolean;
|
||||||
|
ip: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The neutral shape of a response: a fully buffered body, or a stream to pipe frame-by-frame. */
|
||||||
|
export type NeutralOutcome =
|
||||||
|
| { kind: 'buffered'; status: number; headers: Record<string, string>; body: string | Buffer }
|
||||||
|
| { kind: 'stream'; headers: Record<string, string>; stream: AsyncIterable<unknown>; encoder: StreamEncoder };
|
||||||
|
|
||||||
|
/** {@link handle}'s result for a normal (non-preflight) request. */
|
||||||
|
export interface HandleResult {
|
||||||
|
injected: Record<string, string>;
|
||||||
|
outcome: NeutralOutcome;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** {@link handle}'s result for a CORS preflight: the caller must answer with 204 + these headers. */
|
||||||
|
export interface Preflight {
|
||||||
|
preflight: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runtime-neutral request handler: security/CORS headers, preflight short-circuit, route match / 404 / 405,
|
||||||
|
* route-handler invocation with error rendering, and the buffered-vs-stream decision. Does no I/O — the
|
||||||
|
* caller (a Node adapter, a fetch adapter, …) reads/writes the actual request/response.
|
||||||
|
*/
|
||||||
|
export async function handle(
|
||||||
|
routes: RouteDef[],
|
||||||
|
opts: HttpOptions | undefined,
|
||||||
|
req: NeutralRequest,
|
||||||
|
): Promise<HandleResult | Preflight> {
|
||||||
|
const path = req.url.split('?')[0];
|
||||||
|
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) };
|
||||||
|
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||||
|
|
||||||
|
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
||||||
|
return { preflight: corsPreflightHeaders(opts.cors, req) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const matched = matchRoute(routes, req.method, path);
|
||||||
|
|
||||||
|
if (!matched) {
|
||||||
|
// Path matches a route under a different method → 405 with Allow; otherwise 404.
|
||||||
|
const allow = allowedMethods(routes, path);
|
||||||
|
const err = allow.length ? new HttpError(405, 'Method Not Allowed') : new NotFound('Not Found');
|
||||||
|
const rendered = renderError(err, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
||||||
|
const headers = allow.length ? { ...rendered.headers, allow: allow.join(', ') } : rendered.headers;
|
||||||
|
return { injected, outcome: { kind: 'buffered', status: rendered.status, headers, body: rendered.body } };
|
||||||
|
}
|
||||||
|
|
||||||
|
let result: PipelineResult;
|
||||||
|
|
||||||
|
try {
|
||||||
|
result = await matched.def.handler({
|
||||||
|
method: req.method,
|
||||||
|
url: req.url,
|
||||||
|
headers: req.headers,
|
||||||
|
params: matched.params,
|
||||||
|
query: parseQuery(req.url),
|
||||||
|
body: req.body,
|
||||||
|
protocol: req.secure ? 'https' : 'http',
|
||||||
|
ip: req.ip,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
result = renderError(error, { method: req.method, url: req.url, headers: req.headers }, opts?.onError);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isStreamResult(result)) {
|
||||||
|
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
||||||
|
return { injected, outcome: { kind: 'stream', headers: encoder.headers, stream: result.stream, encoder } };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { injected, outcome: { kind: 'buffered', status: result.status, headers: result.headers, body: result.body } };
|
||||||
|
}
|
||||||
+48
-68
@@ -1,16 +1,16 @@
|
|||||||
import http from 'http';
|
import http from 'http';
|
||||||
import https from 'https';
|
import https from 'https';
|
||||||
import { renderError, type ErrorRequest, type ErrorRenderer } from '../transformers';
|
import { renderError, type ErrorRequest } from '../transformers';
|
||||||
import { isHttpError, HttpError, NotFound } from '../signals';
|
import { isHttpError, HttpError } from '../signals';
|
||||||
import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline';
|
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../security';
|
import { buildSecurityHeaders, resolveCors } from '../security';
|
||||||
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
|
||||||
import { matchRoute, allowedMethods, parseQuery } from './router';
|
import { matchRoute } from './router';
|
||||||
import { readBody, deriveSecure, deriveIp } from './request';
|
import { readBody, deriveSecure, deriveIp } from './request';
|
||||||
import { pickEncoder, pipeStream } from './stream';
|
import { pipeStream } from './stream';
|
||||||
import { attachWs } from './ws';
|
import { attachWs } from './ws';
|
||||||
import { mergeInjectedHeaders } from './headers';
|
import { mergeInjectedHeaders } from './headers';
|
||||||
|
import { handle } from './core';
|
||||||
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types';
|
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types';
|
||||||
|
|
||||||
interface HandlerConfig {
|
interface HandlerConfig {
|
||||||
@@ -29,19 +29,6 @@ function errorRequest(req: http.IncomingMessage): ErrorRequest {
|
|||||||
return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers };
|
return { method: req.method ?? 'GET', url: req.url ?? '/', headers: req.headers };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Renders an error (through the optional user hook) and writes it, merging any extra headers (e.g. `Allow`). */
|
|
||||||
function sendError(
|
|
||||||
res: http.ServerResponse,
|
|
||||||
error: unknown,
|
|
||||||
req: http.IncomingMessage,
|
|
||||||
onError?: ErrorRenderer,
|
|
||||||
extraHeaders?: Record<string, string>,
|
|
||||||
): void {
|
|
||||||
const rendered = renderError(error, errorRequest(req), onError);
|
|
||||||
res.writeHead(rendered.status, extraHeaders ? { ...rendered.headers, ...extraHeaders } : rendered.headers);
|
|
||||||
res.end(rendered.body);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
|
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
|
||||||
* @param routes HTTP route definitions.
|
* @param routes HTTP route definitions.
|
||||||
@@ -72,13 +59,20 @@ export function createHttpServer(
|
|||||||
return server;
|
return server;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Builds the request listener: security/CORS headers, routing, body parsing, then buffered or streamed response. */
|
/**
|
||||||
|
* Builds the request listener: a thin Node adapter around the runtime-neutral {@link handle} core.
|
||||||
|
* Reads the body (Node-specific), delegates security/CORS/routing/error-rendering to `handle()`,
|
||||||
|
* then writes the result to `res` (buffered or streamed). The security-header monkeypatch is
|
||||||
|
* installed here — and stays the single source of truth for merging headers into every response —
|
||||||
|
* so `handle()`'s own `injected` is intentionally unused by this adapter.
|
||||||
|
*/
|
||||||
function createRequestHandler(cfg: HandlerConfig) {
|
function createRequestHandler(cfg: HandlerConfig) {
|
||||||
const { routes, bus, opts, maxBody, trustProxy } = cfg;
|
const { routes, bus, opts, maxBody, trustProxy } = cfg;
|
||||||
|
|
||||||
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||||
const url = req.url ?? '/';
|
const url = req.url ?? '/';
|
||||||
const path = url.split('?')[0];
|
const path = url.split('?')[0];
|
||||||
|
const method = req.method ?? 'GET';
|
||||||
// Install the security-header patch BEFORE any routing/response so every path
|
// Install the security-header patch BEFORE any routing/response so every path
|
||||||
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
// (200, 404, error, stream) writes headers through the same patched writeHead.
|
||||||
const secure = deriveSecure(req, trustProxy);
|
const secure = deriveSecure(req, trustProxy);
|
||||||
@@ -89,61 +83,47 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
// by reference at writeHead time, so keys added here still land on every response.
|
// by reference at writeHead time, so keys added here still land on every response.
|
||||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||||
|
|
||||||
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
|
// Mirror handle()'s own preflight/route-match decision here, so we only read the body
|
||||||
res.writeHead(204, corsPreflightHeaders(opts.cors, req));
|
// (below) for a request that actually reaches a route handler — matching prior behaviour.
|
||||||
|
const isPreflight = Boolean(opts?.cors && method === 'OPTIONS' && req.headers['access-control-request-method']);
|
||||||
|
const matched = isPreflight ? undefined : matchRoute(routes, method, path);
|
||||||
|
|
||||||
|
let body: unknown;
|
||||||
|
|
||||||
|
if (matched) {
|
||||||
|
const acquired = await acquireBody(req, matched, opts, maxBody);
|
||||||
|
|
||||||
|
if ('fail' in acquired) {
|
||||||
|
res.writeHead(acquired.fail.status, acquired.fail.headers);
|
||||||
|
res.end(acquired.fail.body);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
body = acquired.body;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await handle(routes, opts, {
|
||||||
|
method,
|
||||||
|
url,
|
||||||
|
headers: req.headers,
|
||||||
|
body,
|
||||||
|
secure,
|
||||||
|
ip: deriveIp(req, trustProxy),
|
||||||
|
});
|
||||||
|
|
||||||
|
if ('preflight' in result) {
|
||||||
|
res.writeHead(204, result.preflight);
|
||||||
res.end();
|
res.end();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const matched = matchRoute(routes, req.method ?? 'GET', path);
|
if (result.outcome.kind === 'stream') {
|
||||||
|
await pipeStream(res, result.outcome.stream, result.outcome.encoder, bus, matched?.def.pattern, opts?.streams);
|
||||||
if (!matched) {
|
|
||||||
// Path matches a route under a different method → 405 with Allow; otherwise 404.
|
|
||||||
const allow = allowedMethods(routes, path);
|
|
||||||
|
|
||||||
if (allow.length) {
|
|
||||||
sendError(res, new HttpError(405, 'Method Not Allowed'), req, opts?.onError, { allow: allow.join(', ') });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
sendError(res, new NotFound('Not Found'), req, opts?.onError);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const acquired = await acquireBody(req, matched, opts, maxBody);
|
res.writeHead(result.outcome.status, result.outcome.headers);
|
||||||
|
res.end(result.outcome.body);
|
||||||
if ('fail' in acquired) {
|
|
||||||
res.writeHead(acquired.fail.status, acquired.fail.headers);
|
|
||||||
res.end(acquired.fail.body);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let result: PipelineResult;
|
|
||||||
|
|
||||||
try {
|
|
||||||
result = await matched.def.handler({
|
|
||||||
method: req.method ?? 'GET',
|
|
||||||
url,
|
|
||||||
headers: req.headers,
|
|
||||||
params: matched.params,
|
|
||||||
query: parseQuery(url),
|
|
||||||
body: acquired.body,
|
|
||||||
protocol: secure ? 'https' : 'http',
|
|
||||||
ip: deriveIp(req, trustProxy),
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
result = renderError(error, errorRequest(req), opts?.onError);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isStreamResult(result)) {
|
|
||||||
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
|
|
||||||
await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const response: ResponseShape = result;
|
|
||||||
res.writeHead(response.status, response.headers);
|
|
||||||
res.end(response.body);
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user