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

Signed-off-by: hgshreyas <hgshreyas.cs24@bmsce.ac.in>
This commit is contained in:
hgshreyas authored and Diego Resendez committed 2026-08-31 08:53:14 -05:00
1 parent 82e1678dea
commit ff94e55496
7 files changed
+430 -34

No files matched your search

+62 -21
View File
@@ -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);