| 1 | // native/benchmarks/live-push/browser-probe.mjs <devtools-port> <connection.json> <mode> <out.json> [keys] [mean-ms] [sqid-index] |
| 2 | // |
| 3 | // The real web editor in headless Chrome, against the probe server |
| 4 | // (run-probe.py SERVER_ONLY=1). Modes: |
| 5 | // web-web two tabs of one document: type "Q"s in one, watch the other |
| 6 | // web-types one tab types; the other side is the native probe |
| 7 | // web-watches one tab watches; the other side is the native probe |
| 8 | // The typing tab records each keydown's time; the watching tab records, per |
| 9 | // new "Q", when the DOM showed it (MutationObserver) and the start of the |
| 10 | // next frame after that (requestAnimationFrame). Times are Unix ms |
| 11 | // (performance.timeOrigin + performance.now()), comparable with the server's |
| 12 | // log and the native probe's. Keys are real CDP key events, as |
| 13 | // fixtures/browser-drive.mjs types. |
| 14 | import { readFileSync, writeFileSync } from 'node:fs' |
| 15 | |
| 16 | const [, , port, connPath, mode, outPath, keysArg = '120', meanArg = '150', indexArg = '0'] = process.argv |
| 17 | const conn = JSON.parse(readFileSync(connPath, 'utf8')) |
| 18 | const sqid = conn.sqids[Number(indexArg)] |
| 19 | const url = `${conn.origin}/d/${sqid}` |
| 20 | const version = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json() |
| 21 | const ws = new WebSocket(version.webSocketDebuggerUrl) |
| 22 | await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = reject }) |
| 23 | let nextId = 0 |
| 24 | const pending = new Map() |
| 25 | ws.onmessage = (e) => { |
| 26 | const msg = JSON.parse(e.data) |
| 27 | if (msg.id && pending.has(msg.id)) { |
| 28 | const { resolve, reject } = pending.get(msg.id) |
| 29 | pending.delete(msg.id) |
| 30 | msg.error ? reject(new Error(JSON.stringify(msg.error))) : resolve(msg.result) |
| 31 | } |
| 32 | } |
| 33 | const send = (method, params = {}, sessionId) => new Promise((resolve, reject) => { |
| 34 | if (process.env.CDP_DEBUG) console.error("cdp", method) |
| 35 | const id = ++nextId |
| 36 | pending.set(id, { resolve, reject }) |
| 37 | ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })) |
| 38 | }) |
| 39 | const sleep = (ms) => new Promise(r => setTimeout(r, ms)) |
| 40 | |
| 41 | |
| 42 | async function openTab() { |
| 43 | const { targetId } = await send('Target.createTarget', { url: 'about:blank' }) |
| 44 | const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true }) |
| 45 | await send('Page.enable', {}, sessionId) |
| 46 | await send('Runtime.enable', {}, sessionId) |
| 47 | await send('Emulation.setFocusEmulationEnabled', { enabled: true }, sessionId) |
| 48 | await send('Network.enable', {}, sessionId) |
| 49 | for (const c of conn.cookies) { |
| 50 | if (c.Value) await send('Network.setCookie', { name: c.Name, value: c.Value, url: conn.origin }, sessionId) |
| 51 | } |
| 52 | await send('Page.navigate', { url }, sessionId) |
| 53 | const evaluate = async (expression) => { |
| 54 | const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }, sessionId) |
| 55 | if (r.exceptionDetails) throw new Error(JSON.stringify(r.exceptionDetails)) |
| 56 | return r.result.value |
| 57 | } |
| 58 | for (let i = 0; i < 200; i++) { |
| 59 | if (await evaluate(`!!document.querySelector('.ProseMirror') && document.readyState === 'complete'`).catch(() => false)) break |
| 60 | await sleep(100) |
| 61 | } |
| 62 | await sleep(1500) // the stream opens and its connect-time event settles |
| 63 | return { sessionId, evaluate } |
| 64 | } |
| 65 | |
| 66 | async function watch(tab) { |
| 67 | await tab.evaluate(`(() => { |
| 68 | window.__seen = [] |
| 69 | const ed = document.querySelector('.ProseMirror') |
| 70 | 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 } |
| 71 | let n = count() |
| 72 | window.__base = n |
| 73 | new MutationObserver(() => { |
| 74 | const c = count() |
| 75 | if (c <= n) return |
| 76 | const t = performance.timeOrigin + performance.now(), from = n |
| 77 | n = c |
| 78 | requestAnimationFrame(() => { |
| 79 | const f = performance.timeOrigin + performance.now() |
| 80 | for (let i = from; i < c; i++) window.__seen.push([i - window.__base, t, f]) |
| 81 | }) |
| 82 | }).observe(ed, { subtree: true, childList: true, characterData: true }) |
| 83 | return document.visibilityState |
| 84 | })()`) |
| 85 | } |
| 86 | |
| 87 | // Same distribution as live_push_probe_test.go's probeSchedule. |
| 88 | function schedule(keys, mean, seed) { |
| 89 | let s = seed |
| 90 | const rand = () => { s = (s * 1103515245 + 12345) % 2147483648; return s / 2147483648 } |
| 91 | const out = [] |
| 92 | let at = 0, nextPause = 30 + Math.floor(rand() * 30) |
| 93 | for (let k = 0; k < keys; k++) { |
| 94 | out.push(at) |
| 95 | at += 60 + -Math.log(1 - rand()) * (mean - 60) |
| 96 | if (k === nextPause) { at += 700 + rand() * 800; nextPause += 30 + Math.floor(rand() * 30) } |
| 97 | } |
| 98 | return out |
| 99 | } |
| 100 | |
| 101 | async function type(tab, keys, mean) { |
| 102 | await tab.evaluate(`(() => { |
| 103 | window.__keys = [] |
| 104 | document.addEventListener('keydown', (e) => { if (e.key === 'Q') window.__keys.push(performance.timeOrigin + performance.now()) }, true) |
| 105 | const ed = document.querySelector('.ProseMirror') |
| 106 | const ps = [...ed.querySelectorAll('p')].filter(p => p.textContent.length > 40) |
| 107 | const p = ps[Math.floor(ps.length / 2)] |
| 108 | p.scrollIntoView({ block: 'center' }) |
| 109 | ed.focus() |
| 110 | const range = document.createRange() |
| 111 | range.setStart(p.firstChild.nodeType === 3 ? p.firstChild : p, 0) |
| 112 | range.collapse(true) |
| 113 | const sel = getSelection(); sel.removeAllRanges(); sel.addRange(range) |
| 114 | return true |
| 115 | })()`) |
| 116 | await sleep(300) |
| 117 | const times = schedule(keys, mean, 4242) |
| 118 | const start = performance.now() |
| 119 | for (const at of times) { |
| 120 | const wait = start + at - performance.now() |
| 121 | if (wait > 0) await sleep(wait) |
| 122 | await send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Q', code: 'KeyQ', text: 'Q', unmodifiedText: 'Q', windowsVirtualKeyCode: 81 }, tab.sessionId) |
| 123 | await send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Q', code: 'KeyQ', windowsVirtualKeyCode: 81 }, tab.sessionId) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | const keys = Number(keysArg), mean = Number(meanArg) |
| 128 | const result = { mode, url } |
| 129 | if (mode === 'web-web') { |
| 130 | const watcher = await openTab() |
| 131 | const typer = await openTab() |
| 132 | result.visibility = await watcher.evaluate('document.visibilityState') |
| 133 | await watch(watcher) |
| 134 | await type(typer, keys, mean) |
| 135 | await sleep(4000) |
| 136 | result.keys = await typer.evaluate('window.__keys') |
| 137 | result.seen = await watcher.evaluate('window.__seen') |
| 138 | } else if (mode === 'web-types') { |
| 139 | const typer = await openTab() |
| 140 | if (process.env.START_AT) await sleep(Number(process.env.START_AT) - Date.now()) |
| 141 | await type(typer, keys, mean) |
| 142 | await sleep(4000) |
| 143 | result.keys = await typer.evaluate('window.__keys') |
| 144 | } else if (mode === 'web-watches') { |
| 145 | const watcher = await openTab() |
| 146 | await watch(watcher) |
| 147 | writeFileSync(outPath + '.ready', '') |
| 148 | const until = Date.now() + Number(process.env.WATCH_MS || 60000) |
| 149 | while (Date.now() < until) await sleep(500) |
| 150 | result.seen = await watcher.evaluate('window.__seen') |
| 151 | } |
| 152 | writeFileSync(outPath, JSON.stringify(result)) |
| 153 | if (result.keys && result.seen) { |
| 154 | const dom = [], frame = [] |
| 155 | for (const [i, t, f] of result.seen) { |
| 156 | if (result.keys[i] !== undefined) { dom.push(t - result.keys[i]); frame.push(f - result.keys[i]) } |
| 157 | } |
| 158 | const pct = (xs, p) => { const s = [...xs].sort((a, b) => a - b); return s[Math.max(0, Math.ceil(p * s.length) - 1)] } |
| 159 | console.log('BROWSERPROBE ' + JSON.stringify({ mode, rtt: conn.rtt_ms, keys: result.keys.length, seen: result.seen.length, |
| 160 | dom: [pct(dom, 0.5), pct(dom, 0.95)], frame: [pct(frame, 0.5), pct(frame, 0.95)] })) |
| 161 | } |
| 162 | process.exit(0) |
| 163 | |