Merge claude/performance-2026-12-36a376: fewer queries per render, no 'use client' on the /client barrels, budgets, the doctor's performance and growth groups
Conflicts kept both sides: the doctor status (twoFactorConfirm with growth and media), its key test, e2e:built (the 2FA enrolment spec and the performance budgets), the reference index (regenerated). Reference skill copies synced (iapl-performance added, iapl-audit and iapl-reference updated). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Lab measurements of one page in Chromium (Playwright + the DevTools protocol) — used by `pnpm perf:measure`
|
||||
* (scripts/perf-measure.mjs, numbers for docs/performance.md) and by the budget gate (e2e/performance.spec.ts).
|
||||
*
|
||||
* Profiles follow Lighthouse's defaults so the numbers compare with PageSpeed Insights' lab data:
|
||||
* - mobile: 412×823 at DPR 1.75, "Slow 4G" (150 ms RTT, 1.6 Mbit/s down, 750 kbit/s up), CPU 4× slower;
|
||||
* - desktop: 1350×940, 40 ms RTT, 10 Mbit/s, CPU 1×.
|
||||
* Every run is a fresh browser context (empty HTTP cache, no cookies): a first visit, the worst ordinary case.
|
||||
*
|
||||
* What is measured (all from the browser itself, web.dev/articles/vitals):
|
||||
* ttfb, fcp, lcp (+ the LCP element: tag, src, loading, fetchpriority), cls (session windows, as web-vitals does),
|
||||
* tbt (sum of long-task time over 50 ms between FCP and the end of the run: the lab stand-in for INP),
|
||||
* inp (the longest Event Timing entry of one scripted interaction: a click on the page's first visible button),
|
||||
* scriptMs (CDP Performance.ScriptDuration: parse, compile, run and hydrate), requests, bytes per type
|
||||
* (transfer size, compressed), renderBlocking (resource timing renderBlockingStatus), thirdParty (requests to
|
||||
* another origin before any consent is given). Next's link prefetches (`?_rsc=`, made when the browser is idle) are
|
||||
* counted apart (`prefetches`): they are not part of the page's load and come at a different moment each run.
|
||||
* Option `blockThirdParty` (the gate): requests to another origin are recorded, then aborted — a slow external host
|
||||
* cannot hold the page's load event, and the numbers are the site's own.
|
||||
*/
|
||||
import { chromium } from '@playwright/test'
|
||||
|
||||
export const PROFILES = {
|
||||
desktop: { cpu: 1, network: { downloadThroughput: (10 * 1024 * 1024) / 8, latency: 40, uploadThroughput: (10 * 1024 * 1024) / 8 }, viewport: { deviceScaleFactor: 1, height: 940, isMobile: false, width: 1350 } },
|
||||
mobile: { cpu: 4, network: { downloadThroughput: (1.6 * 1024 * 1024) / 8, latency: 150, uploadThroughput: (750 * 1024) / 8 }, viewport: { deviceScaleFactor: 1.75, hasTouch: true, height: 823, isMobile: true, width: 412 } },
|
||||
}
|
||||
|
||||
const OBSERVERS = `(() => {
|
||||
const v = (window.__perf = { cls: 0, events: [], lcp: null, longTasks: [] })
|
||||
let win = 0, winStart = 0, winLast = 0
|
||||
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
|
||||
const el = e.element
|
||||
v.lcp = { at: e.startTime, size: e.size, tag: el ? el.tagName.toLowerCase() : null, src: e.url || null,
|
||||
loading: el && el.getAttribute ? el.getAttribute('loading') : null,
|
||||
fetchpriority: el && el.getAttribute ? el.getAttribute('fetchpriority') : null }
|
||||
} }).observe({ buffered: true, type: 'largest-contentful-paint' })
|
||||
new PerformanceObserver((l) => { for (const e of l.getEntries()) {
|
||||
if (e.hadRecentInput) continue
|
||||
if (win && e.startTime - winLast < 1000 && e.startTime - winStart < 5000) { win += e.value } else { win = e.value; winStart = e.startTime }
|
||||
winLast = e.startTime
|
||||
v.cls = Math.max(v.cls, win)
|
||||
} }).observe({ buffered: true, type: 'layout-shift' })
|
||||
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.longTasks.push([e.startTime, e.duration]) }).observe({ buffered: true, type: 'longtask' })
|
||||
new PerformanceObserver((l) => { for (const e of l.getEntries()) v.events.push({ d: e.duration, n: e.name }) }).observe({ buffered: true, durationThreshold: 16, type: 'event' })
|
||||
})()`
|
||||
|
||||
/**
|
||||
* @typedef {{ bytes: { css: number, font: number, html: number, image: number, js: number, other: number }, cls: number,
|
||||
* fcp: null | number, inp: null | number, interaction: null | string, lcp: null | number,
|
||||
* lcpElement: null | { fetchpriority: null | string, loading: null | string, src: null | string, tag: null | string },
|
||||
* load: null | number, prefetches: number, profile: string, renderBlocking: string[], requests: number, runs?: number, scriptMs: null | number,
|
||||
* status: null | number, tbt: null | number, thirdParty: string[], ttfb: null | number, url: string }} PageMeasurement
|
||||
*/
|
||||
|
||||
const typeOf = (resourceType, mime = '') => {
|
||||
if (resourceType === 'Document') {return 'html'}
|
||||
if (resourceType === 'Script') {return 'js'}
|
||||
if (resourceType === 'Stylesheet') {return 'css'}
|
||||
if (resourceType === 'Font') {return 'font'}
|
||||
if (resourceType === 'Image' || mime.startsWith('image/')) {return 'image'}
|
||||
return 'other'
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import('@playwright/test').Browser} browser
|
||||
* @param {string} url
|
||||
* @param {'mobile'|'desktop'} profileName
|
||||
* @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options]
|
||||
* @returns {Promise<PageMeasurement>}
|
||||
*/
|
||||
export async function measurePage(browser, url, profileName, options = {}) {
|
||||
const profile = PROFILES[profileName]
|
||||
const context = await browser.newContext({ ...profile.viewport, viewport: { height: profile.viewport.height, width: profile.viewport.width } })
|
||||
const page = await context.newPage()
|
||||
const cdp = await context.newCDPSession(page)
|
||||
await cdp.send('Network.enable')
|
||||
await cdp.send('Network.setCacheDisabled', { cacheDisabled: true })
|
||||
await cdp.send('Network.emulateNetworkConditions', { offline: false, ...profile.network })
|
||||
await cdp.send('Emulation.setCPUThrottlingRate', { rate: profile.cpu })
|
||||
await cdp.send('Performance.enable')
|
||||
await page.addInitScript(OBSERVERS)
|
||||
|
||||
const origin = new URL(url).origin
|
||||
if (options.blockThirdParty) {await context.route((u) => u.origin !== origin, (route) => route.abort())}
|
||||
const requests = new Map()
|
||||
let prefetches = 0
|
||||
cdp.on('Network.requestWillBeSent', (e) => {
|
||||
if (e.request.url.startsWith('data:')) {return}
|
||||
if (/[?&]_rsc=/.test(e.request.url)) {prefetches++; return}
|
||||
requests.set(e.requestId, { bytes: 0, type: typeOf(e.type), url: e.request.url })
|
||||
})
|
||||
cdp.on('Network.responseReceived', (e) => { const r = requests.get(e.requestId); if (r) {r.type = typeOf(e.type, e.response.mimeType); r.status = e.response.status} })
|
||||
cdp.on('Network.loadingFinished', (e) => { const r = requests.get(e.requestId); if (r) {r.bytes = e.encodedDataLength} })
|
||||
|
||||
const response = await page.goto(url, { timeout: 60_000, waitUntil: 'load' })
|
||||
await page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => {})
|
||||
await page.waitForTimeout(options.settleMs ?? 1000)
|
||||
|
||||
let interaction = null
|
||||
if (options.interact !== false) {
|
||||
// INP stand-in: one click on the first visible button (menu toggle, cookie settings, theme): a real handler runs
|
||||
const button = page.locator('button:visible').first()
|
||||
if (await button.count()) {
|
||||
interaction = (await button.getAttribute('aria-label')) ?? (await button.innerText()).slice(0, 40)
|
||||
await button.click({ timeout: 5000 }).catch(() => { interaction = null })
|
||||
await page.waitForTimeout(500)
|
||||
}
|
||||
}
|
||||
|
||||
const nav = await page.evaluate(() => {
|
||||
const n = performance.getEntriesByType('navigation')[0]
|
||||
const fcp = performance.getEntriesByName('first-contentful-paint')[0]
|
||||
const blocking = performance.getEntriesByType('resource').filter((r) => r.renderBlockingStatus === 'blocking').map((r) => r.name)
|
||||
return { blocking, domContentLoaded: n.domContentLoadedEventEnd, fcp: fcp ? fcp.startTime : null, load: n.loadEventEnd, ttfb: n.responseStart }
|
||||
})
|
||||
const vitals = await page.evaluate(() => window.__perf)
|
||||
const { metrics } = await cdp.send('Performance.getMetrics')
|
||||
const metric = (name) => metrics.find((m) => m.name === name)?.value ?? 0
|
||||
await context.close()
|
||||
|
||||
const list = [...requests.values()]
|
||||
const bytes = { css: 0, font: 0, html: 0, image: 0, js: 0, other: 0 }
|
||||
for (const r of list) {bytes[r.type] += r.bytes}
|
||||
const fcp = nav.fcp ?? 0
|
||||
const tbt = vitals.longTasks.filter(([start]) => start >= fcp).reduce((sum, [, d]) => sum + Math.max(0, d - 50), 0)
|
||||
const round = (n) => (n == null ? null : Math.round(n))
|
||||
return {
|
||||
bytes: Object.fromEntries(Object.entries(bytes).map(([k, b]) => [k, Math.round(b)])),
|
||||
cls: Math.round(vitals.cls * 1000) / 1000,
|
||||
fcp: round(nav.fcp),
|
||||
inp: vitals.events.length ? round(Math.max(...vitals.events.map((e) => e.d))) : interaction ? 0 : null,
|
||||
interaction,
|
||||
lcp: round(vitals.lcp?.at),
|
||||
lcpElement: vitals.lcp ? { fetchpriority: vitals.lcp.fetchpriority, loading: vitals.lcp.loading, src: vitals.lcp.src ? vitals.lcp.src.replace(origin, '') : null, tag: vitals.lcp.tag } : null,
|
||||
load: round(nav.load),
|
||||
prefetches,
|
||||
profile: profileName,
|
||||
renderBlocking: nav.blocking.map((u) => u.replace(origin, '')),
|
||||
requests: list.length,
|
||||
scriptMs: round(metric('ScriptDuration') * 1000),
|
||||
status: response?.status() ?? null,
|
||||
tbt: round(tbt),
|
||||
thirdParty: [...new Set(list.filter((r) => !r.url.startsWith(origin)).map((r) => new URL(r.url).origin))],
|
||||
ttfb: round(nav.ttfb),
|
||||
url: url.replace(origin, ''),
|
||||
}
|
||||
}
|
||||
|
||||
export const median = (values) => {
|
||||
const sorted = values.filter((v) => typeof v === 'number').sort((a, b) => a - b)
|
||||
if (!sorted.length) {return null}
|
||||
const mid = Math.floor(sorted.length / 2)
|
||||
return sorted.length % 2 ? sorted[mid] : Math.round(((sorted[mid - 1] + sorted[mid]) / 2) * 1000) / 1000
|
||||
}
|
||||
|
||||
/**
|
||||
* The median of `runs` measurements for every number; the rest from the last run.
|
||||
* @param {import('@playwright/test').Browser} browser
|
||||
* @param {string} url
|
||||
* @param {'mobile'|'desktop'} profileName
|
||||
* @param {number} [runs]
|
||||
* @param {{ blockThirdParty?: boolean, interact?: boolean, settleMs?: number }} [options]
|
||||
* @returns {Promise<PageMeasurement>}
|
||||
*/
|
||||
export async function measureMedian(browser, url, profileName, runs = 3, options = {}) {
|
||||
const all = []
|
||||
for (let i = 0; i < runs; i++) {all.push(await measurePage(browser, url, profileName, options))}
|
||||
const last = all.at(-1)
|
||||
const out = { ...last, runs }
|
||||
for (const key of ['cls', 'fcp', 'inp', 'lcp', 'load', 'requests', 'scriptMs', 'tbt', 'ttfb']) {out[key] = median(all.map((r) => r[key]))}
|
||||
out.bytes = Object.fromEntries(Object.keys(last.bytes).map((k) => [k, median(all.map((r) => r.bytes[k]))]))
|
||||
return out
|
||||
}
|
||||
|
||||
export const launch = () => chromium.launch()
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { Browser } from '@playwright/test'
|
||||
|
||||
import { overBudget, perfBudgets, SERVER_BUDGET } from '@intecion/ipal-kit/doctor'
|
||||
import { chromium, expect, test } from '@playwright/test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import path from 'node:path'
|
||||
|
||||
// a plain ES module (JSDoc types), shared with scripts/perf-measure.mjs
|
||||
import { measureMedian } from './perf-lab.mjs'
|
||||
|
||||
/**
|
||||
* Performance budgets — a BINDING gate (docs/performance.md): every page type, a phone on Slow 4G with a 4× slower CPU
|
||||
* and a desktop, first visit. The numbers are this site's own, measured on 2026-12-01 (docs/dev/perf/*-after.json)
|
||||
* with headroom for lab noise: a change that makes a page heavier or slower fails here, in `pnpm e2e:built`, with both
|
||||
* bundlers. Loosen a number only with a reason in the comment next to it.
|
||||
* PERF_RUNS (default 1) runs per page; the gate takes the median. Third-party requests are recorded (none may come
|
||||
* before consent) and aborted, so an external host's speed cannot fail or hang the gate.
|
||||
*/
|
||||
const runs = Number(process.env.PERF_RUNS ?? 1)
|
||||
|
||||
const budgets = perfBudgets({
|
||||
// measured 1.18.0: JS 184–188 kB, CSS 11–12 kB, fonts 209.5 kB (Inter + Fraunces, latin + latin-ext — four
|
||||
// preloaded files: see "fonts" in docs/performance.md), LCP 0.8 s on the phone, 0.3 s on the desktop
|
||||
desktop: { cssBytes: 16_000, fontBytes: 215_000, jsBytes: 200_000, lcp: 800, renderBlocking: 1, requests: 36, tbt: 50 },
|
||||
mobile: { cssBytes: 16_000, fontBytes: 215_000, jsBytes: 200_000, lcp: 1500, renderBlocking: 1, requests: 30, tbt: 100 },
|
||||
})
|
||||
|
||||
/** One of each template (AGENTS.md → Site map), with what differs for that page. */
|
||||
type Budget = Partial<typeof budgets.mobile>
|
||||
const PAGES: Array<{ budget?: { desktop?: Budget; mobile?: Budget }; name: string; path: string; why?: string }> = [
|
||||
{ name: 'home', path: '/pl' },
|
||||
{ name: 'page', path: '/pl/o-nas' },
|
||||
{ name: 'archive', path: '/pl/blog' },
|
||||
{ name: 'post', path: '/pl/blog/zanim-kupisz-dzialke' },
|
||||
{ name: 'case study', path: '/pl/realizacje/dom-pod-lasem' },
|
||||
{ name: 'form', path: '/pl/wycena' },
|
||||
// every block × variant on one page, the contact form's Turnstile included (a necessary service, before consent)
|
||||
{ budget: { desktop: { jsBytes: 230_000, thirdParty: ['https://challenges.cloudflare.com'] }, mobile: { jsBytes: 230_000, thirdParty: ['https://challenges.cloudflare.com'] } }, name: 'showcase', path: '/pl/bloki' },
|
||||
// The 404 content loads after hydration (createNotFoundPage `load`, so it is not in every page's payload): it
|
||||
// arrives late and moves the footer — measured CLS 0.32 and LCP 2.5 s on the phone. An owner decision in
|
||||
// docs/performance.md; until then the gate holds it where it is (no worse).
|
||||
{ budget: { mobile: { cls: 0.35, lcp: 3000 } }, name: '404', path: '/pl/nie-ma-takiej-strony', why: 'lazy 404 (owner decision pending)' },
|
||||
]
|
||||
|
||||
let browser: Browser
|
||||
test.beforeAll(async () => {
|
||||
browser = await chromium.launch()
|
||||
})
|
||||
test.afterAll(async () => {
|
||||
await browser?.close()
|
||||
})
|
||||
|
||||
test.describe('performance budgets', () => {
|
||||
test.describe.configure({ timeout: 180_000 })
|
||||
for (const page of PAGES) {
|
||||
for (const profile of ['mobile', 'desktop'] as const) {
|
||||
test(`${page.name} (${profile}) stays within its budget`, async ({ baseURL }) => {
|
||||
const budget = { ...budgets[profile], ...page.budget?.[profile] }
|
||||
const measured = await measureMedian(browser, `${baseURL}${page.path}`, profile, runs, { blockThirdParty: true })
|
||||
test.info().annotations.push({ description: JSON.stringify({ bytes: measured.bytes, cls: measured.cls, inp: measured.inp, lcp: measured.lcp, requests: measured.requests, tbt: measured.tbt }), type: 'measured' })
|
||||
expect(overBudget(measured, budget), `${page.path} ${profile}${page.why ? ` (${page.why})` : ''}`).toEqual([])
|
||||
// the LCP image is never lazy (web.dev/articles/lcp-lazy-loading)
|
||||
if (measured.lcpElement?.tag === 'img') {expect(measured.lcpElement.loading, `${page.path}: the LCP image is lazy`).not.toBe('lazy')}
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Database queries for ONE render of a page outside the ISR cache (Next's own on-demand revalidation header), counted
|
||||
* by MongoDB's profiler. Measured 1.18.0: 19–27 per page (1.17.2: 30–43); each budget is that plus ~15 %. Skipped when the profiler cannot be
|
||||
* switched on (not MongoDB, or a user without the right).
|
||||
*/
|
||||
test.describe('queries per render', () => {
|
||||
const QUERY_BUDGET: Record<string, number> = { '/pl': 28, '/pl/bloki': 31, '/pl/blog/zanim-kupisz-dzialke': 30, '/pl/o-nas': 25, '/pl/wycena': 22 }
|
||||
test('every page type stays within its query budget', async ({ baseURL }) => {
|
||||
test.setTimeout(120_000)
|
||||
const uri = process.env.DATABASE_URI
|
||||
test.skip(!uri?.startsWith('mongodb'), 'not MongoDB')
|
||||
const site = process.cwd() // Playwright runs in reference/
|
||||
const requireFromAdapter = createRequire(createRequire(path.join(site, 'package.json')).resolve('@payloadcms/db-mongodb'))
|
||||
const mongoose = requireFromAdapter('mongoose') as typeof import('mongoose')
|
||||
const conn = await mongoose.createConnection(uri!).asPromise()
|
||||
const db = conn.db!
|
||||
try {
|
||||
try {
|
||||
await db.command({ profile: 0 })
|
||||
} catch {
|
||||
test.skip(true, 'the database user may not use the profiler')
|
||||
}
|
||||
const previewModeId = JSON.parse(readFileSync(path.join(site, '.next', 'prerender-manifest.json'), 'utf8')).preview?.previewModeId as string
|
||||
const counts: Record<string, number> = {}
|
||||
for (const [p, limit] of Object.entries(QUERY_BUDGET)) {
|
||||
await fetch(`${baseURL}${p}`, { headers: { 'x-prerender-revalidate': previewModeId } }) // warm: the first render compiles
|
||||
await db.command({ profile: 0 })
|
||||
await db.collection('system.profile').drop().catch(() => {})
|
||||
await db.command({ profile: 2 })
|
||||
const res = await fetch(`${baseURL}${p}`, { headers: { 'x-prerender-revalidate': previewModeId } })
|
||||
expect(res.status).toBe(200)
|
||||
await db.command({ profile: 0 })
|
||||
counts[p] = await db.collection('system.profile').countDocuments({ ns: { $not: /system\.profile$/ }, op: 'query' })
|
||||
expect(counts[p], `${p}: no query counted — the profiler did not record this database`).toBeGreaterThan(0)
|
||||
expect(counts[p], `${p}: ${counts[p]} queries (budget ${limit}, plugin default ${SERVER_BUDGET.queriesPerRender})`).toBeLessThanOrEqual(limit)
|
||||
}
|
||||
test.info().annotations.push({ description: JSON.stringify(counts), type: 'queries' })
|
||||
} finally {
|
||||
await db.command({ profile: 0 }).catch(() => {})
|
||||
await conn.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user