| 5 |
| import fs from 'node:fs'; |
| 6 | import net from 'node:net'; |
| 7 | import path from 'node:path'; |
| 8 | import { fileURLToPath } from 'node:url'; |
| 9 | import zlib from 'node:zlib'; |
| 10 | import type { Page } from '@playwright/test'; |
| 11 | import { LOADS, STRICT_LIMITS, type LimitKey, type Load } from './loads'; |
| 12 |
| 13 | export const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..'); |
| 14 | export const STRESS = path.join(ROOT, 'packages', 'stress'); |
| 15 | export const WIDGETS = path.join(STRESS, 'widgets'); |
| 16 |
| 17 | /** A mini-widget (docs/tgw-format.md): the server refuses more than 4096 B after zlib at level 9; the kit keeps the conformance set's margin. */ |
| 18 | export const SIZE_LIMIT = { zlib: 3800, raw: 32_768 }; |
| 19 | /** Every widget fits a bubble: at most 560 px tall at 320 px wide (the conformance set's rule, under the 600 px cap). */ |
| 20 | export const MAX_HEIGHT = { width: 320, height: 560 }; |
| 21 | export const sizeOf = (html: string) => { const b = Buffer.from(html); return { raw: b.length, zlib: zlib.deflateSync(b, { level: 9 }).length }; }; |
| 22 |
| 23 | export interface ManifestWidget { |
| 24 | id: string; file: string; load: string; level: number; value: number; |
| 25 | /** Boxes on screen with a blurred shadow, filter, backdrop-filter or opacity < 1 (§3), and of those with backdrop-filter. */ |
| 26 | heavyBoxes: number; backdropBoxes: number; |
| 27 | /** Boxes that change every frame. */ |
| 28 | changedBoxes: number; |
| 29 | /** Rough counts of what the strict limits measure, and the limits this level crosses. */ |
| 30 | estimates: Partial<Record<LimitKey, number>>; |
| 31 | crosses: string[]; |
| 32 | /** Measured by build.ts through the sandbox (Chromium, shadow renderer, compat): nodes, the largest validated batch, height at 320 px. */ |
| 33 | measured?: { nodes: number; maxBatchOps: number; height: number }; |
| 34 | size: { raw: number; zlib: number }; |
| 35 | } |
| 36 | export interface Manifest { |
| 37 | version: 2; |
| 38 | limits: typeof STRICT_LIMITS; |
| 39 | run: { warmupMs: number; measureMs: number; width: number }; |
| 40 | loads: { id: string; title: string; stresses: string; param: string; unit: string; levels: number[]; fit: 'heavy' | 'plain' | null; widgets: string[] }[]; |
| 41 | widgets: ManifestWidget[]; |
| 42 | } |
| 43 | export const DEFAULT_RUN = { warmupMs: 2000, measureMs: 10_000, width: 390 }; |
| 44 |
| 45 | const pad = (n: number) => String(n).padStart(6, '0'); |
| 46 | export const widgetId = (load: Load, value: number) => `${load.id}/${value}`; |
| 47 | export const widgetFile = (load: Load, value: number) => `widgets/${load.id}/${pad(value)}.html`; |
| 48 |
| 49 | /** The measuring loop every widget carries: its own requestAnimationFrame rate, published as `data-stress` on <html>. */ |
| 50 | const HARNESS = `(function(){var de=document.documentElement,h=document.getElementById('h'),lb=h.textContent,n=0,t0=0,lt=0,lp=0,mx=0,j=0,fs=0,fc=0,fps=0; |
| 51 | function pub(st,t){de.setAttribute('data-stress',JSON.stringify({v:1,id:ID,level:LV,value:N,status:st,t:Math.round(t),frames:n,fps:fps,maxGap:Math.round(mx),jank:j}));mx=0} |
| 52 | function loop(t){if(!t0)t0=lt=lp=fs=t;var g=t-lt;lt=t;if(g>mx)mx=g;if(g>50)j++;n++;fc++;if(t-fs>=1000){fps=Math.round(fc*1000/(t-fs));fc=0;fs=t} |
| 53 | if(typeof step=='function')step(t-t0); |
| 54 | if(t-lp>=500){lp=t;h.firstChild.data=lb+' \\u00b7 '+fps+' fps';pub('running',t-t0)}requestAnimationFrame(loop)} |
| 55 | pub('setup',0);requestAnimationFrame(loop)})();`; |
| 56 |
| 57 | /** One level of one load as a widget. */ |
| 58 | export function widgetHtml(load: Load, level: number, value: number): string { |
| 59 | const label = `${load.title} · ${value} ${load.unit}`; |
| 60 | const meta = { id: widgetId(load, value), load: load.id, level, param: load.param, value, unit: load.unit }; |
| 61 | return `<!doctype html> |
| 62 | <html><head><meta charset="utf-8"><title>stress: ${label}</title> |
| 63 | <!-- stress ${JSON.stringify(meta)} --> |
| 64 | <style>body{margin:0;font:12px system-ui,sans-serif}#h{padding:5px 8px;color:var(--tg-theme-hint-color);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden}#f{position:relative;height:300px;overflow:hidden}${load.css}</style> |
| 65 | </head><body><div id="h">${label}</div><div id="f"></div> |
| 66 | <script> |
| 67 | var ID=${JSON.stringify(meta.id)},LV=${level},N=${value},F=document.getElementById('f'),W=F.clientWidth||300; |
| 68 | function mk(n,c){for(var a=[],i=0;i<n;i++){var d=document.createElement('div');d.className=c;F.appendChild(d);a.push(d)}return a} |
| 69 | ${load.setup}; |
| 70 | ${load.step ? `function step(t){${load.step}}\n` : ''}${HARNESS} |
| 71 | </script> |
| 72 | </body></html> |
| 73 | `; |
| 74 | } |
| 75 |
| 76 | /** The strict limits a level crosses: the table's estimates, with the nodes and the largest batch measured through the sandbox where the build has them. */ |
| 77 | export function crossesOf(w: Pick<ManifestWidget, 'estimates' | 'heavyBoxes' | 'backdropBoxes' | 'measured'>): string[] { |
| 78 | const all: Partial<Record<LimitKey, number>> = { ...w.estimates, heavyBoxes: w.heavyBoxes, backdropBoxes: w.backdropBoxes }; |
| 79 | // Measured through the sandbox: the shim hands a long flush over in parts (v0.6.0), so the largest batch is the measured one. |
| 80 | if (w.measured) { all.nodes = w.measured.nodes; all.opsPerBatch = w.measured.maxBatchOps; } |
| 81 | return (Object.keys(STRICT_LIMITS) as LimitKey[]).filter((k) => (all[k] ?? 0) > STRICT_LIMITS[k]).map((k) => `${k} ${all[k]} > ${STRICT_LIMITS[k]}`); |
| 82 | } |
| 83 |
| 84 | /** Every level of every load, with what the manifest says about it. */ |
| 85 | export function generate(): { widgets: (ManifestWidget & { html: string })[]; manifest: Omit<Manifest, 'widgets'> } { |
| 86 | const widgets: (ManifestWidget & { html: string })[] = []; |
| 87 | for (const load of LOADS) { |
| 88 | load.levels.forEach((value, level) => { |
| 89 | const html = widgetHtml(load, level, value); |
| 90 | const w = { id: widgetId(load, value), file: widgetFile(load, value), load: load.id, level, value, heavyBoxes: load.heavy?.(value) ?? 0, backdropBoxes: load.backdrop?.(value) ?? 0, changedBoxes: load.changed?.(value) ?? 0, estimates: load.est(value), crosses: [] as string[], size: sizeOf(html), html }; |
| 91 | w.crosses = crossesOf(w); |
| 92 | widgets.push(w); |
| 93 | }); |
| 94 | } |
| 95 | return { |
| 96 | widgets, |
| 97 | manifest: { |
| 98 | version: 2, limits: STRICT_LIMITS, run: DEFAULT_RUN, |
| 99 | loads: LOADS.map((l) => ({ id: l.id, title: l.title, stresses: l.stresses, param: l.param, unit: l.unit, levels: l.levels, fit: l.fit ?? null, widgets: l.levels.map((v) => widgetId(l, v)) })), |
| 100 | }, |
| 101 | }; |
| 102 | } |
| 103 |
| 104 | export function readManifest(): Manifest { |
| 105 | return JSON.parse(fs.readFileSync(path.join(STRESS, 'manifest.json'), 'utf8')); |
| 106 | } |
| 107 |
| 108 | /** The measuring configuration of CLIENTS.md as the dev app's URL parameters (unknown ones are ignored until the app reads them). */ |
| 109 | export const MEASURE_PARAMS = { policy: 'compat', cpuLimitMs: '500', cpuQuotaMs: '10000', cpuQuotaWindowMs: '1000', mainThreadQuotaMs: '10000', maxTimers: '256', memoryLimitBytes: String(64 * 1024 * 1024) }; |
| 110 |
| 111 | /** Runs `fn` on the dev app: `origin`, or a dev server started for it on a free port (stopped afterwards). */ |
| 112 | export async function withDevServer<T>(origin: string | undefined, fn: (origin: string) => Promise<T>): Promise<T> { |
| 113 | let server: ReturnType<typeof spawn> | undefined; |
| 114 | if (!origin) { |
| 115 | const port = await new Promise<number>((resolve) => { const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = (s.address() as net.AddressInfo).port; s.close(() => resolve(p)); }); }); |
| 116 | origin = `http://127.0.0.1:${port}`; |
| 117 | server = spawn('corepack', ['pnpm', 'dev', '--port', String(port)], { cwd: ROOT, stdio: 'ignore', detached: true }); |
| 118 | const t0 = Date.now(); |
| 119 | for (;;) { |
| 120 | try { if ((await fetch(origin)).ok) break; } catch {} |
| 121 | if (Date.now() - t0 > 90_000) { process.kill(-server.pid!); throw new Error(`the dev server did not start on ${origin}`); } |
| 122 | await new Promise((r) => setTimeout(r, 500)); |
| 123 | } |
| 124 | } |
| 125 | try { return await fn(origin); } |
| 126 | finally { if (server) process.kill(-server.pid!); } |
| 127 | } |
| 128 |
| 129 | /** Opens the dev app with `params` on `renderer` and waits for its harness API (`window.__tw`). */ |
| 130 | export async function openDevApp(page: Page, origin: string, renderer: string, params: Record<string, string>) { |
| 131 | const q = new URLSearchParams({ theme: 'light', features: 'webAnimations', ...params }); |
| 132 | if (renderer !== 'iframe') q.set(renderer, '1'); |
| 133 | await page.goto(`${origin}/?${q}`); |
| 134 | await page.waitForFunction(() => !!(window as any).__tw, null, { timeout: 60_000 }); |
| 135 | } |
| 136 |
| 137 | /** |
| 138 | * Loads a widget into the dev app at `width` and taps what any host can see: the validated ops (the last |
| 139 | * `data-stress` on the element the `el` op adopted as <html>, the ops per batch) and the renderer's size reports. |
| 140 | */ |
| 141 | export async function loadWidget(page: Page, html: string, name: string, width: number) { |
| 142 | await page.evaluate(({ html, name, width }) => { |
| 143 | const wrap = document.querySelector('#sandbox-wrap') as HTMLElement; |
| 144 | (wrap.closest('.chat') as HTMLElement).style.width = width + 'px'; |
| 145 | const bubble = wrap.closest('.bubble') as HTMLElement; |
| 146 | bubble.style.padding = '0'; |
| 147 | bubble.style.borderRadius = '0'; |
| 148 | bubble.style.boxShadow = 'none'; |
| 149 | const tw = (window as any).__tw; |
| 150 | const s: any = ((window as any).__stress = { html: null, attr: null, height: 0, batches: 0, ops: 0, maxBatch: 0, t0: performance.now(), loadedAt: 0 }); |
| 151 | tw.load(html, name); |
| 152 | const host = tw.host; |
| 153 | host.element.setAttribute('data-stress-el', ''); |
| 154 | const onRenderer = host.onRenderer; |
| 155 | host.onRenderer = function (msg: any) { |
| 156 | if (msg?.type === 'size' && Number.isFinite(msg.height)) s.height = msg.height; |
| 157 | return onRenderer.call(this, msg); |
| 158 | }; |
| 159 | const r = host.renderer; |
| 160 | const send = r.send.bind(r); |
| 161 | r.send = (m: any) => { |
| 162 | if (m?.type === 'ops') { |
| 163 | s.batches++; |
| 164 | s.ops += m.ops.length; |
| 165 | if (m.ops.length > s.maxBatch) s.maxBatch = m.ops.length; |
| 166 | for (const op of m.ops) { |
| 167 | if (op.op === 'el' && op.adopt === 'html') { |
| 168 | s.html = op.id; |
| 169 | for (const [n, v] of op.attrs) if (n === 'data-stress') s.attr = v; |
| 170 | } else if (op.op === 'attr' && op.id === s.html && op.name === 'data-stress') s.attr = op.value; |
| 171 | } |
| 172 | } |
| 173 | return send(m); |
| 174 | }; |
| 175 | }, { html, name, width }); |
| 176 | } |
| 177 |
| 178 | export interface Published { v: number; id: string; level: number; value: number; status: string; t: number; frames: number; fps: number; maxGap: number; jank: number } |
| 179 | export async function published(page: Page): Promise<Published | null> { |
| 180 | return page.evaluate(() => { const a = (window as any).__stress?.attr; try { return a ? JSON.parse(a) : null; } catch { return null; } }); |
| 181 | } |
| 182 |