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
+405
-9
No files matched your search
@@ -141,7 +141,7 @@ without growing the runtime dependency tree past `reflect-metadata`:
|
|||||||
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
|
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
|
||||||
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
|
||||||
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
|
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
|
||||||
- **Ceilings that are already on.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. Configurable, and safe before you configure anything.
|
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there.
|
||||||
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
|
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
|
||||||
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
|
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
|
||||||
- **Shutdown is an extension point, not a `SIGTERM` handler you write.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
|
- **Shutdown is an extension point, not a `SIGTERM` handler you write.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
|
||||||
|
|||||||
@@ -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--;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
+46
-2
@@ -1,5 +1,6 @@
|
|||||||
import type http from 'http';
|
import type http from 'http';
|
||||||
import type https from 'https';
|
import type https from 'https';
|
||||||
|
import { createRequestGate } from './request-gate';
|
||||||
import { renderError, type ErrorRequest } from '../transformers';
|
import { renderError, type ErrorRequest } from '../transformers';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import { buildSecurityHeaders, resolveCors } from '../security';
|
import { buildSecurityHeaders, resolveCors } from '../security';
|
||||||
@@ -7,7 +8,7 @@ import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request';
|
|||||||
import { 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, correlateRequest } from './core';
|
import { handle, correlateRequest, type HandleResult, type Preflight } from './core';
|
||||||
import type { BodyFailure, BodyReader } from './body';
|
import type { BodyFailure, BodyReader } from './body';
|
||||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||||
|
|
||||||
@@ -87,6 +88,7 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
const { routes, bus, opts, trustProxy } = cfg;
|
const { routes, bus, opts, trustProxy } = cfg;
|
||||||
// Built once per server, not once per request — see `BodyReader`.
|
// Built once per server, not once per request — see `BodyReader`.
|
||||||
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
|
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> => {
|
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
|
||||||
// Install the security-header patch BEFORE any routing/response so every path
|
// Install the security-header patch BEFORE any routing/response so every path
|
||||||
@@ -101,7 +103,43 @@ 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));
|
||||||
|
|
||||||
const result = await handle(routes, opts, {
|
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,
|
...correlation,
|
||||||
method: req.method ?? 'GET',
|
method: req.method ?? 'GET',
|
||||||
url: req.url ?? '/',
|
url: req.url ?? '/',
|
||||||
@@ -111,6 +149,12 @@ function createRequestHandler(cfg: HandlerConfig) {
|
|||||||
secure,
|
secure,
|
||||||
ip: deriveIp(req, trustProxy),
|
ip: deriveIp(req, trustProxy),
|
||||||
});
|
});
|
||||||
|
} finally {
|
||||||
|
if (acquired) {
|
||||||
|
acquired = false;
|
||||||
|
gate.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if ('preflight' in result) {
|
if ('preflight' in result) {
|
||||||
res.writeHead(204, result.preflight);
|
res.writeHead(204, result.preflight);
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import type { Logger } from '../logger';
|
|||||||
export interface RequestLimits {
|
export interface RequestLimits {
|
||||||
maxBodyBytes?: number; // default 1_000_000
|
maxBodyBytes?: number; // default 1_000_000
|
||||||
maxConnections?: number; // default 1000; <= 0 means unlimited (Node only)
|
maxConnections?: number; // default 1000; <= 0 means unlimited (Node only)
|
||||||
|
maxConcurrentRequests?: number; // default unlimited; <= 0 means unlimited
|
||||||
requestTimeoutMs?: number; // default 30_000
|
requestTimeoutMs?: number; // default 30_000
|
||||||
headersTimeoutMs?: number; // default 10_000
|
headersTimeoutMs?: number; // default 10_000
|
||||||
keepAliveTimeoutMs?: number; // default 5_000
|
keepAliveTimeoutMs?: number; // default 5_000
|
||||||
|
|||||||
+46
-5
@@ -1,5 +1,6 @@
|
|||||||
import type { StreamEncoder } from '../encoders';
|
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 { mergeInjectedHeaders } from './headers';
|
||||||
import type { BodyFailure, BodyReader, MaybePromise } from './body';
|
import type { BodyFailure, BodyReader, MaybePromise } from './body';
|
||||||
import { HttpError } from '../signals';
|
import { HttpError } from '../signals';
|
||||||
@@ -127,6 +128,7 @@ function outcomeToResponse(result: HandleResult): Response {
|
|||||||
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
||||||
// Built once per server, not once per request — see `BodyReader`.
|
// Built once per server, not once per request — see `BodyReader`.
|
||||||
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
|
const readBody: BodyReader = (source, limit) => readFetchBytes(source, limit, opts);
|
||||||
|
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
|
||||||
|
|
||||||
return async (request: Request): Promise<Response> => {
|
return async (request: Request): Promise<Response> => {
|
||||||
const url = new URL(request.url);
|
const url = new URL(request.url);
|
||||||
@@ -139,7 +141,39 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
// this adapter builds itself — carries the same security/CORS headers every other one does.
|
// this adapter builds itself — carries the same security/CORS headers every other one does.
|
||||||
const injected = computeInjected(opts, { secure, headers });
|
const injected = computeInjected(opts, { secure, headers });
|
||||||
|
|
||||||
const result = await handle(routes, opts, {
|
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,
|
...correlation,
|
||||||
method: request.method,
|
method: request.method,
|
||||||
url: path,
|
url: path,
|
||||||
@@ -156,12 +190,19 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
.trim()
|
.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
|
// 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
|
// so picks up the same authoritative security headers `injected` carries.
|
||||||
// merges every response — including the 204 preflight — with `injected`; this adapter must too).
|
|
||||||
if ('preflight' in result) {
|
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);
|
return outcomeToResponse(result);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { describe, expect, it, test, vi } from 'vitest';
|
import { describe, expect, it, test, vi } from 'vitest';
|
||||||
import * as net from 'node:net';
|
import * as net from 'node:net';
|
||||||
import { once } from 'node:events';
|
import { once } from 'node:events';
|
||||||
|
import { Bus } from '../src/bus';
|
||||||
import { matchRoute, parseQuery, createHttpServer } from '../src/http';
|
import { matchRoute, parseQuery, createHttpServer } from '../src/http';
|
||||||
|
|
||||||
const handler = async () => ({ status: 200, headers: {}, body: 'ok' });
|
const handler = async () => ({ status: 200, headers: {}, body: 'ok' });
|
||||||
@@ -194,6 +195,136 @@ describe('request hardening', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => {
|
||||||
|
let release!: () => void;
|
||||||
|
let started!: () => void;
|
||||||
|
|
||||||
|
const blocked = new Promise<void>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
const firstStarted = new Promise<void>((resolve) => {
|
||||||
|
started = resolve;
|
||||||
|
});
|
||||||
|
|
||||||
|
const bus = new Bus();
|
||||||
|
const ended: Array<{ method?: string; status?: number; requestId?: string }> = [];
|
||||||
|
bus.on('request:end', (event) => {
|
||||||
|
ended.push(event);
|
||||||
|
});
|
||||||
|
|
||||||
|
const server = createHttpServer(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
pattern: '/slow',
|
||||||
|
transport: 'buffer',
|
||||||
|
handler: async () => {
|
||||||
|
started();
|
||||||
|
await blocked;
|
||||||
|
return { status: 200, headers: {}, body: 'ok' };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[],
|
||||||
|
bus,
|
||||||
|
undefined,
|
||||||
|
{
|
||||||
|
limits: { maxConcurrentRequests: 1 },
|
||||||
|
cors: { origins: 'https://example.com' },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
await new Promise<void>((resolve) => server.listen(0, resolve));
|
||||||
|
|
||||||
|
const first = fetch(`${getUrl(server)}/slow`);
|
||||||
|
await firstStarted;
|
||||||
|
|
||||||
|
const rejected = await fetch(`${getUrl(server)}/slow`, {
|
||||||
|
headers: { origin: 'https://example.com' },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(rejected.status).toBe(503);
|
||||||
|
expect(rejected.headers.get('content-type')).toBe('application/json');
|
||||||
|
expect(rejected.headers.get('retry-after')).toBe('1');
|
||||||
|
expect(rejected.headers.get('connection')).toBe('close');
|
||||||
|
expect(rejected.headers.get('access-control-allow-origin')).toBe('https://example.com');
|
||||||
|
expect(rejected.headers.get('x-content-type-options')).toBe('nosniff');
|
||||||
|
expect(rejected.headers.get('x-frame-options')).toBe('SAMEORIGIN');
|
||||||
|
await expect(rejected.json()).resolves.toEqual({ error: 'Service Unavailable' });
|
||||||
|
|
||||||
|
expect(ended).toHaveLength(1);
|
||||||
|
expect(ended[0]).toMatchObject({
|
||||||
|
method: 'GET',
|
||||||
|
status: 503,
|
||||||
|
});
|
||||||
|
expect(ended[0].requestId).toBeTruthy();
|
||||||
|
|
||||||
|
release();
|
||||||
|
|
||||||
|
const firstResponse = await first;
|
||||||
|
expect(firstResponse.status).toBe(200);
|
||||||
|
|
||||||
|
const afterRelease = await fetch(`${getUrl(server)}/slow`);
|
||||||
|
expect(afterRelease.status).toBe(200);
|
||||||
|
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('releases a request slot when the client disconnects before the handler settles', async () => {
|
||||||
|
let started!: () => void;
|
||||||
|
const handlerStarted = new Promise<void>((resolve) => {
|
||||||
|
started = resolve;
|
||||||
|
});
|
||||||
|
|
||||||
|
const server = createHttpServer(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
pattern: '/hang',
|
||||||
|
transport: 'buffer',
|
||||||
|
handler: async () => {
|
||||||
|
started();
|
||||||
|
await new Promise(() => {});
|
||||||
|
return { status: 200, headers: {}, body: 'never' };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
pattern: '/ok',
|
||||||
|
transport: 'buffer',
|
||||||
|
handler: async () => ({ status: 200, headers: {}, body: 'ok' }),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[],
|
||||||
|
undefined,
|
||||||
|
undefined,
|
||||||
|
{ limits: { maxConcurrentRequests: 1 } },
|
||||||
|
);
|
||||||
|
|
||||||
|
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||||
|
const address = server.address();
|
||||||
|
if (!address || typeof address === 'string') throw new Error('server did not bind to a TCP port');
|
||||||
|
|
||||||
|
const responseClosed = new Promise<void>((resolve) => {
|
||||||
|
server.once('request', (_req, res) => {
|
||||||
|
res.once('close', resolve);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = net.createConnection({ host: '127.0.0.1', port: address.port });
|
||||||
|
await once(client, 'connect');
|
||||||
|
client.write('GET /hang HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n');
|
||||||
|
|
||||||
|
await handlerStarted;
|
||||||
|
client.destroy();
|
||||||
|
await responseClosed;
|
||||||
|
|
||||||
|
const afterDisconnect = await fetch(`${getUrl(server)}/ok`);
|
||||||
|
expect(afterDisconnect.status).toBe(200);
|
||||||
|
|
||||||
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||||
|
});
|
||||||
|
|
||||||
it('requestTimeout does NOT kill an in-flight SSE stream (streaming regression)', async () => {
|
it('requestTimeout does NOT kill an in-flight SSE stream (streaming regression)', async () => {
|
||||||
async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } }
|
async function* feed() { for (let n = 1; n <= 3; n++) { yield { n }; await new Promise((r) => setTimeout(r, 80)); } }
|
||||||
const server = createHttpServer(
|
const server = createHttpServer(
|
||||||
|
|||||||
+150
-1
@@ -1,5 +1,6 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
import { asReadableStream, toBodyInit } from '../src/http/web';
|
import { Bus } from '../src/bus';
|
||||||
|
import { asReadableStream, buildFetch, toBodyInit } from '../src/http/web';
|
||||||
import { sseEncoder } from '../src/encoders';
|
import { sseEncoder } from '../src/encoders';
|
||||||
|
|
||||||
async function* nums() { yield { n: 1 }; yield { n: 2 }; }
|
async function* nums() { yield { n: 1 }; yield { n: 2 }; }
|
||||||
@@ -46,4 +47,152 @@ describe('asReadableStream', () => {
|
|||||||
await new Promise((r) => setTimeout(r, 10));
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
expect(returned).toBe(true);
|
expect(returned).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('buildFetch request gate', () => {
|
||||||
|
it('does not permanently exhaust the gate when CORS setup throws', async () => {
|
||||||
|
let attempts = 0;
|
||||||
|
|
||||||
|
const fetchHandler = buildFetch(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
pattern: '/ok',
|
||||||
|
transport: 'buffer',
|
||||||
|
handler: async () => ({ status: 200, headers: {}, body: 'ok' }),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{
|
||||||
|
limits: { maxConcurrentRequests: 2 },
|
||||||
|
cors: {
|
||||||
|
origins: () => {
|
||||||
|
attempts++;
|
||||||
|
if (attempts <= 2) throw new Error('transient CORS failure');
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const request = () =>
|
||||||
|
new Request('http://localhost/ok', {
|
||||||
|
headers: { origin: 'https://example.com' },
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(fetchHandler(request())).rejects.toThrow('transient CORS failure');
|
||||||
|
await expect(fetchHandler(request())).rejects.toThrow('transient CORS failure');
|
||||||
|
|
||||||
|
const recovered = await fetchHandler(request());
|
||||||
|
expect(recovered.status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => {
|
||||||
|
let release!: () => void;
|
||||||
|
let started!: () => void;
|
||||||
|
|
||||||
|
const blocked = new Promise<void>((resolve) => {
|
||||||
|
release = resolve;
|
||||||
|
});
|
||||||
|
const firstStarted = new Promise<void>((resolve) => {
|
||||||
|
started = resolve;
|
||||||
|
});
|
||||||
|
|
||||||
|
const bus = new Bus();
|
||||||
|
const ended: Array<{ method?: string; status?: number; requestId?: string }> = [];
|
||||||
|
bus.on('request:end', (event) => {
|
||||||
|
ended.push(event);
|
||||||
|
});
|
||||||
|
|
||||||
|
const fetchHandler = buildFetch(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
pattern: '/slow',
|
||||||
|
transport: 'buffer',
|
||||||
|
handler: async () => {
|
||||||
|
started();
|
||||||
|
await blocked;
|
||||||
|
return { status: 200, headers: {}, body: 'ok' };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{
|
||||||
|
bus,
|
||||||
|
limits: { maxConcurrentRequests: 1 },
|
||||||
|
cors: { origins: 'https://example.com' },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const first = fetchHandler(new Request('http://localhost/slow'));
|
||||||
|
await firstStarted;
|
||||||
|
|
||||||
|
const rejected = await fetchHandler(
|
||||||
|
new Request('http://localhost/slow', {
|
||||||
|
headers: { origin: 'https://example.com' },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(rejected.status).toBe(503);
|
||||||
|
expect(rejected.headers.get('content-type')).toBe('application/json');
|
||||||
|
expect(rejected.headers.get('retry-after')).toBe('1');
|
||||||
|
expect(rejected.headers.get('access-control-allow-origin')).toBe('https://example.com');
|
||||||
|
expect(rejected.headers.get('x-content-type-options')).toBe('nosniff');
|
||||||
|
expect(rejected.headers.get('x-frame-options')).toBe('SAMEORIGIN');
|
||||||
|
await expect(rejected.json()).resolves.toEqual({ error: 'Service Unavailable' });
|
||||||
|
|
||||||
|
expect(ended).toHaveLength(1);
|
||||||
|
expect(ended[0]).toMatchObject({
|
||||||
|
method: 'GET',
|
||||||
|
status: 503,
|
||||||
|
});
|
||||||
|
expect(ended[0].requestId).toBeTruthy();
|
||||||
|
|
||||||
|
release();
|
||||||
|
|
||||||
|
expect((await first).status).toBe(200);
|
||||||
|
|
||||||
|
const afterRelease = await fetchHandler(new Request('http://localhost/slow'));
|
||||||
|
expect(afterRelease.status).toBe(200);
|
||||||
|
});
|
||||||
|
it('releases the slot when a streaming handler returns', async () => {
|
||||||
|
async function* stream() {
|
||||||
|
yield { n: 1 };
|
||||||
|
await new Promise(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchHandler = buildFetch(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
method: 'GET',
|
||||||
|
pattern: '/stream',
|
||||||
|
transport: 'sse',
|
||||||
|
handler: async () => ({ stream: stream() }),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{ limits: { maxConcurrentRequests: 1 } },
|
||||||
|
);
|
||||||
|
|
||||||
|
const first = await fetchHandler(
|
||||||
|
new Request('http://localhost/stream', {
|
||||||
|
headers: { accept: 'text/event-stream' },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(first.status).toBe(200);
|
||||||
|
|
||||||
|
// The first response stream is still open, but its request slot should
|
||||||
|
// already be released once handle() has returned.
|
||||||
|
const second = await fetchHandler(
|
||||||
|
new Request('http://localhost/stream', {
|
||||||
|
headers: { accept: 'text/event-stream' },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(second.status).toBe(200);
|
||||||
|
|
||||||
|
await first.body?.cancel();
|
||||||
|
await second.body?.cancel();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user