Files
core/test/web-stream.test.ts
chrnx b8b3548f15
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
perf(cors): resolve the request's headers once, not two or three times
`security` and `cors` were computed twice for every request and three times for a
preflight: once in the adapter, to seed the headers a response written *above*
`handle()` still has to carry — a shed 503, a 413 from the body reader — and again in
`dispatch`, plus a third time inside `corsPreflightHeaders`.

Nothing was incorrect, because the predicate is expected to be pure with respect to one
request. The cost is that `cors.origins` is a predicate precisely so it can be a lookup:
an allowlist in Redis, a tenant query. The framework charged the caller's latency budget
and their backend two to three times for an answer whose inputs did not change in
between, and made a predicate with a counter in it count double.

`handle()` now takes the headers the adapter already computed and hands them down, with
`computeInjected` kept as the fallback for a caller that has none.
`corsPreflightHeaders` extends that result instead of re-deriving it. The Node adapter
was carrying its own copy of `computeInjected`, inlined; it uses the real one now, which
is what removes the duplicate rather than papering over it.

Measured against the built `dist/`, same script that produced the numbers in the issue:

    GET with Origin      2x -> 1x
    OPTIONS preflight    3x -> 1x
    buildFetch, Origin   2x -> 1x
    GET without Origin   0x -> 0x   (never reached the predicate; unchanged)

The risk here is not the call count, it is that `injected` carries the security headers
onto every response shape — so the tests that matter are the existing ones across
`transport-security`, `http-headers`, `fetch`, `parity` and `web-stream`, all green.
The two new tests assert the count directly, on both adapters, which is the assertion
that keeps it from drifting back.

Closes #77.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:27:32 -05:00

231 lines
7.7 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import { Bus } from '../src/bus';
import { asReadableStream, buildFetch, toBodyInit } from '../src/http/web';
import { sseEncoder } from '../src/encoders';
async function* nums() { yield { n: 1 }; yield { n: 2 }; }
describe('toBodyInit', () => {
it('passes a string through untouched', () => {
expect(toBodyInit('hello')).toBe('hello');
});
// `Buffer.from` allocates inside a shared 8 KB pool, so these bytes sit at a non-zero byteOffset.
// A conversion that re-views the backing store without the offset and length returns the entire
// pool — every other allocation in it included. Asserting the length alone catches that.
it('re-views a pooled Buffer as its own bytes, not the whole pool', async () => {
const buf = Buffer.from([0x00, 0x89, 0xff, 0xfe, 0x0a]);
expect(buf.byteOffset).toBeGreaterThan(0); // guards the premise: this Buffer really is pooled
expect(buf.buffer.byteLength).toBeGreaterThan(buf.byteLength);
const bytes = new Uint8Array(await new Response(toBodyInit(buf)).arrayBuffer());
expect(bytes.byteLength).toBe(5);
expect([...bytes]).toEqual([0x00, 0x89, 0xff, 0xfe, 0x0a]);
});
it('does not copy — the view shares the backing store', () => {
const buf = Buffer.from([1, 2, 3]);
expect((toBodyInit(buf) as Uint8Array).buffer).toBe(buf.buffer);
});
});
describe('asReadableStream', () => {
it('encodes each yielded value with the encoder', async () => {
const rs = asReadableStream(nums(), sseEncoder);
const text = await new Response(rs).text();
expect(text).toContain('data: {"n":1}');
expect(text).toContain('data: {"n":2}');
});
it('cancels the source iterator when the stream is cancelled', async () => {
let returned = false;
async function* forever() { try { while (true) yield { t: 1 }; } finally { returned = true; } }
const rs = asReadableStream(forever(), sseEncoder);
const reader = rs.getReader();
await reader.read();
await reader.cancel();
await new Promise((r) => setTimeout(r, 10));
expect(returned).toBe(true);
});
});
describe('buildFetch request gate', () => {
it('rides out a transient CORS predicate failure without leaking a gate slot', async () => {
// A flag rather than an attempt counter: `computeInjected` runs both in this adapter and again
// inside `handle()`, so the predicate is consulted more than once per request.
let lookupDown = true;
const fetchHandler = buildFetch(
[
{
method: 'GET',
pattern: '/ok',
transport: 'buffer',
handler: async () => ({ status: 200, headers: {}, body: 'ok' }),
},
],
{
limits: { maxConcurrentRequests: 2 },
cors: {
origins: () => {
if (lookupDown) throw new Error('transient CORS failure');
return true;
},
},
},
);
const request = () =>
new Request('http://localhost/ok', {
headers: { origin: 'https://example.com' },
});
// While the lookup is down the origin is denied — the request is answered, just without the
// header that would let the browser read it. A failed lookup has not said yes.
for (let i = 0; i < 2; i++) {
const denied = await fetchHandler(request());
expect(denied.status).toBe(200);
expect(denied.headers.get('access-control-allow-origin')).toBeNull();
}
// Once the lookup recovers the origin is allowed again, which also proves the two failures
// returned their slots: a budget of 2 that leaked would have shed this one.
lookupDown = false;
const recovered = await fetchHandler(request());
expect(recovered.status).toBe(200);
expect(recovered.headers.get('access-control-allow-origin')).toBe('https://example.com');
});
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('consults a cors.origins predicate once per request on the fetch path too', async () => {
let calls = 0;
const fetchHandler = buildFetch(
[{ method: 'GET', pattern: '/ok', transport: 'buffer',
handler: async () => ({ status: 200, headers: {}, body: 'ok' }) }],
{ cors: { origins: () => { calls++; return true; } } },
);
const res = await fetchHandler(new Request('http://localhost/ok', { headers: { origin: 'https://a.com' } }));
expect(res.headers.get('access-control-allow-origin')).toBe('https://a.com');
expect(calls).toBe(1);
calls = 0;
const preflight = await fetchHandler(new Request('http://localhost/ok', {
method: 'OPTIONS',
headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' },
}));
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-methods')).toContain('GET');
expect(calls).toBe(1);
});
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();
});
});