import { createHash } from 'node:crypto'; import { arch, cpus, platform, release } from 'node:os'; import { brotliCompressSync, constants, gzipSync, } from 'node:zlib'; const BENCHMARK_DATE = '2026-07-13'; const RUNS = 30; const GZIP_LEVEL = 6; const BROTLI_QUALITY = 5; function smallApiResponse() { return { request_id: 'req_01JEXAMPLE', generated_at: '2026-07-13T12:00:00.000Z', status: 'ok', pagination: { next_cursor: null, has_more: false }, data: [ { id: 'usr_001', name: 'Ada Rivera', role: 'owner', active: true, tags: ['api', 'production'] }, { id: 'usr_002', name: 'Lin Okafor', role: 'developer', active: true, tags: ['worker', 'staging'] }, { id: 'usr_003', name: 'Sam Ito', role: 'viewer', active: false, tags: ['audit'] }, ], }; } function mediumServiceCatalog() { const regions = ['us-east', 'us-west', 'eu-central', 'ap-southeast']; const tiers = ['starter', 'growth', 'business']; return { generated_at: '2026-07-13T12:00:00.000Z', catalog_version: 'fixture-1.0.0', services: Array.from({ length: 120 }, (_, index) => { const number = String(index + 1).padStart(3, '0'); return { id: `svc_${number}`, name: `Example Service ${number}`, region: regions[index % regions.length], tier: tiers[index % tiers.length], enabled: index % 11 !== 0, endpoint: `https://api.example.test/v1/services/${number}`, limits: { requests_per_minute: 600 + (index % 8) * 300, burst: 50 + (index % 5) * 25, concurrent_requests: 5 + (index % 6), }, labels: ['synthetic', `group-${index % 10}`, `region-${regions[index % regions.length]}`], description: 'Synthetic catalog record used to compare deterministic payload compression settings.', }; }), }; } function largeEventBatch() { const eventTypes = ['request.started', 'request.completed', 'request.failed', 'job.queued']; const regions = ['us-east', 'us-west', 'eu-central', 'ap-southeast']; const baseTime = Date.parse('2026-07-13T12:00:00.000Z'); return { batch_id: 'batch_fixture_001', schema_version: '1.0', events: Array.from({ length: 1200 }, (_, index) => { const number = String(index + 1).padStart(5, '0'); const eventType = eventTypes[index % eventTypes.length]; return { id: `evt_${number}`, occurred_at: new Date(baseTime + index * 1000).toISOString(), type: eventType, source: `worker-${(index % 24) + 1}`, region: regions[index % regions.length], duration_ms: 20 + (index * 37) % 1800, success: eventType !== 'request.failed', attempt: 1 + (index % 3), request: { method: index % 5 === 0 ? 'POST' : 'GET', route: `/v1/resources/${index % 150}`, status: eventType === 'request.failed' ? 503 : 200, }, tags: ['synthetic', `shard-${index % 12}`, `tenant-${index % 40}`], message: `Synthetic event ${number} for deterministic compression comparison.`, }; }), }; } const fixtures = [ { id: 'small-api-response', label: 'Small API response', records: 3, value: smallApiResponse() }, { id: 'medium-service-catalog', label: 'Medium service catalog', records: 120, value: mediumServiceCatalog() }, { id: 'large-event-batch', label: 'Large event batch', records: 1200, value: largeEventBatch() }, ]; function median(values) { const sorted = [...values].sort((left, right) => left - right); const middle = Math.floor(sorted.length / 2); return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle]; } function encodedSizes(source, encoder) { const sizes = Array.from({ length: RUNS }, () => encoder(source).byteLength); if (!sizes.every((size) => size === sizes[0])) { throw new Error('Compressed output size changed across identical runs.'); } return sizes; } function resultFor(fixture) { const source = Buffer.from(JSON.stringify(fixture.value), 'utf8'); const identity = Array.from({ length: RUNS }, () => source.byteLength); const gzip = encodedSizes(source, (input) => gzipSync(input, { level: GZIP_LEVEL, mtime: 0 })); const brotli = encodedSizes(source, (input) => brotliCompressSync(input, { params: { [constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_TEXT, [constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY, }, })); const originalBytes = median(identity); const encodingResult = (name, values) => { const medianBytes = median(values); return { encoding: name, median_bytes: medianBytes, reduction_percent: Number(((1 - medianBytes / originalBytes) * 100).toFixed(2)), }; }; return { id: fixture.id, label: fixture.label, records: fixture.records, sha256: createHash('sha256').update(source).digest('hex'), encodings: [ encodingResult('identity', identity), encodingResult('gzip', gzip), encodingResult('br', brotli), ], }; } const cpu = cpus()[0]?.model ?? 'Unknown'; const report = { benchmark: 'payload-compression', benchmark_version: '1.0.0', benchmark_date: BENCHMARK_DATE, method: { runs_per_fixture_and_encoding: RUNS, source_serialization: 'JSON.stringify with UTF-8 encoding and no added whitespace', gzip_level: GZIP_LEVEL, brotli_quality: BROTLI_QUALITY, brotli_mode: 'text', result_statistic: 'median encoded byte length', }, environment: { node: process.version, zlib: process.versions.zlib, brotli: process.versions.brotli, operating_system: `${platform()} ${release()} ${arch()}`, cpu, logical_cpus: cpus().length, }, fixtures: fixtures.map(resultFor), }; process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);