| 6 | // --pool N: host mode also with a pool of N warmed sandbox workers (prewarmed before the clock, refilled as taken). |
| 7 | // Needs the dev server (corepack pnpm dev) on 127.0.0.1:5173. |
| 8 |
| 9 | import { chromium } from '@playwright/test'; |
| 10 | import fs from 'node:fs'; |
| 11 | import path from 'node:path'; |
| 12 | import { fileURLToPath } from 'node:url'; |
| 13 | import { runWidget } from '@telegram/widget-sandbox/node'; |
| 14 |
| 15 | const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); |
| 16 | const argv = process.argv.slice(2); |
| 17 | const opt = (name: string, def: string) => { const i = argv.indexOf(name); return i >= 0 && argv[i + 1] ? argv[i + 1] : def; }; |
| 18 | const counts = opt('--counts', '50,200').split(',').map(Number); |
| 19 | const modes = opt('--mode', 'ops').split(','); |
| 20 | const cvs = argv.includes('--cv') ? [false, true] : [false]; |
| 21 | const pools = [0, ...opt('--pool', '').split(',').filter(Boolean).map(Number)]; |
| 22 | const out = opt('--out', ''); |
| 23 | const origin = opt('--origin', 'http://127.0.0.1:5173'); |
| 24 | const WIDGETS = [ |
| 25 | 'generated/with-profile/01-show-me-a-mortgage-calculator-loan-amount', |
| 26 | 'generated/with-profile/06-show-a-comparison-table-of-three-laptops', |
| 27 | 'generated/with-profile/11-make-a-to-do-list-widget-where-i-can-add', |
| 28 | 'generated/with-profile/19-make-a-step-by-step-recipe-card-for', |
| 29 | 'generated/without-profile/02-make-an-interactive-quiz-about-the-solar', |
| 30 | ]; |
| 31 |
| 32 | const opsDir = path.join(root, 'bench', 'ops'); |
| 33 | fs.mkdirSync(opsDir, { recursive: true }); |
| 34 | // One ops file per widget and renderer: the validator scopes CSS differently for the shadow renderer. |
| 35 | for (const w of WIDGETS) for (const scope of ['document', 'shadow'] as const) { |
| 36 | const file = path.join(opsDir, w.replace(/\//g, '__') + (scope === 'shadow' ? '.shadow' : '') + '.json'); |
| 37 | if (fs.existsSync(file)) continue; |
| 38 | const r = await runWidget(fs.readFileSync(path.join(root, 'corpus', w + '.html'), 'utf8'), { verbose: false, probes: [], cssScope: scope }); |
| 39 | fs.writeFileSync(file, JSON.stringify([{ type: 'ops', ops: r.renderOps }])); |
| 40 | console.error(`ops: ${w} (${scope}) → ${r.renderOps.length} ops`); |
| 41 | } |
| 42 |
| 43 | const browser = await chromium.launch(); |
| 44 | const rows: any[] = []; |
| 45 | for (const mode of modes) for (const count of counts) for (const cv of cvs) for (const pool of mode === 'host' ? pools : [0]) for (const renderer of ['iframe', 'shadow']) { |
| 46 | const page = await browser.newPage({ viewport: { width: 900, height: 900 } }); |
| 47 | const url = `${origin}/bench/feed.html?renderer=${renderer}&mode=${mode}&count=${count}${cv ? '&cv=1' : ''}${pool ? `&pool=${pool}` : ''}`; |
| 48 | await page.goto(url); |
| 49 | await page.waitForFunction(() => typeof (window as any).__feed?.start === 'function'); |
| 50 | // Chromium's own counters for the whole page (frames included): JS heap, documents, DOM nodes, layout / style time. |
| 51 | const cdp = await page.context().newCDPSession(page); |
| 52 | await cdp.send('Performance.enable'); |
| 53 | const metrics = async () => Object.fromEntries(((await cdp.send('Performance.getMetrics')).metrics as { name: string; value: number }[]).map((m) => [m.name, m.value])); |
| 54 | const before = await metrics(); |
| 55 | await page.evaluate(() => (window as any).__feed.start()); |
| 56 | await page.waitForFunction(() => (window as any).__feed?.done, null, { timeout: 600_000 }); |
| 57 | const after = await metrics(); |
| 58 | const r = await page.evaluate(() => (window as any).__feed); |
| 59 | if (r.error) { console.error(`${renderer} ${mode} ${count}: ${r.error}`); await page.close(); continue; } |
| 60 | const d = (k: string) => (after[k] ?? 0) - (before[k] ?? 0); |
| 61 | const x = { ...r.result, jsHeap: d('JSHeapUsedSize'), documents: d('Documents'), frames: d('Frames'), nodes: d('Nodes'), layoutMs: d('LayoutDuration') * 1000, styleMs: d('RecalcStyleDuration') * 1000, taskMs: d('TaskDuration') * 1000 }; |
| 62 | rows.push(x); |
| 63 | console.log(`${renderer.padEnd(7)} ${mode.padEnd(5)} ${String(count).padStart(4)}${cv ? ' cv' : ' '}${pool ? ` pool ${String(pool).padStart(2)} (prewarm ${x.prewarmMs.toFixed(0)} ms, hits ${x.poolStats.hits}/${count})` : ''.padEnd(0)} build ${x.build.toFixed(0).padStart(5)} ms ready ${x.ready.toFixed(0).padStart(6)} ms painted ${x.painted.toFixed(0).padStart(6)} ms ${x.perBubble.toFixed(1).padStart(6)} ms/bubble long ${String(x.longTasks.count).padStart(3)} (${x.longTasks.total.toFixed(0).padStart(5)} ms) heap +${(x.jsHeap / 1048576).toFixed(1)} MB docs +${x.documents} frames +${x.frames} nodes +${x.nodes} layout ${x.layoutMs.toFixed(0)} ms style ${x.styleMs.toFixed(0)} ms task ${x.taskMs.toFixed(0)} ms scroll avg ${x.scroll.avg.toFixed(1)} p95 ${x.scroll.p95.toFixed(1)} slow ${x.scroll.slow}/${x.scroll.frames} height ${x.feedHeight}`); |
| 64 | await page.close(); |
| 65 | } |
| 66 | await browser.close(); |
| 67 |
| 68 | if (out && rows.length) { |
| 69 | const mb = (b: number | null) => (b === null ? 'n/a' : (b / 1048576).toFixed(1)); |
| 70 | const lines = [ |
| 71 | '# Feed bench — iframe vs Shadow DOM renderer on the web', '', |
| 72 | `Generated ${new Date().toISOString()} by \`corepack pnpm tsx scripts/feed-bench.ts --counts ${counts.join(',')} --mode ${modes.join(',')}${cvs.length > 1 ? ' --cv' : ''}\` (headless Chromium ${browser.version()}, dev server, 900×900). ` + |
| 73 | 'ops = renderer only, replaying the validated ops of five generated widgets (bench/ops/, Node harness) round-robin; host = a WidgetHost per bubble (QuickJS worker + validator + renderer), four booting at a time. ' + |
| 74 | 'build = creating the renderers and sending the ops (main thread, synchronous); ready = every bubble applied its ops; painted = the frame after that; ' + |
| 75 | 'long tasks = main-thread tasks over 50 ms until painted; heap / documents / frames / nodes / layout / style / task = Chromium `Performance.getMetrics` deltas for the whole page, iframes included (JS heap of the renderer process, documents and frames created, DOM nodes, time in layout, style recalc and all tasks); ' + |
| 76 | 'scroll = 60 scroll steps through the feed, frame intervals. Bubble heights are clamped to 24–900 px like in WidgetHost. ' + |
| 77 | 'Pool = host mode with a WorkerPool of that many warmed sandbox workers (QuickJS + bundle evaluated), prewarmed before the clock starts and refilled as taken; hits = bubbles that got a warm worker.', '', |
| 78 | '| Renderer | Mode | Bubbles | CV | Pool (prewarm ms, hits) | Build ms | Ready ms | Painted ms | ms / bubble | Long tasks | JS heap MB | Documents | Frames | Nodes | Layout ms | Style ms | Task ms | Scroll avg / p95 ms | Slow frames | Feed height |', |
| 79 | '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|', |
| 80 | ]; |
| 81 | for (const x of rows) lines.push(`| ${x.renderer} | ${x.mode} | ${x.count} | ${x.cv ? 'yes' : ''} | ${x.pool ? `${x.pool} (${x.prewarmMs.toFixed(0)} ms, ${x.poolStats.hits}/${x.count})` : ''} | ${x.build.toFixed(0)} | ${x.ready.toFixed(0)} | ${x.painted.toFixed(0)} | ${x.perBubble.toFixed(1)} | ${x.longTasks.count} (${x.longTasks.total.toFixed(0)} ms) | ${mb(x.jsHeap)} | ${x.documents} | ${x.frames} | ${x.nodes} | ${x.layoutMs.toFixed(0)} | ${x.styleMs.toFixed(0)} | ${x.taskMs.toFixed(0)} | ${x.scroll.avg.toFixed(1)} / ${x.scroll.p95.toFixed(1)} | ${x.scroll.slow} / ${x.scroll.frames} | ${x.feedHeight} |`); |
| 82 | fs.writeFileSync(path.join(root, out), lines.join('\n') + '\n'); |
| 83 | console.error(`→ ${out}`); |
| 84 | } |
| 85 |