#!/usr/bin/env node /** * pnpm perf:measure — measures the BUILT reference site (reference/) and writes the numbers to a JSON file. * The method behind docs/performance.md → "How the plugin is measured"; repeat it after a change and compare. * * Before: reference/.env filled (local seeded MongoDB, ALLOW_LOCAL_MEDIA=1), the plugin built, `pnpm build` in * reference/ (webpack; `pnpm exec next build --turbopack` for Turbopack). The script starts `next start` itself. * * node scripts/perf-measure.mjs --label=webpack-before [--runs=3] [--port=3370] [--out=file.json] [--no-server] * * Server side: cold start (spawn → /api/health answers, → first page), memory (RSS of the server after the run), * TTFB of a cached (ISR) page over 20 requests, and the cost of RENDERING each page once: the request carries * Next's `x-prerender-revalidate` header (the on-demand revalidation Next uses itself), so the page is rendered * now and not served from the ISR cache; MongoDB's profiler (level 2, the database in DATABASE_URI) counts every * query that render made and their time. The profiler is switched off again at the end. * Client side: e2e/perf-lab.mjs (Lighthouse's mobile and desktop profiles), the median of --runs runs per page. */ import { execFileSync, spawn } from 'node:child_process' import { readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { launch, measureMedian } from '../reference/e2e/perf-lab.mjs' const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') const site = path.join(root, 'reference') const arg = (name, fallback) => process.argv.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback const label = arg('label', 'run') const runs = Number(arg('runs', 3)) const env = Object.fromEntries(readFileSync(path.join(site, '.env'), 'utf8').split('\n').filter((l) => /^[A-Z0-9_]+=/.test(l)).map((l) => [l.slice(0, l.indexOf('=')), l.slice(l.indexOf('=') + 1)])) const port = Number(arg('port', new URL(env.NEXT_PUBLIC_SERVER_URL ?? 'http://localhost:3370').port || 3370)) const base = `http://localhost:${port}` const out = arg('out', path.join(root, 'docs', 'dev', 'perf', `${label}.json`)) /** The page types measured: one of each template the reference site has (AGENTS.md → Site map). */ export const PAGES = { home: '/pl', page: '/pl/o-nas', archive: '/pl/blog', post: '/pl/blog/zanim-kupisz-dzialke', caseStudy: '/pl/realizacje/dom-pod-lasem', form: '/pl/wycena', showcase: '/pl/bloki', notFound: '/pl/nie-ma-takiej-strony', } // --- MongoDB profiler (through the mongo container's shell when DATABASE_URI is local; else skipped) --- const dbUri = process.env.DATABASE_URI ?? env.DATABASE_URI const dbName = new URL(dbUri).pathname.slice(1) const container = arg('mongo-container', process.env.PERF_MONGO_CONTAINER ?? '') const mongo = (js) => { if (!container) {return null} return execFileSync('docker', ['exec', container, 'mongosh', '--quiet', dbName, '--eval', js], { encoding: 'utf8' }).trim() } const profileOn = () => mongo('db.setProfilingLevel(0); db.system.profile.drop(); db.setProfilingLevel(2); "ok"') const profileOff = () => mongo('db.setProfilingLevel(0); "ok"') const profileRead = () => { const raw = mongo(`JSON.stringify(db.system.profile.find({ ns: { $not: /system\\.profile$/ }, op: { $in: ['query','command','getmore','insert','update','remove'] } }, { millis: 1, ns: 1, op: 1, 'command.find': 1, 'command.aggregate': 1, 'command.count': 1 }).toArray())`) if (raw == null) {return null} const rows = JSON.parse(raw).filter((r) => !r.command || r.command.find || r.command.aggregate || r.command.count || r.op !== 'command') mongo('db.setProfilingLevel(0); db.system.profile.drop(); db.setProfilingLevel(2); "ok"') const byCollection = {} for (const r of rows) {const c = r.ns.split('.').slice(1).join('.'); byCollection[c] = (byCollection[c] ?? 0) + 1} return { byCollection, count: rows.length, ms: rows.reduce((s, r) => s + (r.millis ?? 0), 0) } } const waitFor = async (url, timeoutMs = 60000) => { const start = Date.now() while (Date.now() - start < timeoutMs) { try { if ((await fetch(url)).ok) {return Date.now() - start} } catch {} await new Promise((r) => setTimeout(r, 100)) } throw new Error(`${url} did not answer in ${timeoutMs} ms`) } const timed = async (url, init) => { const t = performance.now() const res = await fetch(url, { redirect: 'manual', ...init }) await res.arrayBuffer() return { ms: performance.now() - t, res } } const pct = (values, p) => { const s = [...values].sort((a, b) => a - b) return Math.round(s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))] * 10) / 10 } const rssOf = (pid) => { // the server is `node … next start` under pnpm: sum the process tree's RSS (KiB → MiB) const tree = execFileSync('ps', ['-A', '-o', 'pid=,ppid=,rss='], { encoding: 'utf8' }).trim().split('\n').map((l) => l.trim().split(/\s+/).map(Number)) const ids = new Set([pid]) for (let changed = true; changed;) { changed = false for (const [p, pp] of tree) {if (ids.has(pp) && !ids.has(p)) {ids.add(p); changed = true}} } return Math.round(tree.filter(([p]) => ids.has(p)).reduce((s, [, , rss]) => s + rss, 0) / 1024) } const result = { client: {}, date: new Date().toISOString(), label, method: 'scripts/perf-measure.mjs + reference/e2e/perf-lab.mjs', runs, server: {} } let server = null if (!process.argv.includes('--no-server')) { // another server on the port would be measured instead of this build (and a stale .next answers 404 for assets) if (await fetch(`${base}/api/health`).then(() => true, () => false)) { console.error(`[perf] ${base} already answers: stop that server first (lsof -ti tcp:${port} | xargs kill) or pass --no-server`) process.exit(2) } const t0 = Date.now() server = spawn('pnpm', ['start'], { cwd: site, env: { ...process.env, PORT: String(port) }, detached: true, stdio: ['ignore', 'ignore', 'inherit'] }) result.server.coldStartHealthMs = await waitFor(`${base}/api/health`) const first = await timed(`${base}${PAGES.home}`) result.server.coldStartFirstPageMs = Date.now() - t0 result.server.firstPageMs = Math.round(first.ms) } try { // TTFB of a cached page and of the dynamic routes the plugin serves for (const [name, p] of Object.entries({ home: PAGES.home, md: '/md/pl', sitemap: '/sitemap.xml', llms: '/llms.txt' })) { await timed(`${base}${p}`) const times = [] for (let i = 0; i < 20; i++) {times.push((await timed(`${base}${p}`)).ms)} result.server[`ttfb_${name}`] = { median: pct(times, 50), p95: pct(times, 95) } } // the cost of one render of each page (ISR bypassed), with the queries it made const manifest = JSON.parse(readFileSync(path.join(site, '.next', 'prerender-manifest.json'), 'utf8')) const previewModeId = manifest.preview?.previewModeId result.server.render = {} if (profileOn() == null) {result.server.queriesNote = 'no --mongo-container: query counts not measured'} for (const [name, p] of Object.entries(PAGES)) { profileRead() const renders = [] for (let i = 0; i < 3; i++) {renders.push((await timed(`${base}${p}`, { headers: previewModeId ? { 'x-prerender-revalidate': previewModeId } : {} })).ms)} const q = profileRead() result.server.render[name] = { medianMs: pct(renders, 50), queries: q ? Math.round(q.count / 3) : null, queryMs: q ? Math.round(q.ms / 3) : null, byCollection: q?.byCollection } } for (const [name, p] of Object.entries({ md: '/md/pl', sitemap: '/sitemap.xml', llms: '/llms.txt', llmsFull: '/llms-full.txt' })) { profileRead() const { ms } = await timed(`${base}${p}`) const q = profileRead() result.server.render[name] = { medianMs: Math.round(ms), queries: q?.count ?? null, queryMs: q?.ms ?? null, byCollection: q?.byCollection } } profileOff() const browser = await launch() for (const profile of ['mobile', 'desktop']) { result.client[profile] = {} for (const [name, p] of Object.entries(PAGES)) { result.client[profile][name] = await measureMedian(browser, `${base}${p}`, profile, runs) const r = result.client[profile][name] console.log(`[perf] ${profile.padEnd(7)} ${name.padEnd(9)} LCP ${r.lcp} CLS ${r.cls} TBT ${r.tbt} INP ${r.inp} JS ${r.bytes.js} CSS ${r.bytes.css} req ${r.requests}`) } } result.client.admin = await measureMedian(browser, `${base}/admin/login`, 'desktop', runs, { interact: false }) await browser.close() if (server) {result.server.rssMiB = rssOf(server.pid)} } finally { profileOff() if (server) { try { process.kill(-server.pid, 'SIGTERM') } catch {} // the whole process group: pnpm and next start } } writeFileSync(out, `${JSON.stringify(result, null, 2)}\n`) console.log(`[perf] written ${path.relative(root, out)}`) console.log(JSON.stringify(result.server, null, 1)) process.exit(0)