Reuse validators for prepared JSON responses

This commit is contained in:
Codex committed 2026-11-16 07:01:14 +00:00
1 parent e1b06cb572
commit 0eee9490c3
3 files changed
+388 -5

No files matched your search

+317
View File
@@ -1,4 +1,5 @@
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { once } from 'node:events';
import type { AddressInfo } from 'node:net';
import test from 'node:test';
@@ -324,3 +325,319 @@ test('ordinary payload properties cannot masquerade as an encoded representation
const base = await start(t, app);
assert.deepEqual(await (await fetch(base)).json(), value);
});
test('builtin ETag is computed once while each fenced delivery owns fresh UTF8, including HEAD and304', async t => {
const app = express();
const value = { text: 'Public 🛰️ <>& "node" ' + 'x'.repeat(1200) };
const body = JSON.stringify(value), marker = PreparedJson(value, body, structuredClone);
const original = Buffer.from, createHash = crypto.createHash;
const deliveries: Buffer[] = [];
let hashes = 0, reads = 0, release!: () => void, reached!: () => void;
const waiting = new Promise<void>(resolve => { reached = resolve; });
const gate = new Promise<void>(resolve => { release = resolve; });
t.mock.method(Buffer, 'from', (value: unknown, ...options: unknown[]) => {
const buffer = Reflect.apply(original, Buffer, [value, ...options]);
if (value === body) deliveries.push(buffer);
return buffer;
});
t.mock.method(crypto, 'createHash', (...args: Parameters<typeof createHash>) => {
if (args[0] === 'sha1') hashes++;
return Reflect.apply(createHash, crypto, args);
});
app.get('/', async (_req, res) => {
let count = 0;
await publicJson(res, async () => {
reads++; count++;
if (reads === 2 && count === 2) { reached(); await gate; }
return 1;
}, async () => marker);
});
const base = await start(t, app);
t.after(() => release());
const pending = fetch(base);
await waiting;
assert.equal(deliveries.length, 0, 'no bytes allocated before final authority completes');
assert.equal(hashes, 0, 'no validator computed before final authority completes');
release();
const first = await pending;
assert.equal(await first.text(), body);
assert.equal(first.headers.get('content-type'), 'application/json; charset=utf-8');
assert.equal(first.headers.get('content-length'), String(Buffer.byteLength(body)));
const etag = first.headers.get('etag')!;
assert.ok(etag);
assert.equal(await (await fetch(base)).text(), body);
const head = await fetch(base, { method: 'HEAD' });
assert.equal(await head.text(), '');
assert.equal(head.headers.get('etag'), etag);
assert.equal(head.headers.get('content-length'), first.headers.get('content-length'));
const cached = await fetch(base, { cache: 'force-cache', headers: { 'If-None-Match': etag } });
assert.equal(cached.status, 304); assert.equal(await cached.text(), '');
assert.equal(reads, 8); assert.equal(deliveries.length, 4);
assert.equal(new Set(deliveries).size, 4, 'no delivery shares mutable bytes');
assert.equal(hashes, 1, 'HEAD and conditional delivery reuse only the builtin validator');
});
test('custom ETag mutation through either setting cannot poison a shared prepared value', async t => {
const app = express(), value = { text: 'visible 🛰️ ' + 'x'.repeat(1200) };
const body = JSON.stringify(value), marker = PreparedJson(value, body);
app.get('/ordinary', (_req, res) => res.json(value));
app.get('/prepared', async (_req, res) => publicJson(res, async () => 1, async () => marker));
const base = await start(t, app);
assert.equal(await (await fetch(base + '/prepared')).text(), body, 'populate the builtin validator');
for (const setting of ['etag', 'etag fn']) {
app.set('etag', 'weak');
const received: Buffer[] = [];
const mutate = (chunk: Buffer) => {
assert.ok(Buffer.isBuffer(chunk));
received.push(chunk);
const index = chunk.indexOf('visible'); assert.ok(index >= 0);
chunk[index] = 'V'.charCodeAt(0);
return '"custom-mutating-validator"';
};
app.set(setting, mutate);
if (setting === 'etag fn') assert.equal(app.get('etag'), 'weak', 'direct fn override leaves ordinary setting unchanged');
const control = await fetch(base + '/ordinary'), prepared = await fetch(base + '/prepared');
const controlBody = await control.text(), preparedBody = await prepared.text();
assert.equal(preparedBody, controlBody); assert.notEqual(preparedBody, body);
assert.equal(prepared.headers.get('etag'), control.headers.get('etag'));
assert.equal(received.length, 2); assert.notEqual(received[0], received[1], 'hooks get fresh per-delivery buffers');
app.set('etag', 'weak');
assert.equal(await (await fetch(base + '/prepared')).text(), body, 'custom hook cannot corrupt later delivery');
}
});
test('builtin validator changes recompute only the last weak or strong ETag', async t => {
const app = express(), value = { text: 'Public 🛰️ <>& ' + 'xyz'.repeat(700) };
const body = JSON.stringify(value), marker = PreparedJson(value, body);
const createHash = crypto.createHash;
let hashes = 0;
t.mock.method(crypto, 'createHash', (...args: Parameters<typeof createHash>) => {
if (args[0] === 'sha1') hashes++;
return Reflect.apply(createHash, crypto, args);
});
app.get('/ordinary', (_req, res) => res.json(value));
app.get('/prepared', async (_req, res) => publicJson(res, async () => 1, async () => marker));
const base = await start(t, app);
let previous = '';
for (const mode of ['weak', 'weak', 'strong', 'strong', 'weak']) {
app.set('etag', mode);
const control = await fetch(base + '/ordinary');
assert.equal(await control.text(), body);
const before = hashes, prepared = await fetch(base + '/prepared');
assert.equal(await prepared.text(), body);
assert.equal(prepared.headers.get('etag'), control.headers.get('etag'));
assert.equal(prepared.headers.get('etag')!.startsWith('W/'), mode === 'weak');
assert.equal(hashes - before, mode === previous ? 0 : 1);
previous = mode;
}
});
test('preset ETag retains ordinary string delivery and conditional semantics', async t => {
const app = express(), value = { text: 'small 🛰️' }, body = JSON.stringify(value);
const marker = PreparedJson(value, body), kinds: string[] = [];
app.use((req, res, next) => {
res.setHeader('ETag', '"application-owned"');
if (req.path === '/prepared') {
const end = res.end;
res.end = function (chunk: unknown, ...args: unknown[]) {
kinds.push(typeof chunk); return Reflect.apply(end, this, [chunk, ...args]);
} as typeof res.end;
}
next();
});
app.get('/ordinary', (_req, res) => res.json(value));
app.get('/prepared', async (_req, res) => publicJson(res, async () => 1, async () => marker));
const base = await start(t, app);
const control = await fetch(base + '/ordinary'), prepared = await fetch(base + '/prepared');
assert.equal(await prepared.text(), await control.text());
for (const name of ['content-type', 'content-length', 'etag']) assert.equal(prepared.headers.get(name), control.headers.get(name));
assert.deepEqual(kinds, ['string']);
const conditional = { cache: 'force-cache' as const, headers: { 'If-None-Match': '"application-owned"' } };
assert.equal((await fetch(base + '/ordinary', conditional)).status, 304);
assert.equal((await fetch(base + '/prepared', conditional)).status, 304);
});
test('custom header setters observe ordinary Content-Length before ETag assignment', async t => {
for (const method of ['set', 'setHeader'] as const) await t.test(method, async child => {
const app = express(), value = { text: '🛰️ public ' + 'xyz'.repeat(700) };
const body = JSON.stringify(value), marker = PreparedJson(value, body);
const observed: Array<{ route: string; length: unknown; type: unknown }> = [];
app.use((req, res, next) => {
const setter = res[method];
Object.defineProperty(res, method, { configurable: true, value: function (name: unknown, ...args: unknown[]) {
if (typeof name === 'string' && name.toLowerCase() === 'etag') {
observed.push({ route: req.path, length: this.getHeader('Content-Length'), type: this.getHeader('Content-Type') });
}
return Reflect.apply(setter, this, [name, ...args]);
} });
next();
});
app.get('/ordinary', (_req, res) => res.json(value));
app.get('/prepared', async (_req, res) => publicJson(res, async () => 1, async () => marker));
const base = await start(child, app);
const control = await fetch(base + '/ordinary'), prepared = await fetch(base + '/prepared');
assert.equal(await prepared.text(), await control.text());
assert.equal(prepared.headers.get('etag'), control.headers.get('etag'));
assert.deepEqual(observed.map(({ route, ...headers }) => headers), [
{ length: String(Buffer.byteLength(body)), type: 'application/json; charset=utf-8' },
{ length: String(Buffer.byteLength(body)), type: 'application/json; charset=utf-8' },
]);
});
});
test('custom header queries retain logical presets and ordinary query behavior', async t => {
for (const method of ['get', 'getHeader', 'hasHeader'] as const) await t.test(method, async child => {
const app = express(), value = { text: 'small 🛰️' }, body = JSON.stringify(value);
const marker = PreparedJson(value, body);
app.use((_req, res, next) => {
const original = res[method];
Object.defineProperty(res, method, { configurable: true, value: function (name: string) {
if (method === 'hasHeader') throw new Error('ordinary send does not query hasHeader');
if (name.toLowerCase() === 'etag') return '"logical-preset"';
return Reflect.apply(original, this, [name]);
} });
next();
});
app.get('/ordinary', (_req, res) => res.json(value));
app.get('/prepared', async (_req, res) => publicJson(res, async () => 1, async () => marker));
const base = await start(child, app);
const control = await fetch(base + '/ordinary'), prepared = await fetch(base + '/prepared');
assert.equal(control.status, 200); assert.equal(prepared.status, 200);
assert.equal(await prepared.text(), await control.text());
for (const name of ['content-type', 'content-length', 'etag']) assert.equal(prepared.headers.get(name), control.headers.get(name));
if (method !== 'hasHeader') assert.equal(prepared.headers.get('etag'), null, 'logical preset prevents generation without writing a new header');
});
});
test('custom application getter retains original lookup count and order', async t => {
const app = express(), value = { text: 'Public 🛰️ ' + 'xyz'.repeat(700) }, body = JSON.stringify(value);
const marker = PreparedJson(value, body);
let lookups: string[] = [];
app.get('/ordinary', (_req, res) => res.json(value));
app.get('/prepared', async (_req, res) => publicJson(res, async () => 1, async () => marker));
const get = app.get;
app.get = function (name: string, ...args: unknown[]) {
if (!args.length) lookups.push(name);
return Reflect.apply(get, this, [name, ...args]);
} as typeof app.get;
const base = await start(t, app);
lookups = [];
const control = await fetch(base + '/ordinary'); assert.equal(await control.text(), body);
const expected = [...lookups];
lookups = [];
const prepared = await fetch(base + '/prepared'); assert.equal(await prepared.text(), body);
const relevant = (names: string[]) => names.filter(name => name.startsWith('json ') || name === 'etag fn');
assert.deepEqual(relevant(expected), ['json escape', 'json replacer', 'json spaces', 'etag fn']);
// PreparedJson's existing settings order differs from res.json, but its only
// etag lookup still belongs to ordinary send after those settings reads.
assert.deepEqual(relevant(lookups), ['json replacer', 'json spaces', 'json escape', 'etag fn']);
assert.equal(lookups.filter(name => name === 'etag fn').length, 1);
assert.equal(prepared.headers.get('etag'), control.headers.get('etag'));
});
test('overridden send receives the original string, preserving preset content types', async t => {
const app = express(), value = { text: 'public 🛰️ ' + 'x'.repeat(1200) };
const body = JSON.stringify(value), marker = PreparedJson(value, body);
const seen: unknown[] = [];
app.use((req, res, next) => {
if (req.query.preset) res.type('application/vnd.ukmesh.map+json');
if (req.path === '/prepared') {
const send = res.send;
res.send = function (body) { seen.push(body); return send.call(this, body); };
}
next();
});
app.get('/ordinary', (_req, res) => res.json(value));
app.get('/prepared', async (_req, res) => publicJson(res, async () => 1, async () => marker));
const base = await start(t, app);
for (const query of ['', '?preset=1']) {
const control = await fetch(base + '/ordinary' + query), prepared = await fetch(base + '/prepared' + query);
assert.equal(await prepared.text(), await control.text());
for (const header of ['content-type', 'content-length', 'etag']) assert.equal(prepared.headers.get(header), control.headers.get(header));
}
assert.deepEqual(seen, [body, body]);
});
test('production compression preserves exact gzip bytes, validators, HEAD and304', async t => {
const { default: compression } = await import('compression');
const { default: http } = await import('node:http');
const { gunzipSync } = await import('node:zlib');
const app = express(), value = { text: 'Public 🛰️ <>& ' + 'xyz'.repeat(1500) };
const body = JSON.stringify(value), marker = PreparedJson(value, body);
let reads = 0;
app.use(compression());
app.get('/ordinary', (_req, res) => res.json(value));
app.get('/prepared', async (_req, res) => {
reads = 0;
await publicJson(res, async () => { reads++; return 1; }, async () => marker);
});
const base = await start(t, app);
const request = (route: string, method = 'GET', headers: Record<string, string> = {}) =>
new Promise<{ status: number; headers: import('node:http').IncomingHttpHeaders; body: Buffer }>((resolve, reject) => {
const req = http.request(base + route, { method, headers: { 'Accept-Encoding': 'gzip', ...headers } }, res => {
const chunks: Buffer[] = [];
res.on('data', chunk => chunks.push(chunk)); res.on('error', reject);
res.on('end', () => resolve({ status: res.statusCode!, headers: res.headers, body: Buffer.concat(chunks) }));
});
req.on('error', reject); req.end();
});
const control = await request('/ordinary'), prepared = await request('/prepared');
assert.equal(control.headers['content-encoding'], 'gzip');
assert.deepEqual(prepared.body, control.body); assert.equal(gunzipSync(prepared.body).toString(), body);
for (const header of ['content-type', 'content-encoding', 'content-length', 'etag', 'vary']) assert.equal(prepared.headers[header], control.headers[header]);
assert.equal(reads, 2);
for (const [method, headers] of [['HEAD', {}], ['GET', { 'If-None-Match': String(control.headers.etag) }]] as const) {
const ordinary = await request('/ordinary', method, headers), actual = await request('/prepared', method, headers);
assert.equal(actual.status, method === 'HEAD' ? 200 : 304); assert.equal(actual.status, ordinary.status);
assert.equal(actual.body.length, 0); assert.equal(reads, 2);
for (const header of ['content-type', 'content-encoding', 'content-length', 'etag', 'vary']) assert.equal(actual.headers[header], ordinary.headers[header]);
}
});
test('custom end mutation under compression preserves repeated-marker ownership', async t => {
const { default: compression } = await import('compression');
const app = express(), value = { text: 'visible 🛰️ ' + 'xyz'.repeat(1000) };
const body = JSON.stringify(value), marker = PreparedJson(value, body);
app.use(compression());
app.use((req, res, next) => {
if (req.query.mutate) {
const end = res.end;
res.end = function (chunk: unknown, ...args: unknown[]) {
assert.ok(Buffer.isBuffer(chunk));
const index = chunk.indexOf('visible'); assert.ok(index >= 0);
chunk[index] = 'V'.charCodeAt(0);
return Reflect.apply(end, this, [chunk, ...args]);
} as typeof res.end;
}
next();
});
app.get('/ordinary', (_req, res) => res.json(value));
app.get('/prepared', async (_req, res) => publicJson(res, async () => 1, async () => marker));
const base = await start(t, app);
assert.equal(await (await fetch(base + '/prepared')).text(), body);
const ordinary = await fetch(base + '/ordinary?mutate=1'), actual = await fetch(base + '/prepared?mutate=1');
const expected = await ordinary.text();
assert.notEqual(expected, body); assert.equal(await actual.text(), expected);
assert.equal(actual.headers.get('etag'), ordinary.headers.get('etag'));
assert.equal(await (await fetch(base + '/prepared')).text(), body, 'transport mutation cannot poison later delivery');
});
test('small UTF16 strings retain original end input even when UTF8 exceeds1000bytes', async t => {
const app = express(); app.disable('etag');
const value = { text: '🛰️'.repeat(200) }, body = JSON.stringify(value);
assert.ok(body.length < 1000); assert.ok(Buffer.byteLength(body) > 1000);
const marker = PreparedJson(value, body), kinds: string[] = [];
app.use((_req, res, next) => {
const end = res.end;
res.end = function (chunk: unknown, ...args: unknown[]) {
kinds.push(typeof chunk); return Reflect.apply(end, this, [chunk, ...args]);
} as typeof res.end;
next();
});
app.get('/ordinary', (_req, res) => res.json(value));
app.get('/prepared', async (_req, res) => publicJson(res, async () => 1, async () => marker));
const base = await start(t, app);
assert.equal(await (await fetch(base + '/ordinary')).text(), body);
assert.equal(await (await fetch(base + '/prepared')).text(), body);
assert.deepEqual(kinds, ['string', 'string']);
});
+35 -5
View File
@@ -1,10 +1,25 @@
import type { Response } from 'express';
import express, { type Response } from 'express';
type EtagGenerator = (body: Buffer, encoding?: string) => string;
const ordinarySend = express.response.send;
const ordinarySet = express.response.set;
const ordinarySetHeader = express.response.setHeader;
const ordinaryGet = express.response.get;
const ordinaryGetHeader = express.response.getHeader;
const ordinaryHasHeader = express.response.hasHeader;
const ordinaryApplicationGet = express.application.get;
const builtinEtagGenerators = new Set<EtagGenerator>(['weak', 'strong'].map(mode => {
const app = express();
app.set('etag', mode);
return app.get('etag fn') as EtagGenerator;
}));
export const PUBLIC_REVALIDATE = 'private, no-cache, must-revalidate';
class PreparedJsonValue<T> {
readonly #value: T;
readonly #encodedBody: string;
#lastEtag?: Readonly<{ generator: EtagGenerator; value: string }>;
readonly #cloneForDelivery?: (value: T) => T;
constructor(value: T, encodedBody: string, cloneForDelivery?: (value: T) => T) {
@@ -18,7 +33,22 @@ class PreparedJsonValue<T> {
// a custom serializer when its representation owner supplied a clone.
const defaultJson = res.app && ['json replacer', 'json spaces', 'json escape']
.every(setting => res.app.get(setting) === undefined);
if (defaultJson) {
const generator = res.app?.get === ordinaryApplicationGet
? res.app.get('etag fn') as EtagGenerator | undefined : undefined;
if (defaultJson && res.send === ordinarySend && res.set === ordinarySet && res.setHeader === ordinarySetHeader
&& res.get === ordinaryGet && res.getHeader === ordinaryGetHeader && res.hasHeader === ordinaryHasHeader
&& !res.hasHeader('Content-Type') && !res.hasHeader('ETag')
&& typeof generator === 'function' && builtinEtagGenerators.has(generator)) {
// Express hashes these same UTF-8 bytes on every ordinary string send.
// Keep only its last builtin validator; every delivery owns fresh bytes.
const body = Buffer.from(this.#encodedBody, 'utf8');
if (!this.#lastEtag || this.#lastEtag.generator !== generator) {
this.#lastEtag = Object.freeze({ generator, value: generator(body) });
}
res.set('Content-Type', 'application/json; charset=utf-8');
res.set('ETag', this.#lastEtag.value);
res.send(body);
} else if (defaultJson) {
if (!res.get('Content-Type')) res.set('Content-Type', 'application/json');
res.send(this.#encodedBody);
} else {
@@ -33,8 +63,8 @@ export function PreparedJson<T>(value: T, encodedBody: string, cloneForDelivery?
return Object.freeze(new PreparedJsonValue(value, encodedBody, cloneForDelivery));
}
/** Fence delivery as well as cache lookup. Express computes/compares the body ETag
* only after both fresh authority reads succeed, including on conditional GETs. */
/** Fence delivery as well as cache lookup. Validator selection and Express's
* freshness comparison follow both authority reads, including conditional GETs. */
export async function publicJson(
res: Response,
readGeneration: () => Promise<number>,
@@ -50,7 +80,7 @@ export async function publicJson(
if (await readGeneration() !== generation) throw new Error('PUBLIC_VISIBILITY_CHANGED');
res.setHeader('Cache-Control', cacheControl);
if (payload instanceof PreparedJsonValue) {
// Express still owns UTF-8, length, ETag and HEAD/304 after both fences.
// Express still owns length, freshness and HEAD/304 after both fences.
payload.send(res);
} else {
res.json(payload);
+36
View File
@@ -1364,3 +1364,39 @@ qualification. Do not change workloads, timing or acceptance limits.
reviewed fixture repair; its test bytes match the validated worktree. Its
application implementation is unchanged. This component evidence does not
replace full-stack performance or recovery qualification.
## The prepared representation owns its reusable HTTP validator
- Hidden link: equal queued responses already share one immutable encoded body,
but ordinary Express delivery hashes that body again for every reader. The
native CPU profile attributes 174 ms to this ETag path.
- Fix: keep one last known built-in generator and validator inside the existing
opaque representation. Each delivery still owns fresh bytes. No mutable byte
cache, completed-response cache, global validator cache or copied hash
algorithm is introduced. Routes, SQL admission and their 4 ms bound stay with
their existing owners.
- Privacy authority remains independent: both fresh generation reads must pass
before selecting a validator or delivering a body. Express still handles
content length, conditional freshness and HEAD/304. Custom serializers,
application/header hooks and preset headers retain their existing path.
- Two earlier diagnostics remain rejected: an 8 ms admission delay and private
UTF-8 byte reuse did not show a consistent benefit. The ETag-only ABBA run
(`9f1f5a7d`) reduced aggregate CPU 6.7%, wall time 7.4% and median trial p95
7.5%; warm-only median p95 increased 7.1%. All 24 map trials met 100 ms.
- Broader private validation (`2c010548`) passed all 144 lookup trial rows and
all 9,600 reads over the unchanged 120-second, 80-RPS schedule. The largest
C8 p95 was 75.5 ms. All 27 HTTP compatibility checks and a bound full backend
typecheck passed. Independent adoption-readiness audit: `012ecfac`. A tiny
native scheduler rounding warning remains recorded with its passing actual
timing checks.
- This supports the exact reviewed implementation and normal repository
regression checks. The canonical 1x/10x matrices, full load/RF qualification
and restoration of original targets remain required; the original 115 ms
failure is retained.
- Normal repository validation passed: 1,067 unit checks, typecheck, the 75 API/
11 operator route contract, local alert firing/recovery and production build.
Fourteen pre-existing conditional unit skips retain their separate native or
optional dispositions (`41263fec`). Both existing real-PostgreSQL ordinary
and prepared privacy-fence tests then passed without skips (`87ed1abc`), with
their temporary databases and instance removed; independent audit `ac6ed9a8`.