Files
cad-world/frontend/tests/performance/benchmark.mjs
T
2026-09-24 17:20:27 +08:00

135 lines
9.9 KiB
JavaScript

import assert from 'node:assert/strict';
import { promises as fs } from 'node:fs';
import { createHash } from 'node:crypto';
import path from 'node:path';
import os from 'node:os';
import { chromium } from 'playwright';
import { frontend } from './snapshot-dist.mjs';
import { serveProduction } from './production-server.mjs';
import { geometryBenchmark } from './geometry-benchmark.mjs';
const options = process.argv.slice(2);
function option(name, fallback) {
const index = options.indexOf(name);
return index === -1 ? fallback : options[index + 1];
}
const manifestPath = path.resolve(option('--manifest', path.join(frontend, 'tests/performance/baseline-dist.json')));
const output = path.resolve(option('--out', path.join(frontend, 'tests/performance/baseline-run.json')));
assert.equal(path.dirname(output), path.join(frontend, 'tests/performance'), 'Reports must stay in tests/performance');
try { await fs.access(output); throw new Error(`Refusing to overwrite ${output}`); } catch (error) { if (error.code !== 'ENOENT') throw error; }
const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
const startedAt = new Date().toISOString();
const dependencyVersions = {};
for (const dependency of ['three', 'three-mesh-bvh', 'playwright']) {
dependencyVersions[dependency] = JSON.parse(await fs.readFile(path.join(frontend, 'node_modules', dependency, 'package.json'), 'utf8')).version;
}
const localDiscovery = [];
for (const url of ['http://127.0.0.1:8081/', 'http://127.0.0.1:8082/api/projects', 'http://127.0.0.1:8082/api/robot/conversations']) {
try {
const response = await fetch(url, { method: 'GET', redirect: 'manual', signal: AbortSignal.timeout(5000) });
localDiscovery.push({ url, status: response.status, bodyBytes: (await response.arrayBuffer()).byteLength });
} catch (error) { localDiscovery.push({ url, error: error.cause?.code || error.name }); }
}
const projectDirectories = (await fs.readdir(path.join(frontend, '../backend/data/projects'), { withFileTypes: true }).catch(() => []))
.filter(entry => entry.isDirectory()).length;
const server = await serveProduction(manifest);
let browser;
const navigations = [];
let browserVersion;
try {
// A local denying proxy preserves the HTTP cache (Playwright routing disables
// it) while preventing all external access, including hardcoded asset hosts.
browser = await chromium.launch({ headless: true, args: [`--proxy-server=${server.origin}`, '--proxy-bypass-list=<-loopback>', '--disable-background-networking'] });
browserVersion = browser.version();
for (let pair = 0; pair < 3; pair++) {
const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1,
serviceWorkers: 'block' });
try {
for (const temperature of ['cold', 'warm']) {
const page = await context.newPage();
const cdp = await context.newCDPSession(page);
await cdp.send('Network.enable');
await cdp.send('Network.setCacheDisabled', { cacheDisabled: false });
const network = new Map();
const errors = [];
page.on('pageerror', error => errors.push(error.message.slice(0, 500)));
cdp.on('Network.requestWillBeSent', event => {
const url = new URL(event.request.url);
network.set(event.requestId, { path: url.origin === server.origin ? url.pathname : '[external blocked]', type: event.type });
});
cdp.on('Network.requestServedFromCache', event => { const row = network.get(event.requestId); if (row) row.servedFromCache = true; });
cdp.on('Network.responseReceived', event => {
const row = network.get(event.requestId);
if (row) Object.assign(row, { status: event.response.status, fromDiskCache: event.response.fromDiskCache || false,
fromServiceWorker: event.response.fromServiceWorker || false });
});
cdp.on('Network.loadingFinished', event => {
const row = network.get(event.requestId); if (row) row.encodedDataLength = event.encodedDataLength;
});
cdp.on('Network.loadingFailed', event => { const row = network.get(event.requestId); if (row) row.failure = event.errorText; });
const requestStart = server.requests.length;
await page.goto(`${server.origin}/assemble`, { waitUntil: 'networkidle', timeout: 45000 });
// Fixed additional observation window catches startup work after load;
// requests later than this are explicitly outside the measurement.
await page.waitForTimeout(1500);
const measurements = await page.evaluate(() => {
const navigation = performance.getEntriesByType('navigation')[0];
return { finalPath: location.pathname, title: document.title,
navigation: navigation.toJSON(), paints: performance.getEntriesByType('paint').map(entry => entry.toJSON()),
resources: performance.getEntriesByType('resource').map(entry => ({ path: new URL(entry.name).pathname,
initiatorType: entry.initiatorType, duration: entry.duration, transferSize: entry.transferSize,
encodedBodySize: entry.encodedBodySize, decodedBodySize: entry.decodedBodySize })),
canvas: [...document.querySelectorAll('canvas')].map(canvas => ({ width: canvas.width, height: canvas.height,
rendererBackend: canvas.dataset.rendererBackend ?? null, autoPerformanceLevel: canvas.dataset.autoPerformanceLevel ?? null })),
userAgent: navigator.userAgent };
});
assert.equal(measurements.finalPath, '/auth', 'No authenticated production session is supplied; unexpected route needs investigation');
const requests = server.requests.slice(requestStart);
assert(!requests.some(request => request.error), 'Frozen dist integrity/read error');
const rows = [...network.values()];
navigations.push({ pair, temperature, ...measurements, errors, network: rows, serverRequests: requests,
serverBodyBytes: requests.reduce((sum, request) => sum + request.bodyBytes, 0),
cdpEncodedDataLength: rows.reduce((sum, row) => sum + (row.encodedDataLength || 0), 0),
cacheHits: rows.filter(row => row.servedFromCache || row.fromDiskCache).length });
process.stdout.write(`${temperature} pair=${pair} route=${measurements.finalPath} bodyBytes=${navigations.at(-1).serverBodyBytes} cacheHits=${navigations.at(-1).cacheHits}\n`);
await page.close();
}
} finally { await context.close(); }
}
} finally {
if (browser) await browser.close();
await server.close();
}
process.stdout.write('Running bounded geometry/BVH CPU benchmark...\n');
const microbenchmark = geometryBenchmark();
const harnessFiles = ['benchmark.mjs', 'geometry-benchmark.mjs', 'production-server.mjs', 'snapshot-dist.mjs'];
const harnessSha256 = {};
for (const name of harnessFiles) harnessSha256[name] = createHash('sha256').update(await fs.readFile(path.join(frontend, 'tests/performance', name))).digest('hex');
const report = { schemaVersion: 1, startedAt, completedAt: new Date().toISOString(),
command: `node tests/performance/benchmark.mjs --manifest ${path.relative(frontend, manifestPath)} --out ${path.relative(frontend, output)}`,
environment: { node: process.version, platform: process.platform, arch: process.arch, osRelease: os.release(),
cpu: os.cpus()[0]?.model, logicalCpuCount: os.cpus().length, memoryBytes: os.totalmem(), browserVersion,
headless: true, viewport: { width: 1440, height: 900, deviceScaleFactor: 1 }, dependencyVersions },
harnessSha256, baseline: { manifestPath, capturedAt: manifest.capturedAt, sha256: manifest.sha256,
fileCount: manifest.fileCount, totalBytes: manifest.totalBytes },
discovery: { localDiscovery, projectDirectories, inspectedFixtures: ['tests/e2e/assembly/smoke.e2e.spec.ts', 'tests/e2e/fixtures/motion-preview-rfs.ts'],
auth: 'No secrets, browser profiles, stored tokens, or credentials read. Fresh Playwright contexts have no auth.',
assembly: 'Unavailable: unauthenticated production /assemble redirects to /auth. Backend list endpoints require authentication; fixtures use fake auth and synthetic geometry.',
recordsCreated: 0 },
productionPage: { serverPolicy: 'Loopback ephemeral port; unchanged frozen dist, uncompressed bodies, ETag HTML revalidation, immutable asset cache. Outbound proxy denies all external origins and writes.',
cacheProtocol: 'Three isolated browser contexts; cold first navigation and warm navigation in a second page in the same context. No Playwright route interception. Service workers blocked.',
window: 'networkidle (500ms) plus 1500ms; page navigation timeout 45s',
sizeDefinitions: { serverBodyBytes: 'Exact bytes served by local static server; excludes HTTP headers.',
cdpEncodedDataLength: 'Chromium CDP reported received encoded bytes; cached requests can report 0. Not packet capture.',
resourceTiming: 'Browser Resource Timing transferSize includes estimated HTTP overhead; encodedBodySize counts cached bodies too.' },
blockedExternal: server.blockedExternal, navigations }, microbenchmark,
limitations: ['Production-page numbers describe the unauthenticated redirect/login startup, not assembly readiness or rendering.',
'Cold means an empty browser HTTP cache, not cold OS/filesystem cache or first machine startup.',
'Loopback uncompressed serving is not deployed CDN, Brotli, WAN latency, or a mobile device.',
'No mobile device, real GPU FPS, GPU timestamp, application memory plateau, or real assembly measurement was performed.',
'Canvas rendererBackend/autoPerformanceLevel are observed only if present; missing values are not inferred.',
'No application build was run: this preserves the prechanges dist while another agent owns the production changes.',
'Local project directories are present but were not loaded by bypassing authentication; no backend writes or external requests were forwarded.'] };
await fs.writeFile(output, JSON.stringify(report, null, 2) + '\n', { flag: 'wx' });
process.stdout.write(`Report: ${output}\n`);