Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ Key: uses `node:http`/`node:https` (not `fetch`), global queue with 100ms interv

**Timeout:** a request is aborted after 30 seconds. `HTTP_TIMEOUT_MS` sets another limit for the whole process.

**Response size:** a body is read inside `makeHttpRequest`, counted after decompression, and the request fails with `HttpResponseTooLargeError` past 64 MiB. `HTTP_MAX_RESPONSE_BYTES` sets another limit for the whole process, `maxResponseBytes` in a request's `options` for one request. Such a failure is not retried.

**ZIP archives:** read entries through `createZipEntryReader()` (`src/zipLimits.ts`), never `zip.readAsText()` or `entry.getData()` directly, and pass `zipMaxDownloadBytes()` as the download's `maxResponseBytes`. The reader refuses an entry over `ZIP_MAX_ENTRY_BYTES` (128 MiB) and stops at `ZIP_MAX_TOTAL_BYTES` (512 MiB) per archive, with a `ZipTooLargeError`.

**HTTP transport:** `setHttpTransport(transport)` puts `transport(request, caller, send)` between the queue and the network. It sees every attempt after the injectors, never a cache hit. A request outside `@http` therefore goes through `makeHttpRequest(options, caller)`, never through the global `fetch`.

**HTTP cache hits:** `setHttpCacheObserver(observer)` reports every request served from the HTTP cache with the request, its caller, the cached body and its expiry.
Expand Down
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,22 @@ EFTELING_FETCHWAITTIMES_CACHESECONDS=0 # never serve wait times from the cac
HTTP_TIMEOUT_MS=10000 # give up on a request after 10 seconds
```

`HTTP_MAX_RESPONSE_BYTES` sets the largest response body a request may return, counted after decompression. The default is 64 MiB. A larger body fails the request with an `HttpResponseTooLargeError`, which names the limit:

```
HTTP_MAX_RESPONSE_BYTES=134217728 # accept bodies up to 128 MiB
```

A single request can carry its own limit, as `maxResponseBytes` in the options of `makeHttpRequest`, or in the `options` of the request an `@http` method returns.

The destinations that download a ZIP archive have three limits of their own, since an archive is larger than other responses and its entries are larger again once inflated. Going past one fails with a `ZipTooLargeError`:

```
ZIP_MAX_DOWNLOAD_BYTES=268435456 # the archive itself, default 256 MiB
ZIP_MAX_ENTRY_BYTES=134217728 # one entry, uncompressed, default 128 MiB
ZIP_MAX_TOTAL_BYTES=536870912 # all entries read from one archive, uncompressed, default 512 MiB
```

## Architecture

The library uses a **decorator-based design** with TypeScript:
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
},
"dependencies": {
"@themeparks/typelib": "^2.0.0",
"adm-zip": "^0.6.0",
"adm-zip": "^0.6.1",
"ajv": "^8.17.1",
"sift": "^17.1.3",
"tz-lookup": "^6.1.25",
Expand Down
310 changes: 310 additions & 0 deletions src/__tests__/httpMaxResponseSize.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,310 @@
/**
* The limit on the size of a response body.
*
* `makeHttpRequest` reads a body while counting its bytes and gives up past
* `HTTP_MAX_RESPONSE_BYTES` (64 MiB unless set), or past the
* `maxResponseBytes` of the request. The count is of the decompressed body.
* Everything runs against a loopback server that records how many bytes it
* managed to send before the client went away, so "gives up" is measured on
* the sending side rather than taken from the error alone.
*/
import {createServer, Server, ServerResponse} from 'node:http';
import type {AddressInfo} from 'node:net';
import {gzipSync} from 'node:zlib';
import {HttpResponseTooLargeError, httpMaxResponseBytes, makeHttpRequest} from '../httpProxy.js';
import {http, HTTPObj, stopHttpQueue} from '../http.js';

const ENV = 'HTTP_MAX_RESPONSE_BYTES';
const KIB = 1024;
const MIB = 1024 * KIB;

/** How much `/endless` would send if nobody stopped it. */
const ENDLESS_BYTES = 64 * MIB;
/** `/gzip` inflates to this from a few kilobytes on the wire. */
const GZIP_INFLATED_BYTES = 8 * MIB;
const GZIP_BODY = gzipSync(Buffer.alloc(GZIP_INFLATED_BYTES));
const SMALL_BODY = 'x'.repeat(100 * KIB);

type Sent = {bytes: number; closedEarly: boolean; finished: Promise<void>};

function saveEnv(): () => void {
const saved = process.env[ENV];
delete process.env[ENV];
return () => {
if (saved === undefined) delete process.env[ENV];
else process.env[ENV] = saved;
};
}

describe('httpMaxResponseBytes', () => {
let restore: () => void;

beforeEach(() => {
restore = saveEnv();
});

afterEach(() => {
restore();
});

it('defaults to 64 MiB', () => {
expect(httpMaxResponseBytes()).toBe(64 * MIB);
});

it('reads a positive whole number of bytes', () => {
process.env[ENV] = '1048576';
expect(httpMaxResponseBytes()).toBe(MIB);
});

it('falls back to the default on anything else', () => {
for (const value of ['', '0', '-1', 'abc', '1.5', 'Infinity']) {
process.env[ENV] = value;
expect(httpMaxResponseBytes(), `value "${value}"`).toBe(64 * MIB);
}
});
});

describe('the size limit on a response', () => {
let server: Server;
let baseURL: string;
let restore: () => void;
/** What the server sent for each path, most recent request last. */
const sent = new Map<string, Sent[]>();

/** Write `total` bytes in 64 KiB chunks, waiting for the client to take them. */
function stream(res: ServerResponse, total: number, record: Sent, done: () => void): void {
const chunk = Buffer.alloc(64 * KIB, 0x61);
const pump = () => {
while (record.bytes < total) {
if (res.destroyed) return;
const size = Math.min(chunk.length, total - record.bytes);
record.bytes += size;
if (!res.write(size === chunk.length ? chunk : chunk.subarray(0, size))) {
res.once('drain', pump);
return;
}
}
res.end();
};
res.on('close', () => {
record.closedEarly = !res.writableFinished;
done();
});
pump();
}

function lastSent(path: string): Sent {
const records = sent.get(path) || [];
return records[records.length - 1];
}

beforeAll(async () => {
server = createServer((req, res) => {
const path = (req.url || '/').split('?')[0];
let done!: () => void;
const record: Sent = {bytes: 0, closedEarly: false, finished: new Promise<void>(resolve => { done = resolve; })};
sent.set(path, [...(sent.get(path) || []), record]);

if (path === '/endless') {
// No Content-Length: the client cannot know the size without reading.
res.writeHead(200, {'Content-Type': 'application/octet-stream'});
stream(res, ENDLESS_BYTES, record, done);
} else if (path === '/declared') {
res.writeHead(200, {'Content-Type': 'application/octet-stream', 'Content-Length': ENDLESS_BYTES});
stream(res, ENDLESS_BYTES, record, done);
} else if (path === '/gzip') {
res.writeHead(200, {'Content-Type': 'application/json', 'Content-Encoding': 'gzip', 'Content-Length': GZIP_BODY.length});
record.bytes = GZIP_BODY.length;
res.on('close', done);
res.end(GZIP_BODY);
} else if (path === '/small') {
res.writeHead(200, [
['Content-Type', 'text/plain'],
['Set-Cookie', 'a=1'],
['Set-Cookie', 'b=2'],
['X-Probe', 'kept'],
] as any);
res.on('close', done);
res.end(SMALL_BODY);
} else if (path === '/stall') {
// Headers and a first chunk, then silence.
res.writeHead(200, {'Content-Type': 'text/plain'});
res.on('close', done);
res.write('partial');
} else if (path === '/redirect') {
res.writeHead(303, {'Location': `${baseURL}/small`});
res.on('close', done);
res.end();
} else {
const status = /^\/status\/(\d{3})$/.exec(path);
res.writeHead(status ? Number(status[1]) : 404);
res.on('close', done);
res.end();
}
});
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
baseURL = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});

afterAll(async () => {
stopHttpQueue();
server.closeAllConnections();
await new Promise<void>((resolve, reject) => server.close(err => (err ? reject(err) : resolve())));
});

beforeEach(() => {
restore = saveEnv();
sent.clear();
});

afterEach(() => {
restore();
});

it('gives up on a body past the limit, long before the body ends', async () => {
const error = await makeHttpRequest({method: 'GET', url: `${baseURL}/endless`, maxResponseBytes: MIB})
.then(() => null, e => e);

expect(error).toBeInstanceOf(HttpResponseTooLargeError);
expect(error.name).toBe('HttpResponseTooLargeError');
expect(error.limitBytes).toBe(MIB);
expect(error.message).toContain(`larger than the limit of ${MIB} bytes`);
expect(error.message).toContain(`GET ${baseURL}/endless`);
// The error says how to raise the limit, both ways.
expect(error.message).toContain('HTTP_MAX_RESPONSE_BYTES');
expect(error.message).toContain('maxResponseBytes');

// The server was cut off: the connection closed before the body ended,
// with a small part of the 64 MiB sent. The margin over the 1 MiB limit
// is what the socket buffers on both sides can hold.
const record = lastSent('/endless');
await record.finished;
expect(record.closedEarly).toBe(true);
expect(record.bytes).toBeLessThan(ENDLESS_BYTES / 4);
});

it('refuses a body whose stated length is past the limit without reading it', async () => {
const error = await makeHttpRequest({method: 'GET', url: `${baseURL}/declared`, maxResponseBytes: MIB})
.then(() => null, e => e);

expect(error).toBeInstanceOf(HttpResponseTooLargeError);
expect(error.limitBytes).toBe(MIB);
const record = lastSent('/declared');
await record.finished;
expect(record.closedEarly).toBe(true);
expect(record.bytes).toBeLessThan(ENDLESS_BYTES / 4);
});

it('counts the decompressed size, not the bytes on the wire', async () => {
// A few kilobytes travel, well under the limit; 8 MiB come out.
expect(GZIP_BODY.length).toBeLessThan(MIB / 10);

const error = await makeHttpRequest({method: 'GET', url: `${baseURL}/gzip`, maxResponseBytes: MIB})
.then(() => null, e => e);
expect(error).toBeInstanceOf(HttpResponseTooLargeError);
expect(error.limitBytes).toBe(MIB);

// The same body is fine under a limit above its decompressed size.
const response = await makeHttpRequest({method: 'GET', url: `${baseURL}/gzip`, maxResponseBytes: GZIP_INFLATED_BYTES});
expect((await response.arrayBuffer()).byteLength).toBe(GZIP_INFLATED_BYTES);
});

it('returns a body under the limit unchanged, with its status and headers', async () => {
const response = await makeHttpRequest({method: 'GET', url: `${baseURL}/small`, maxResponseBytes: MIB});

expect(response.status).toBe(200);
expect(response.ok).toBe(true);
expect(response.url).toBe(`${baseURL}/small`);
expect(response.headers.get('content-type')).toBe('text/plain');
expect(response.headers.get('x-probe')).toBe('kept');
expect(response.headers.getSetCookie()).toEqual(['a=1', 'b=2']);
// Still unread, and clonable, as the transport contract requires.
expect(response.bodyUsed).toBe(false);
expect(await response.clone().text()).toBe(SMALL_BODY);
expect(await response.text()).toBe(SMALL_BODY);
});

it('accepts a body of exactly the limit', async () => {
const response = await makeHttpRequest({method: 'GET', url: `${baseURL}/small`, maxResponseBytes: SMALL_BODY.length});
expect((await response.text()).length).toBe(SMALL_BODY.length);

await expect(makeHttpRequest({method: 'GET', url: `${baseURL}/small`, maxResponseBytes: SMALL_BODY.length - 1}))
.rejects.toBeInstanceOf(HttpResponseTooLargeError);
});

it('passes responses without a body through', async () => {
for (const status of [204, 304]) {
const response = await makeHttpRequest({method: 'GET', url: `${baseURL}/status/${status}`});
expect(response.status, `status ${status}`).toBe(status);
expect(await response.text()).toBe('');
}

const head = await makeHttpRequest({method: 'HEAD', url: `${baseURL}/small`});
expect(head.status).toBe(200);

// A redirect is still handed back as it came, Location and all.
const redirect = await makeHttpRequest({method: 'GET', url: `${baseURL}/redirect`});
expect(redirect.status).toBe(303);
expect(redirect.headers.get('location')).toBe(`${baseURL}/small`);
});

it('takes the limit from HTTP_MAX_RESPONSE_BYTES', async () => {
process.env[ENV] = '1000';
const error = await makeHttpRequest({method: 'GET', url: `${baseURL}/small`}).then(() => null, e => e);
expect(error).toBeInstanceOf(HttpResponseTooLargeError);
expect(error.limitBytes).toBe(1000);
});

it('lets an explicit maxResponseBytes win over the environment', async () => {
process.env[ENV] = '1000';
const response = await makeHttpRequest({method: 'GET', url: `${baseURL}/small`, maxResponseBytes: MIB});
expect(response.status).toBe(200);
});

it('reports a body that stalls as a timeout, as before', async () => {
await expect(makeHttpRequest({method: 'GET', url: `${baseURL}/stall`, timeoutMs: 200}))
.rejects.toThrow(`HTTP request timed out after 200ms: GET ${baseURL}/stall`);
});

describe('through @http', () => {
class Client {
constructor(private readonly base: string) {}

@http({cacheSeconds: 0, retries: 2})
async fetchEndless(): Promise<HTTPObj> {
return {method: 'GET', url: `${this.base}/endless`, options: {maxResponseBytes: MIB}} as HTTPObj;
}

@http({cacheSeconds: 0})
async fetchSmall(): Promise<HTTPObj> {
return {method: 'GET', url: `${this.base}/small`, options: {maxResponseBytes: MIB}} as HTTPObj;
}

@http({cacheSeconds: 0})
async fetchSmallByDefault(): Promise<HTTPObj> {
return {method: 'GET', url: `${this.base}/small`} as HTTPObj;
}
}

it('fails the request with the same error class and does not retry it', async () => {
const error = await new Client(baseURL).fetchEndless().then(() => null, e => e);

expect(error).toBeInstanceOf(HttpResponseTooLargeError);
expect(error.limitBytes).toBe(MIB);
expect(error.message).toContain('HTTP_MAX_RESPONSE_BYTES');
expect(error.cause).toBeInstanceOf(HttpResponseTooLargeError);
// Two retries were allowed; a second attempt would only download it again.
expect(sent.get('/endless')).toHaveLength(1);
});

it('takes the limit from the options of the request', async () => {
process.env[ENV] = '1000';
const client = new Client(baseURL);
expect(await (await client.fetchSmall()).text()).toBe(SMALL_BODY);
await expect(client.fetchSmallByDefault()).rejects.toBeInstanceOf(HttpResponseTooLargeError);
});
});
});
Loading
Loading