feat: cap concurrent requests across runtimes
CI / dco (push) Has been skipped
CI / build (push) Successful in 28s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (bun) (push) Successful in 59s
CI / runtimes (edge) (push) Successful in 11s
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / dco (push) Has been skipped
CI / build (push) Successful in 28s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (bun) (push) Successful in 59s
CI / runtimes (edge) (push) Successful in 11s
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 29s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
This commit is contained in:
1 parent
82e1678dea
commit
ff94e55496
7 files changed
+430
-34
No files matched your search
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Per-server/adapter request budget.
|
||||
*
|
||||
* `acquire()` reserves one in-flight request slot. `release()` returns that slot when routing and
|
||||
* handler execution finishes; a returned stream does not hold the slot for the stream's lifetime.
|
||||
*/
|
||||
export interface RequestGate {
|
||||
acquire(): boolean;
|
||||
release(): void;
|
||||
}
|
||||
|
||||
/** Creates an unlimited gate when `limit` is undefined or non-positive. */
|
||||
export function createRequestGate(limit: number | undefined): RequestGate {
|
||||
let active = 0;
|
||||
|
||||
return {
|
||||
acquire(): boolean {
|
||||
if (limit === undefined || limit <= 0) return true;
|
||||
if (active >= limit) return false;
|
||||
|
||||
active++;
|
||||
return true;
|
||||
},
|
||||
|
||||
release(): void {
|
||||
if (limit === undefined || limit <= 0) return;
|
||||
if (active > 0) active--;
|
||||
},
|
||||
};
|
||||
}
|
||||
+55
-11
@@ -1,5 +1,6 @@
|
||||
import type http from 'http';
|
||||
import type https from 'https';
|
||||
import { createRequestGate } from './request-gate';
|
||||
import { renderError, type ErrorRequest } from '../transformers';
|
||||
import type { Bus } from '../bus';
|
||||
import { buildSecurityHeaders, resolveCors } from '../security';
|
||||
@@ -7,7 +8,7 @@ import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
||||
import { pipeStream } from './stream';
|
||||
import { attachWs } from './ws';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import { handle, correlateRequest } from './core';
|
||||
import { handle, correlateRequest, type HandleResult, type Preflight } from './core';
|
||||
import type { BodyFailure, BodyReader } from './body';
|
||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||
|
||||
@@ -87,6 +88,7 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
const { routes, bus, opts, trustProxy } = cfg;
|
||||
// Built once per server, not once per request — see `BodyReader`.
|
||||
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
|
||||
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
|
||||
|
||||
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||
// Install the security-header patch BEFORE any routing/response so every path
|
||||
@@ -101,16 +103,58 @@ function createRequestHandler(cfg: HandlerConfig) {
|
||||
// by reference at writeHead time, so keys added here still land on every response.
|
||||
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
...correlation,
|
||||
method: req.method ?? 'GET',
|
||||
url: req.url ?? '/',
|
||||
headers: req.headers,
|
||||
readBody,
|
||||
source: req,
|
||||
secure,
|
||||
ip: deriveIp(req, trustProxy),
|
||||
});
|
||||
let result: HandleResult | Preflight;
|
||||
let acquired = false;
|
||||
const watchingEnd = bus?.hasListeners('request:end') ?? false;
|
||||
const startedAt = watchingEnd ? performance.now() : 0;
|
||||
|
||||
try {
|
||||
if (!gate.acquire()) {
|
||||
if (watchingEnd) {
|
||||
const method = req.method ?? 'GET';
|
||||
const url = req.url ?? '/';
|
||||
bus!.emit('request:end', {
|
||||
name: `${method} ${url}`,
|
||||
method,
|
||||
status: 503,
|
||||
durationMs: performance.now() - startedAt,
|
||||
requestId: correlation.requestId,
|
||||
traceId: correlation.traceId,
|
||||
});
|
||||
}
|
||||
|
||||
res.writeHead(503, {
|
||||
'content-type': 'application/json',
|
||||
'retry-after': '1',
|
||||
connection: 'close',
|
||||
});
|
||||
res.end(JSON.stringify({ error: 'Service Unavailable' }));
|
||||
return;
|
||||
}
|
||||
|
||||
acquired = true;
|
||||
res.once('close', () => {
|
||||
if (!acquired) return;
|
||||
acquired = false;
|
||||
gate.release();
|
||||
});
|
||||
|
||||
result = await handle(routes, opts, {
|
||||
...correlation,
|
||||
method: req.method ?? 'GET',
|
||||
url: req.url ?? '/',
|
||||
headers: req.headers,
|
||||
readBody,
|
||||
source: req,
|
||||
secure,
|
||||
ip: deriveIp(req, trustProxy),
|
||||
});
|
||||
} finally {
|
||||
if (acquired) {
|
||||
acquired = false;
|
||||
gate.release();
|
||||
}
|
||||
}
|
||||
|
||||
if ('preflight' in result) {
|
||||
res.writeHead(204, result.preflight);
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { Logger } from '../logger';
|
||||
export interface RequestLimits {
|
||||
maxBodyBytes?: number; // default 1_000_000
|
||||
maxConnections?: number; // default 1000; <= 0 means unlimited (Node only)
|
||||
maxConcurrentRequests?: number; // default unlimited; <= 0 means unlimited
|
||||
requestTimeoutMs?: number; // default 30_000
|
||||
headersTimeoutMs?: number; // default 10_000
|
||||
keepAliveTimeoutMs?: number; // default 5_000
|
||||
|
||||
+62
-21
@@ -1,5 +1,6 @@
|
||||
import type { StreamEncoder } from '../encoders';
|
||||
import { handle, computeInjected, correlateRequest, type HandleResult } from './core';
|
||||
import { createRequestGate } from './request-gate';
|
||||
import { handle, computeInjected, correlateRequest, type HandleResult, type Preflight } from './core';
|
||||
import { mergeInjectedHeaders } from './headers';
|
||||
import type { BodyFailure, BodyReader, MaybePromise } from './body';
|
||||
import { HttpError } from '../signals';
|
||||
@@ -127,6 +128,7 @@ function outcomeToResponse(result: HandleResult): Response {
|
||||
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||
// Built once per server, not once per request — see `BodyReader`.
|
||||
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
|
||||
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
|
||||
|
||||
return async (request: Request): Promise<Response> => {
|
||||
const url = new URL(request.url);
|
||||
@@ -139,29 +141,68 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||
// this adapter builds itself — carries the same security/CORS headers every other one does.
|
||||
const injected = computeInjected(opts, { secure, headers });
|
||||
|
||||
const result = await handle(routes, opts, {
|
||||
...correlation,
|
||||
method: request.method,
|
||||
url: path,
|
||||
headers,
|
||||
readBody,
|
||||
source: request,
|
||||
secure,
|
||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
|
||||
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
|
||||
// peer address to fall back to on the fetch path, so the untrusted case is simply ''.
|
||||
ip: opts?.trustProxy
|
||||
? String(headers['x-forwarded-for'] ?? '')
|
||||
.split(',')[0]
|
||||
.trim()
|
||||
: '',
|
||||
});
|
||||
let result: HandleResult | Preflight;
|
||||
let acquired = false;
|
||||
const watchingEnd = opts?.bus?.hasListeners('request:end') ?? false;
|
||||
const startedAt = watchingEnd ? performance.now() : 0;
|
||||
|
||||
try {
|
||||
if (!gate.acquire()) {
|
||||
if (watchingEnd) {
|
||||
opts!.bus!.emit('request:end', {
|
||||
name: `${request.method} ${path}`,
|
||||
method: request.method,
|
||||
status: 503,
|
||||
durationMs: performance.now() - startedAt,
|
||||
requestId: correlation.requestId,
|
||||
traceId: correlation.traceId,
|
||||
});
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({ error: 'Service Unavailable' }), {
|
||||
status: 503,
|
||||
headers: mergeInjectedHeaders(
|
||||
{
|
||||
'content-type': 'application/json',
|
||||
'retry-after': '1',
|
||||
},
|
||||
injected,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
acquired = true;
|
||||
|
||||
result = await handle(routes, opts, {
|
||||
...correlation,
|
||||
method: request.method,
|
||||
url: path,
|
||||
headers,
|
||||
readBody,
|
||||
source: request,
|
||||
secure,
|
||||
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is
|
||||
// trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket
|
||||
// peer address to fall back to on the fetch path, so the untrusted case is simply ''.
|
||||
ip: opts?.trustProxy
|
||||
? String(headers['x-forwarded-for'] ?? '')
|
||||
.split(',')[0]
|
||||
.trim()
|
||||
: '',
|
||||
});
|
||||
} finally {
|
||||
// Release when routing/handling finishes, not when a returned stream finishes.
|
||||
// Long-lived streams therefore do not permanently consume the request budget.
|
||||
if (acquired) gate.release();
|
||||
}
|
||||
|
||||
// Mirrors the Node adapter, where `result.preflight` is written through the writeHead patch and
|
||||
// so picks up the same authoritative security headers `injected` carries (Node's writeHead patch
|
||||
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
|
||||
// so picks up the same authoritative security headers `injected` carries.
|
||||
if ('preflight' in result) {
|
||||
return new Response(null, { status: 204, headers: mergeInjectedHeaders(result.preflight, injected) });
|
||||
return new Response(null, {
|
||||
status: 204,
|
||||
headers: mergeInjectedHeaders(result.preflight, injected),
|
||||
});
|
||||
}
|
||||
|
||||
return outcomeToResponse(result);
|
||||
|
||||
Reference in new issue
Block a user