feat: request body-size limit (413) and configurable server timeouts
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
4 files changed
+73
-10
No files matched your search
+3
-3
@@ -3,7 +3,7 @@ import { Bus } from './bus';
|
||||
import { Container } from './container';
|
||||
import { topoSort, GraphNode } from './graph';
|
||||
import { runPipeline, PipelineStep } from './pipeline';
|
||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef } from './http';
|
||||
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from './http';
|
||||
import { isAsyncIterable } from './channel';
|
||||
import { JsonTransformer } from './transformers';
|
||||
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from './plugin';
|
||||
@@ -43,7 +43,7 @@ export interface MeshConfig {
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig }): App {
|
||||
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits }): App {
|
||||
const bus = new Bus();
|
||||
const container = new Container();
|
||||
const extraSteps: ScopeNode[] = [];
|
||||
@@ -279,7 +279,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
|
||||
},
|
||||
}));
|
||||
|
||||
const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl);
|
||||
const server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits });
|
||||
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
|
||||
await new Promise<void>((resolve) => server.listen(port, resolve));
|
||||
return server;
|
||||
|
||||
+28
-7
@@ -2,11 +2,20 @@ import http from 'http';
|
||||
import { once } from 'events';
|
||||
import { channel } from './channel';
|
||||
import { errorToResponse } from './transformers';
|
||||
import { HttpError } from './signals';
|
||||
import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
|
||||
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
|
||||
import type { Transport } from './metadata';
|
||||
import type { Bus } from './bus';
|
||||
|
||||
export interface RequestLimits {
|
||||
maxBodyBytes?: number; // default 1_000_000
|
||||
requestTimeoutMs?: number; // default 30_000
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
}
|
||||
export interface HttpOptions { limits?: RequestLimits }
|
||||
|
||||
export type RouteHandler = (req: {
|
||||
method: string; url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
@@ -58,9 +67,14 @@ export function parseQuery(url: string): Record<string, string> {
|
||||
return out;
|
||||
}
|
||||
|
||||
async function readBody(req: http.IncomingMessage): Promise<string | undefined> {
|
||||
async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<string | undefined> {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) chunks.push(chunk as Buffer);
|
||||
let total = 0;
|
||||
for await (const chunk of req) {
|
||||
total += (chunk as Buffer).length;
|
||||
if (total > maxBodyBytes) throw new HttpError(413, 'Payload Too Large');
|
||||
chunks.push(chunk as Buffer);
|
||||
}
|
||||
if (chunks.length === 0) return undefined;
|
||||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
return raw === '' ? undefined : raw;
|
||||
@@ -154,7 +168,10 @@ function attachWs(server: http.Server, wsRoutes: WsRouteDef[], bus?: Bus, meshCo
|
||||
});
|
||||
}
|
||||
|
||||
export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl): http.Server {
|
||||
export function createHttpServer(
|
||||
routes: RouteDef[], wsRoutes: WsRouteDef[] = [], bus?: Bus, meshControl?: MeshControl, opts?: HttpOptions,
|
||||
): http.Server {
|
||||
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = req.url ?? '/';
|
||||
const path = url.split('?')[0];
|
||||
@@ -166,10 +183,11 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = []
|
||||
}
|
||||
let raw: string | undefined;
|
||||
try {
|
||||
raw = await readBody(req);
|
||||
} catch {
|
||||
res.writeHead(500, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ error: 'Internal Server Error' }));
|
||||
raw = await readBody(req, maxBody);
|
||||
} catch (error) {
|
||||
const r = errorToResponse(error);
|
||||
res.writeHead(r.status, { ...r.headers, connection: 'close' });
|
||||
res.end(r.body);
|
||||
return;
|
||||
}
|
||||
let body: unknown = raw;
|
||||
@@ -200,6 +218,9 @@ export function createHttpServer(routes: RouteDef[], wsRoutes: WsRouteDef[] = []
|
||||
res.writeHead(r.status, r.headers);
|
||||
res.end(r.body);
|
||||
});
|
||||
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
|
||||
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
|
||||
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
|
||||
attachWs(server, wsRoutes, bus, meshControl);
|
||||
return server;
|
||||
}
|
||||
@@ -20,6 +20,7 @@ export { inbound, abort } from './params';
|
||||
export { sseEncoder, ndjsonEncoder } from './encoders';
|
||||
export type { StreamEncoder } from './encoders';
|
||||
export type { MeshConfig } from './app';
|
||||
export type { RequestLimits } from './http';
|
||||
export { connectLink } from './mesh/link';
|
||||
export { buildRemote, envelopeFrom } from './mesh/teacup';
|
||||
export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot';
|
||||
|
||||
Reference in new issue
Block a user