// native/benchmarks/live-push/browser-probe.mjs [keys] [mean-ms] [sqid-index] // // The real web editor in headless Chrome, against the probe server // (run-probe.py SERVER_ONLY=1). Modes: // web-web two tabs of one document: type "Q"s in one, watch the other // web-types one tab types; the other side is the native probe // web-watches one tab watches; the other side is the native probe // The typing tab records each keydown's time; the watching tab records, per // new "Q", when the DOM showed it (MutationObserver) and the start of the // next frame after that (requestAnimationFrame). Times are Unix ms // (performance.timeOrigin + performance.now()), comparable with the server's // log and the native probe's. Keys are real CDP key events, as // fixtures/browser-drive.mjs types. import { readFileSync, writeFileSync } from 'node:fs' const [, , port, connPath, mode, outPath, keysArg = '120', meanArg = '150', indexArg = '0'] = process.argv const conn = JSON.parse(readFileSync(connPath, 'utf8')) const sqid = conn.sqids[Number(indexArg)] const url = `${conn.origin}/d/${sqid}` const version = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json() const ws = new WebSocket(version.webSocketDebuggerUrl) await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = reject }) let nextId = 0 const pending = new Map() ws.onmessage = (e) => { const msg = JSON.parse(e.data) if (msg.id && pending.has(msg.id)) { const { resolve, reject } = pending.get(msg.id) pending.delete(msg.id) msg.error ? reject(new Error(JSON.stringify(msg.error))) : resolve(msg.result) } } const send = (method, params = {}, sessionId) => new Promise((resolve, reject) => { if (process.env.CDP_DEBUG) console.error("cdp", method) const id = ++nextId pending.set(id, { resolve, reject }) ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })) }) const sleep = (ms) => new Promise(r => setTimeout(r, ms)) async function openTab() { const { targetId } = await send('Target.createTarget', { url: 'about:blank' }) const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true }) await send('Page.enable', {}, sessionId) await send('Runtime.enable', {}, sessionId) await send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId) await send('Network.enable', {}, sessionId) for (const c of conn.cookies) { if (c.Value) await send('Network.setCookie', { name: c.Name, value: c.Value, url: conn.origin }, sessionId) } await send('Page.navigate', { url }, sessionId) const evaluate = async (expression) => { const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, sessionId) if (r.exceptionDetails) throw new Error(JSON.stringify(r.exceptionDetails)) return r.result.value } for (let i = 0; i < 200; i++) { if (await evaluate(`!!document.querySelector('.ProseMirror') && document.readyState === 'complete'`).catch(() => false)) break await sleep(100) } await sleep(1500) // the stream opens and its connect-time event settles return { sessionId, evaluate } } async function watch(tab) { await tab.evaluate(`(() => { window.__seen = [] const ed = document.querySelector('.ProseMirror') const count = () => { let n = 0; const s = ed.textContent; for (let i = s.indexOf('Q'); i >= 0; i = s.indexOf('Q', i + 1)) n++; return n } let n = count() window.__base = n new MutationObserver(() => { const c = count() if (c <= n) return const t = performance.timeOrigin + performance.now(), from = n n = c requestAnimationFrame(() => { const f = performance.timeOrigin + performance.now() for (let i = from; i < c; i++) window.__seen.push([i - window.__base, t, f]) }) }).observe(ed, { subtree: true, childList: true, characterData: true }) return document.visibilityState })()`) } // Same distribution as live_push_probe_test.go's probeSchedule. function schedule(keys, mean, seed) { let s = seed const rand = () => { s = (s * 1103515245 + 12345) % 2147483648; return s / 2147483648 } const out = [] let at = 0, nextPause = 30 + Math.floor(rand() * 30) for (let k = 0; k < keys; k++) { out.push(at) at += 60 + -Math.log(1 - rand()) * (mean - 60) if (k === nextPause) { at += 700 + rand() * 800; nextPause += 30 + Math.floor(rand() * 30) } } return out } async function type(tab, keys, mean) { await tab.evaluate(`(() => { window.__keys = [] document.addEventListener('keydown', (e) => { if (e.key === 'Q') window.__keys.push(performance.timeOrigin + performance.now()) }, true) const ed = document.querySelector('.ProseMirror') const ps = [...ed.querySelectorAll('p')].filter(p => p.textContent.length > 40) const p = ps[Math.floor(ps.length / 2)] p.scrollIntoView({ block: 'center' }) ed.focus() const range = document.createRange() range.setStart(p.firstChild.nodeType === 3 ? p.firstChild : p, 0) range.collapse(true) const sel = getSelection(); sel.removeAllRanges(); sel.addRange(range) return true })()`) await sleep(300) const times = schedule(keys, mean, 4242) const start = performance.now() for (const at of times) { const wait = start + at - performance.now() if (wait > 0) await sleep(wait) await send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Q', code: 'KeyQ', text: 'Q', unmodifiedText: 'Q', windowsVirtualKeyCode: 81 }, tab.sessionId) await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Q', code: 'KeyQ', windowsVirtualKeyCode: 81 }, tab.sessionId) } } const keys = Number(keysArg), mean = Number(meanArg) const result = { mode, url } if (mode === 'web-web') { const watcher = await openTab() const typer = await openTab() result.visibility = await watcher.evaluate('document.visibilityState') await watch(watcher) await type(typer, keys, mean) await sleep(4000) result.keys = await typer.evaluate('window.__keys') result.seen = await watcher.evaluate('window.__seen') } else if (mode === 'web-types') { const typer = await openTab() if (process.env.START_AT) await sleep(Number(process.env.START_AT) - Date.now()) await type(typer, keys, mean) await sleep(4000) result.keys = await typer.evaluate('window.__keys') } else if (mode === 'web-watches') { const watcher = await openTab() await watch(watcher) writeFileSync(outPath + '.ready', '') const until = Date.now() + Number(process.env.WATCH_MS || 60000) while (Date.now() < until) await sleep(500) result.seen = await watcher.evaluate('window.__seen') } writeFileSync(outPath, JSON.stringify(result)) if (result.keys && result.seen) { const dom = [], frame = [] for (const [i, t, f] of result.seen) { if (result.keys[i] !== undefined) { dom.push(t - result.keys[i]); frame.push(f - result.keys[i]) } } const pct = (xs, p) => { const s = [...xs].sort((a, b) => a - b); return s[Math.max(0, Math.ceil(p * s.length) - 1)] } console.log('BROWSERPROBE ' + JSON.stringify({ mode, rtt: conn.rtt_ms, keys: result.keys.length, seen: result.seen.length, dom: [pct(dom, 0.5), pct(dom, 0.95)], frame: [pct(frame, 0.5), pct(frame, 0.95)] })) } process.exit(0)