//! `cargo xtask stress [data|huge|flood|all] [--notes N] [--notebooks N] [--keep] [--start N]`: //! load tests against a release server on a scratch database, with the editor driven //! in headless Firefox (never on screen). //! //! - data: thousands of notebooks and many notes through the import endpoint, then the //! latency of the pages that list and search them. //! - huge: very large single notes (a 200k-line code block, 1M lorem paragraphs, ...): //! import, export, page size, time to editable and real keystroke latency. //! - billion / billion-check: a billion lines over a thousand notes on their own //! database (`billion.db`), imported in rounds of `--notes`, then read, searched and //! exported whole, with the exported zip's lines counted. //! - flood: an endless upload (a billion lines) must be refused without the server //! growing, and the server must stay responsive. use std::io::Read; use std::path::Path; use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread::sleep; use std::time::{Duration, Instant}; use anyhow::{Context, Result, bail}; use serde_json::{Value, json}; use crate::e2e::{CAPTURE, EDITABLE, Kill, Session, agent, wait_http}; const PORT: &str = "3918"; const SERVER: &str = "http://127.0.0.1:3918"; const DRIVER_PORT: &str = "4919"; struct Opts { notes: usize, notebooks: usize, keep: bool, /// First note number of the data phase, to add more notes to a kept database. start: usize, build: bool, only: Vec, } pub fn run(root: &Path, target: &Path, args: &[String]) -> Result<()> { let mut opts = Opts { notes: 20_000, notebooks: 2_000, keep: false, start: 0, build: true, only: Vec::new() }; let mut it = args.iter(); let mut phase = "all".to_owned(); while let Some(a) = it.next() { match a.as_str() { "--notes" => opts.notes = it.next().context("--notes N")?.parse()?, "--notebooks" => opts.notebooks = it.next().context("--notebooks N")?.parse()?, "--keep" => opts.keep = true, "--start" => opts.start = it.next().context("--start N")?.parse()?, "--no-build" => opts.build = false, "--only" => opts.only.push(it.next().context("--only NAME")?.clone()), p => phase = p.to_owned(), } } // Builds the release server and bundles its assets next to the executable. if opts.build { let status = Command::new("topcoat").args(["asset", "bundle", "--release", "-p", "project_note"]).current_dir(root).status()?; if !status.success() { bail!("server build failed"); } } let dir = target.join("stress"); std::fs::create_dir_all(dir.join("profile"))?; let db = if phase.starts_with("billion") { "billion.db" } else { "notes.db" }; if !opts.keep { for f in ["", "-wal", "-shm"] { let _ = std::fs::remove_file(dir.join(format!("{db}{f}"))); } } let server = Kill( Command::new(target.join("release/project_note")) .current_dir(root) .env("NOTE_DB", dir.join(db)) .env("PORT", PORT) .stdout(Stdio::null()) .spawn() .context("starting the server")?, ); let pid = server.0.id(); let agent = agent(); wait_http(&agent, &format!("{SERVER}/"))?; println!("server pid {pid}, rss {} MB", rss_mb(pid)); match phase.as_str() { "data" => data(&agent, &opts, pid)?, "huge" => huge(&agent, &opts, &dir, pid)?, "flood" => flood(&agent, pid)?, "billion" => billion(&agent, &opts, pid)?, "billion-check" => billion_check(&agent, &dir, pid)?, "exp" => exp(&agent, &dir, &opts.only)?, "all" => { data(&agent, &opts, pid)?; huge(&agent, &opts, &dir, pid)?; flood(&agent, pid)?; } p => bail!("unknown phase {p}"), } println!("server rss at end {} MB", rss_mb(pid)); drop(server); Ok(()) } fn rss_mb(pid: u32) -> u64 { let s = std::fs::read_to_string(format!("/proc/{pid}/status")).unwrap_or_default(); s.lines() .find_map(|l| l.strip_prefix("VmRSS:")) .and_then(|v| v.split_whitespace().next()?.parse::().ok()) .map_or(0, |kb| kb / 1024) } fn import(agent: &ureq::Agent, path: &str, text: &str) -> Result { let mut resp = agent.post(&format!("{SERVER}/import/file")).send_form([("path", path), ("text", text)])?; let status = resp.status(); let body = resp.body_mut().with_config().limit(u64::MAX).read_to_string()?; if !status.is_success() { bail!("import {path}: {status} {}", body.chars().take(200).collect::()); } Ok(body.trim().to_owned()) } /// GET `url`; returns (seconds, body bytes, status). fn timed_get(agent: &ureq::Agent, url: &str) -> Result<(f64, usize, u16)> { let t = Instant::now(); let mut resp = agent.get(url).call()?; let status = resp.status().as_u16(); let mut n = 0usize; let mut buf = vec![0u8; 1 << 16]; let mut r = resp.body_mut().with_config().limit(u64::MAX).reader(); loop { let k = r.read(&mut buf)?; if k == 0 { break; } n += k; } Ok((t.elapsed().as_secs_f64(), n, status)) } fn report_get(agent: &ureq::Agent, label: &str, url: &str) -> Result<()> { let mut times = Vec::new(); let mut size = 0; for _ in 0..5 { let (t, n, status) = timed_get(agent, url)?; if status >= 400 { bail!("{label}: HTTP {status}"); } times.push(t * 1000.0); size = n; } times.sort_by(f64::total_cmp); println!(" {label:<28} median {:>8.1} ms max {:>8.1} ms {:>10} bytes", times[2], times[4], size); Ok(()) } // --------------------------------------------------------------------------- // data: many notes and notebooks // --------------------------------------------------------------------------- fn small_note(i: usize) -> String { format!( "Note {i} about the project.\n\nSome words for search: alpha{a} beta{b} gamma.\n\n- item one\n- item two [[Note {link}]]\n\n```rust\nfn note_{i}() -> usize {{ {i} }}\n```\n", a = i % 97, b = i % 13, link = (i * 7 + 1) % (i + 1).max(1) ) } fn data(agent: &ureq::Agent, opts: &Opts, pid: u32) -> Result<()> { println!("data: {} notes in {} notebooks", opts.notes, opts.notebooks); let next = AtomicUsize::new(opts.start); let end = opts.start + opts.notes; let errors = AtomicUsize::new(0); let t = Instant::now(); std::thread::scope(|s| { for _ in 0..12 { s.spawn(|| { let agent = agent.clone(); loop { let i = next.fetch_add(1, Ordering::Relaxed); if i >= end { break; } let path = format!("Notebook {}/Note {i}.md", i % opts.notebooks.max(1)); if let Err(e) = import(&agent, &path, &small_note(i)) { if errors.fetch_add(1, Ordering::Relaxed) < 5 { eprintln!(" {e}"); } } if i % 50000 == 49999 { println!(" {} notes, {:.0}/s", i + 1, (i + 1 - opts.start) as f64 / t.elapsed().as_secs_f64()); } } }); } }); let secs = t.elapsed().as_secs_f64(); println!( " imported in {secs:.1}s ({:.0} notes/s), {} errors, server rss {} MB", opts.notes as f64 / secs, errors.load(Ordering::Relaxed), rss_mb(pid) ); let id = import(agent, "probe.md", "probe note")?; report_get(agent, "GET / (all notes)", &format!("{SERVER}/"))?; report_get(agent, "GET /unfiled", &format!("{SERVER}/unfiled"))?; report_get(agent, "GET /notes/", &format!("{SERVER}/notes/{id}"))?; report_get(agent, "titles.json?q=Note 12", &format!("{SERVER}/notes/titles.json?q=Note%2012"))?; report_get(agent, "titles.json?q=", &format!("{SERVER}/notes/titles.json?q="))?; report_get(agent, "search alpha42", &format!("{SERVER}/search?q=alpha42"))?; report_get(agent, "search gamma (all match)", &format!("{SERVER}/search?q=gamma"))?; let nb = notebook_url(agent)?; report_get(agent, "GET /notebooks/", &format!("{SERVER}{nb}"))?; let (t, n, _) = timed_get(agent, &format!("{SERVER}/export.zip"))?; println!(" GET /export.zip {:>8.1} s {:>10} bytes, rss {} MB", t, n, rss_mb(pid)); Ok(()) } // --------------------------------------------------------------------------- // billion: a billion lines over many notes // --------------------------------------------------------------------------- const BILLION_LINES_PER_NOTE: usize = 1_000_000; /// Note `i` of the billion-line set: a heading, a searchable line, then a code block. /// Every line of the code block and the two lines above it count. fn billion_note(i: usize) -> String { let mut s = format!("# Billion {i}\n\nmarker{} of the billion set\n\n```\n", i % 97); s.reserve(BILLION_LINES_PER_NOTE * 14); for k in 0..BILLION_LINES_PER_NOTE - 2 { s.push_str(" ret v"); s.push_str(&(k % 1000).to_string()); s.push('\n'); } s + "```\n" } fn billion(agent: &ureq::Agent, opts: &Opts, pid: u32) -> Result<()> { let end = opts.start + opts.notes; println!("billion: notes {}..{end}, {} lines each", opts.start, BILLION_LINES_PER_NOTE); let next = AtomicUsize::new(opts.start); let errors = AtomicUsize::new(0); let t = Instant::now(); std::thread::scope(|s| { for _ in 0..4 { s.spawn(|| { let agent = agent.clone(); loop { let i = next.fetch_add(1, Ordering::Relaxed); if i >= end { break; } let path = format!("Billion {}/Billion {i}.md", i % 50); if let Err(e) = import(&agent, &path, &billion_note(i)) { if errors.fetch_add(1, Ordering::Relaxed) < 5 { eprintln!(" {e}"); } } if i % 50 == 49 { println!(" {} notes, {:.1}/s, rss {} MB", i + 1, (i + 1 - opts.start) as f64 / t.elapsed().as_secs_f64(), rss_mb(pid)); } } }); } }); println!( " imported in {:.1}s, {} errors, server rss {} MB", t.elapsed().as_secs_f64(), errors.load(Ordering::Relaxed), rss_mb(pid) ); Ok(()) } fn billion_check(agent: &ureq::Agent, dir: &Path, pid: u32) -> Result<()> { println!("billion-check: server rss {} MB", rss_mb(pid)); report_get(agent, "GET / (all notes)", &format!("{SERVER}/"))?; report_get(agent, "search marker42", &format!("{SERVER}/search?q=marker42"))?; report_get(agent, "search v999 (in every line block)", &format!("{SERVER}/search?q=v999"))?; report_get(agent, "search exact \"ret v999\"", &format!("{SERVER}/search?q=ret%20v999&exact=1"))?; report_get(agent, "search regex absent zzq\\d+", &format!("{SERVER}/search?q=zzq%5Cd%2B&re=1"))?; report_get(agent, "search regex ret v99\\d", &format!("{SERVER}/search?q=ret%20v99%5Cd&re=1"))?; report_get(agent, "search regex (no literal) \\d{9}", &format!("{SERVER}/search?q=%5Cd%7B9%7D&re=1"))?; report_get(agent, "search regex (no literal) v\\d{3}\\b", &format!("{SERVER}/search?q=v%5Cd%7B3%7D%5Cb&re=1"))?; report_get(agent, "search regex (spans words) \\w+ \\w{9}", &format!("{SERVER}/search?q=%5Cw%2B%20%5Cw%7B9%7D&re=1"))?; report_get(agent, " same, every note (all=1)", &format!("{SERVER}/search?q=%5Cw%2B%20%5Cw%7B9%7D&re=1&all=1"))?; report_get(agent, "titles.json?q=Billion 7", &format!("{SERVER}/notes/titles.json?q=Billion%207"))?; let nb = notebook_url(agent)?; report_get(agent, "GET /notebooks/", &format!("{SERVER}{nb}"))?; let page = agent.get(&format!("{SERVER}{nb}")).call()?.body_mut().with_config().limit(u64::MAX).read_to_string()?; let at = page.find("href=\"/notes/").context("no note link")?; let rest = &page[at + 6..]; let note = &rest[..rest.find('"').unwrap()]; report_get(agent, "GET /notes/ (1M lines)", &format!("{SERVER}{note}"))?; report_get(agent, "GET export.md (1M lines)", &format!("{SERVER}{note}/export.md"))?; let zip = dir.join("billion.zip"); let t = Instant::now(); let mut resp = agent.get(&format!("{SERVER}/export.zip")).call()?; let mut out = std::io::BufWriter::new(std::fs::File::create(&zip)?); let n = std::io::copy(&mut resp.body_mut().with_config().limit(u64::MAX).reader(), &mut out)?; drop(out); println!(" GET /export.zip {:.1}s, {:.0} MB, rss {} MB", t.elapsed().as_secs_f64(), n as f64 / 1e6, rss_mb(pid)); let t = Instant::now(); let lines = Command::new("sh") .arg("-c") .arg("unzip -p \"$0\" | wc -l") .arg(&zip) .output()?; println!(" lines in zip: {} ({:.1}s)", String::from_utf8_lossy(&lines.stdout).trim(), t.elapsed().as_secs_f64()); std::fs::remove_file(&zip)?; Ok(()) } fn notebook_url(agent: &ureq::Agent) -> Result { let html = agent.get(&format!("{SERVER}/")).call()?.body_mut().with_config().limit(u64::MAX).read_to_string()?; let at = html.find("href=\"/notebooks/").context("no notebook link")?; let rest = &html[at + 6..]; Ok(rest[..rest.find('"').unwrap()].to_owned()) } // --------------------------------------------------------------------------- // huge: single very large notes // --------------------------------------------------------------------------- const WORDS: &[&str] = &[ "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim", "veniam", "quis", ]; fn lorem_line(i: usize) -> String { let n = 6 + i % 7; let mut s = String::new(); for k in 0..n { if k > 0 { s.push(' '); } s.push_str(WORDS[(i * 31 + k * 7) % WORDS.len()]); } s } fn code_lines(n: usize) -> String { let mut s = String::from("```rust\n"); for i in 0..n { match i % 8 { 0 => s.push_str(&format!("pub fn handler_{i}(state: &State, id: u64) -> Result> {{\n")), 1 => s.push_str(" let rows = load_rows(state, id, 50)?;\n"), 2 => s.push_str(" let skipped = rows.iter().filter(|r| !r.name.is_empty()).count();\n"), 3 => s.push_str(" if skipped > 2000 {\n"), 4 => s.push_str(" return Err(anyhow!(\"too many rows: {skipped}\"));\n"), 5 => s.push_str(" }\n"), 6 => s.push_str(" Ok(rows.into_iter().map(|r| r.with_lang(\"en\")).collect())\n"), _ => s.push_str("}\n"), } } s.push_str("```\n"); s } /// The server, for RSS readings along a browser run. static SERVER_PID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); fn server_rss() -> u64 { rss_mb(SERVER_PID.load(Ordering::Relaxed)) } fn huge(agent: &ureq::Agent, opts: &Opts, dir: &Path, pid: u32) -> Result<()> { SERVER_PID.store(pid, Ordering::Relaxed); let cases: Vec<(&str, Box String>)> = vec![ ("tiny", Box::new(|| (0..3).map(|i| lorem_line(i) + "\n\n").collect())), ("p10k", Box::new(|| (0..10_000).map(|i| lorem_line(i) + "\n\n").collect())), ("code200k", Box::new(|| code_lines(200_000))), ("p100k", Box::new(|| (0..100_000).map(|i| lorem_line(i) + "\n\n").collect())), ("lines1m", Box::new(|| (0..1_000_000).map(|i| lorem_line(i) + "\n").collect())), ("p1m", Box::new(|| (0..1_000_000).map(|i| lorem_line(i) + "\n\n").collect())), // Near the 128 MB upload limit once form-encoded: short lines, little punctuation. ("code8m", Box::new(|| { let mut s = String::from("```\n"); for i in 0..8_000_000 { s.push_str(&format!(" ret v{}\n", i % 1000)); } s + "```\n" })), ]; // The page's console (panics land there) goes to gecko.log. let log = std::fs::File::create(dir.join("gecko.log"))?; let gecko = Kill( Command::new("geckodriver") .args(["--port", DRIVER_PORT]) .env("MOZ_HEADLESS", "1") .env_remove("DISPLAY") .env_remove("WAYLAND_DISPLAY") .stdout(log.try_clone()?) .stderr(log) .spawn() .context("starting geckodriver")?, ); wait_http(agent, &format!("http://127.0.0.1:{DRIVER_PORT}/status"))?; let session = Session::new(agent, &format!("http://127.0.0.1:{DRIVER_PORT}"), &dir.join("profile"))?; session.cmd("POST", "/timeouts", Some(json!({"script": 600_000, "pageLoad": 600_000})))?; let result = (|| -> Result<()> { for (name, make) in &cases { if !opts.only.is_empty() && !opts.only.iter().any(|o| o == name) { continue; } let text = make(); println!("huge {name}: {} lines, {:.1} MB", text.lines().count(), text.len() as f64 / 1e6); let t = Instant::now(); let id = match import(agent, &format!("{name}.md"), &text) { Ok(id) => id, Err(e) => { println!(" import failed after {:.1}s: {e}", t.elapsed().as_secs_f64()); continue; } }; println!(" import {:.2}s, server rss {} MB", t.elapsed().as_secs_f64(), rss_mb(pid)); let note = format!("{SERVER}/notes/{id}"); let (t, n, _) = timed_get(agent, &format!("{note}/export.md"))?; println!(" export.md {:.2}s {:.1} MB", t, n as f64 / 1e6); let (t, n, _) = timed_get(agent, ¬e)?; println!(" page html {:.2}s {:.1} MB", t, n as f64 / 1e6); browse(agent, &session, ¬e, name, dir)?; let t = Instant::now(); session.go(¬e)?; session.wait_for(EDITABLE, "editable", 600)?; println!(" reopen: editable after {:.2}s", t.elapsed().as_secs_f64()); println!(" server rss {} MB", rss_mb(pid)); // Kept DBs would otherwise gain 100+ MB per run. session.go(&format!("{SERVER}/"))?; agent.post(&format!("{note}/trash")).send_empty()?; agent.post(&format!("{SERVER}/trash/empty")).send_empty()?; } Ok(()) })(); session.close(); drop(gecko); result } /// Records, for each real keydown, the main-thread time it costs: our event handlers up /// to the next frame plus that frame (rAF callbacks, style, layout, paint) until a timer /// after it runs. `__raw` keeps keydown to that timer, which adds the idle wait for the /// browser's 60 Hz frame clock (0 to 16.7 ms, set by when the key happens to land). const LATENCY: &str = "window.__lat = []; window.__raw = []; if (!window.__latOn) { window.__latOn = true; let cur = null; \ for (const t of ['keydown', 'beforeinput', 'input', 'selectionchange']) { let s = 0; \ window.addEventListener(t, () => { s = performance.now(); if (t !== 'keydown') return; const c = cur = {t0: s, busy: 0}; \ requestAnimationFrame(() => { const t2 = performance.now(); if (cur === c) cur = null; \ setTimeout(() => { const t3 = performance.now(); __raw.push(t3 - c.t0); __lat.push(c.busy + t3 - t2); }, 0); }); }, true); \ window.addEventListener(t, () => { if (cur) cur.busy += performance.now() - s; }, false); } } return true"; /// Splits the time: our handlers per event type (capture to bubble on window), rAF and /// timer callbacks, and the rest (browser style, layout and paint). const PROFILE: &str = "if (!window.__prof) { const P = window.__prof = {ev: {}, raf: 0, rafN: 0, tm: 0, tmN: 0}; \ for (const t of ['keydown', 'beforeinput', 'input', 'keyup', 'selectionchange', 'compositionend']) { let s = 0; \ window.addEventListener(t, () => { s = performance.now(); }, true); \ window.addEventListener(t, () => { const d = performance.now() - s; P.ev[t] = (P.ev[t] || 0) + d; }, false); } \ { let s = 0; document.addEventListener('selectionchange', () => { s = performance.now(); }, true); document.addEventListener('selectionchange', () => { P.ev.docsel = (P.ev.docsel || 0) + performance.now() - s; P.ev.docselN = (P.ev.docselN || 0) + 1; }, false); } \ const raf = window.requestAnimationFrame.bind(window); window.requestAnimationFrame = cb => raf(ts => { const s = performance.now(); cb(ts); P.raf += performance.now() - s; P.rafN++; }); \ const st = window.setTimeout.bind(window); window.setTimeout = (cb, ms, ...a) => st((...b) => { const s = performance.now(); cb(...b); P.tm += performance.now() - s; P.tmN++; }, ms, ...a); } \ const P = window.__prof; P.ev = {}; P.raf = 0; P.rafN = 0; P.tm = 0; P.tmN = 0; return true"; const PROF_STATS: &str = "const P = window.__prof; const r = x => +x.toFixed(1); const ev = {}; \ for (const k in P.ev) ev[k] = r(P.ev[k]); return {handlers_ms: ev, raf_ms: r(P.raf), raf_n: P.rafN, timers_ms: r(P.tm), timers_n: P.tmN}"; /// Each key's time, then with the frame wait. const SERIES: &str = "const f = a => a.map(x => Math.round(x)).join(' '); return `${f(__lat)} | wait incl. ${f(__raw)}`"; const LAT_STATS: &str = "const t = [...__lat].sort((a, b) => a - b); if (!t.length) return null; \ return {n: t.length, avg: +(t.reduce((a, b) => a + b, 0) / t.length).toFixed(2), p50: +t[t.length >> 1].toFixed(2), \ p95: +t[Math.floor(t.length * 0.95)].toFixed(2), max: +t[t.length - 1].toFixed(2)}"; fn caret_at_block(s: &Session, frac: f64) -> Result { // Scroll to `frac` of the editor's height (as a person would with the scrollbar); // only blocks near the viewport are in the DOM, built on the next frames. let n = s.js(&format!( "const r = document.querySelector('#editor .ProseMirror'); r.focus(); \ let sc = r.parentElement; \ while (sc && !(sc.scrollHeight > sc.clientHeight && /(auto|scroll)/.test(getComputedStyle(sc).overflowY))) sc = sc.parentElement; \ sc = sc || document.scrollingElement; \ const top = sc === document.scrollingElement ? 0 : sc.getBoundingClientRect().top; \ const rr = r.getBoundingClientRect(); \ sc.scrollTop += rr.top - top + rr.height * {frac} - sc.clientHeight / 2; \ return r.querySelectorAll('p, pre, li, h1, h2, h3').length" ))?; sleep(Duration::from_millis(400)); // Units in document order among what is built: blocks, long ones chunk by chunk. s.js(&format!( "const r = document.querySelector('#editor .ProseMirror'); const units = []; \ for (const b of r.querySelectorAll('p, pre, li, h1, h2, h3')) {{ const c = b.querySelectorAll('.code-chunk, .text-chunk'); if (c.length) units.push(...c); else units.push(b); }} \ const u = units[Math.floor((units.length - 1) * {frac})]; \ const w = document.createTreeWalker(u, NodeFilter.SHOW_TEXT); const tn = w.nextNode(); \ if (tn) getSelection().collapse(tn, Math.min(5, tn.length)); else getSelection().collapse(u, 0); return true" ))?; Ok(n) } fn keys_latency(s: &Session, keys: &str) -> Result { s.js(LATENCY)?; s.js(PROFILE)?; // One key at a time, ~16 keys/s like a fast typist: a burst would queue keys behind // each other and measure throughput instead of latency. for k in keys.chars() { s.keys("#editor .ProseMirror", &k.to_string())?; sleep(Duration::from_millis(60)); } sleep(Duration::from_millis(300)); let mut v = s.js(LAT_STATS)?; v["with_frame_wait"] = s.js(&LAT_STATS.replace("__lat", "__raw"))?; v["profile"] = s.js(PROF_STATS)?; Ok(v) } fn browse(agent: &ureq::Agent, s: &Session, note: &str, name: &str, dir: &Path) -> Result<()> { let t = Instant::now(); s.go(note)?; let loaded = t.elapsed().as_secs_f64(); if let Err(e) = s.wait_for(EDITABLE, "editable", 600) { println!(" browser: {e}"); return Ok(()); } println!(" browser: load {loaded:.2}s, editable after {:.2}s, server rss {} MB", t.elapsed().as_secs_f64(), server_rss()); s.js(CAPTURE)?; let blocks = caret_at_block(s, 0.5)?; sleep(Duration::from_millis(500)); println!(" blocks in DOM {blocks}, {}", s.js("const c = document.querySelectorAll('.code-chunk, .text-chunk'); \ return c.length ? `${c.length} code chunks, ${getComputedStyle(c[0]).contentVisibility}, ${getComputedStyle(c[0]).containIntrinsicHeight}` : 'no code chunks'")?); const MID: &str = "alpha bravo charlie delta echo foxtrot "; const END: &str = "golf hotel india juliet kilo lima mike "; const START: &str = "november oscar papa quebec romeo sierra"; let at_mid = s.js("const s = getSelection(); return s.anchorNode && s.anchorNode.textContent.slice(Math.max(0, s.anchorOffset - 20), s.anchorOffset)")?; println!(" type 40 chars mid {}", keys_latency(s, MID)?); // 40 presses: of 10, the 95th percentile would be the slowest one. println!(" enter x40 mid {}", keys_latency(s, &"\u{E007}".repeat(40))?); println!(" series {}", s.js(SERIES)?); println!(" backspace x40 mid {}", keys_latency(s, &"\u{E003}".repeat(40))?); println!(" series {}", s.js(SERIES)?); // STRESS_PROBE="label=js;;label=js": run each snippet, then time typing again (bisecting). if let Ok(probe) = std::env::var("STRESS_PROBE") { for step in probe.split(";;") { let (label, js) = step.split_once('=').unwrap_or((step, "")); s.js(&format!("{js}; return true"))?; caret_at_block(s, 0.5)?; sleep(Duration::from_millis(300)); println!(" probe {label:<20} {}", keys_latency(s, "abcdefghijklmnopqrst")?); println!(" series {}", s.js(SERIES)?); } } caret_at_block(s, 1.0)?; sleep(Duration::from_millis(300)); let at_end = s.js("const s = getSelection(); return s.anchorNode && s.anchorNode.textContent.slice(Math.max(0, s.anchorOffset - 20), s.anchorOffset)")?; println!(" type 40 chars end {}", keys_latency(s, END)?); caret_at_block(s, 0.0)?; sleep(Duration::from_millis(300)); let at_start = s.js("const s = getSelection(); return s.anchorNode && s.anchorNode.textContent.slice(Math.max(0, s.anchorOffset - 20), s.anchorOffset)")?; println!(" type 40 chars start {}", keys_latency(s, START)?); println!(" after typing: server rss {} MB", server_rss()); // The model must hold each typed string once, right after where the caret was. // The server applies updates a moment after the client sent them: wait for all // three strings (a lost keystroke still shows as WRONG after the deadline). let waited = Instant::now(); let mut md; loop { sleep(Duration::from_millis(250)); md = agent.get(&format!("{note}/export.md")).call()?.body_mut().with_config().limit(u64::MAX).read_to_string()?; if [MID, END, START].iter().all(|x| md.contains(x)) || waited.elapsed() > Duration::from_secs(15) { break; } } println!(" server has the edits after {:.2}s, server rss {} MB", waited.elapsed().as_secs_f64(), server_rss()); println!( " sync state {}, export {} MB, errors so far {}", s.js("const e = document.querySelector('[data-state]'); return e && e.dataset.state")?, md.len() >> 20, s.js("return __log.filter(l => l.startsWith('error') || l.startsWith('uncaught')).length")? ); for (what, text, before) in [("mid", MID, &at_mid), ("end", END, &at_end), ("start", START, &at_start)] { let found: Vec = md.match_indices(text).map(|(i, _)| i).collect(); let ok = found.len() == 1 && before.as_str().is_some_and(|b| md[..found[0]].ends_with(b)); let ctx = found.first().map(|&i| md[i.saturating_sub(30)..(i + text.len() + 10).min(md.len())].replace('\n', "⏎")).unwrap_or_default(); let line = found.first().map_or(0, |&i| md[..i].matches('\n').count() + 1); println!(" check {what:<5} {} (found {}x at line {line}, caret after {before}) …{ctx}…", if ok { "ok" } else { "WRONG" }, found.len()); if found.is_empty() { let head: String = md.chars().take(160).collect(); println!(" export starts {:?}; dom starts {}", head, s.js("return document.querySelector('#editor .ProseMirror').textContent.slice(0, 160)")?); } } // Select all, delete, undo: the heaviest structural edits. let ops = s.js( "const r = document.querySelector('#editor .ProseMirror'); r.focus(); \ const ev = (k, c, mod) => r.dispatchEvent(new KeyboardEvent('keydown', {key: k, code: c, ctrlKey: mod, cancelable: true, bubbles: true})); \ const time = f => { const s = performance.now(); f(); return +(performance.now() - s).toFixed(1); }; \ const all = time(() => ev('a', 'KeyA', true)); \ const del = time(() => ev('Backspace', 'Backspace', false)); \ const after = r.scrollHeight; \ const undo = time(() => ev('z', 'KeyZ', true)); \ return {select_all_ms: all, delete_ms: del, height_after_delete: after, undo_ms: undo, height_after_undo: r.scrollHeight}", )?; println!(" {ops}"); sleep(Duration::from_millis(3000)); println!(" after undo + 3 s: server rss {} MB", server_rss()); std::thread::sleep(Duration::from_millis(1500)); println!(" after undo: {}", s.js("const r = document.querySelector('#editor .ProseMirror'); return {height: r.scrollHeight, text: r.textContent.length, children: r.children.length, code: r.querySelectorAll('pre').length}")?); let _ = s.screenshot(&dir.join(format!("{name}.png"))); let err = s.js("return window.__log ? __log.filter(l => l.startsWith('error') || l.startsWith('uncaught')).slice(0, 40) : []")?; if err.as_array().is_some_and(|a| !a.is_empty()) { println!(" console errors: {err}"); } Ok(()) } // --------------------------------------------------------------------------- // flood: an upload that never ends // --------------------------------------------------------------------------- /// A urlencoded form body with `lines` lorem lines, produced on the fly. struct Endless { prefix: Vec, at: usize, lines: u64, line: Vec, pos: usize, } impl Read for Endless { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { if self.at < self.prefix.len() { let n = (self.prefix.len() - self.at).min(buf.len()); buf[..n].copy_from_slice(&self.prefix[self.at..self.at + n]); self.at += n; return Ok(n); } let mut n = 0; while n < buf.len() { if self.pos == self.line.len() { if self.lines == 0 { break; } self.lines -= 1; self.pos = 0; } let k = (self.line.len() - self.pos).min(buf.len() - n); buf[n..n + k].copy_from_slice(&self.line[self.pos..self.pos + k]); self.pos += k; n += k; } Ok(n) } } fn flood(agent: &ureq::Agent, pid: u32) -> Result<()> { println!("flood: POST /import/file with 1e9 lines (~45 GB)"); let line = b"lorem+ipsum+dolor+sit+amet+consectetur+adipiscing%0A".to_vec(); let mut body = Endless { prefix: b"path=flood.md&text=".to_vec(), at: 0, lines: 1_000_000_000, pos: line.len(), line }; let t = Instant::now(); let res = agent .post(&format!("{SERVER}/import/file")) .header("content-type", "application/x-www-form-urlencoded") .send(ureq::SendBody::from_reader(&mut body)); match res { Ok(r) => println!(" answered {} after {:.2}s", r.status(), t.elapsed().as_secs_f64()), Err(e) => println!(" connection ended after {:.2}s: {e}", t.elapsed().as_secs_f64()), } println!(" server rss {} MB", rss_mb(pid)); report_get(agent, "GET / after flood", &format!("{SERVER}/"))?; Ok(()) } // --------------------------------------------------------------------------- // exp: which DOM shape keeps native typing fast in a huge code block // --------------------------------------------------------------------------- fn exp(agent: &ureq::Agent, dir: &Path, only: &[String]) -> Result<()> { let lines: Vec = (0..200_000).map(|i| format!(" let rows_{i} = load_rows(state, id, 50)?;\n")).collect(); let esc = |s: &str| s.replace('&', "&").replace('<', "<"); let page = |body: String| format!("
{body}
"); let shapes: Vec<(&str, String)> = vec![ ("one text node", page(esc(&lines.concat()))), ("text node per line", String::new()), ("text node per 100 lines", String::new()), ("span per line", page(lines.iter().map(|l| format!("{}", esc(l))).collect())), ("div per line", page(lines.iter().map(|l| format!("
{}
", esc(l.trim_end_matches('\n')))).collect())), ("cv chunk per 100 lines", page(lines.chunks(100).map(|c| format!("
{}
", esc(&c.concat()))).collect())), ("cv chunk per 1000 lines", page(lines.chunks(1000).map(|c| format!("
{}
", esc(&c.concat()))).collect())), ("cv in editable div", format!("

t

{}
", lines.chunks(1000).map(|c| format!("
{}
", esc(&c.concat()))).collect::())), ("cv in div, pre overflow", format!("

t

{}
", lines.chunks(1000).map(|c| format!("
{}
", esc(&c.concat()))).collect::())), ("cv in div, 20 chunks only", format!("

t

{}
", lines[..20_000].chunks(1000).map(|c| format!("
{}
", esc(&c.concat()))).collect::())), ("plain 1000 lines", page(esc(&lines[..1000].concat()))), ("cv in div, nospell", format!("

t

{}
", lines.chunks(1000).map(|c| format!("
{}
", esc(&c.concat()))).collect::())), ("cv in div, virtual", format!("

t

{}
", lines.chunks(1000).enumerate().map(|(i, c)| if (i == 0) || (98..103).contains(&i) || i == 199 { format!("
{}
", esc(&c.concat())) } else { "
".to_owned() }).collect::())), ("p100k text", format!("
{}
", (0..100_000).map(|i| format!("

Paragraph {i} lorem ipsum dolor sit amet consectetur adipiscing elit sed do

")).collect::())), ("p100k empty", format!("
{}
", (0..100_000).map(|i| if i < 50 || (50_000..50_050).contains(&i) { format!("

Paragraph {i} lorem ipsum dolor sit amet consectetur adipiscing elit sed do

") } else { "

".to_owned() }).collect::())), ("p100k grouped", format!("
{}
", (0..100).map(|g| if g == 0 || g == 50 { format!("
{}
", (0..1000).map(|i| format!("

Paragraph {i} lorem ipsum dolor sit amet consectetur adipiscing elit sed do

")).collect::()) } else { "
".to_owned() }).collect::())), ("textarea", format!("", esc(&lines.concat()))), ]; let gecko = Kill( Command::new("geckodriver").args(["--port", DRIVER_PORT]).env("MOZ_HEADLESS", "1") .env_remove("DISPLAY").env_remove("WAYLAND_DISPLAY").stdout(Stdio::null()).stderr(Stdio::null()).spawn()?, ); wait_http(agent, &format!("http://127.0.0.1:{DRIVER_PORT}/status"))?; let s = Session::new(agent, &format!("http://127.0.0.1:{DRIVER_PORT}"), &dir.join("profile"))?; s.cmd("POST", "/timeouts", Some(json!({"script": 600_000, "pageLoad": 600_000})))?; for (name, html) in shapes { if !only.is_empty() && !only.iter().any(|o| name.contains(o.as_str())) { continue; } let html = if html.is_empty() { // Text nodes are built by script: HTML parsing merges adjacent text. let per = if name.contains("100") { 100 } else { 1 }; format!("
") } else { html }; let file = dir.join("exp.html"); std::fs::write(&file, html)?; let t = Instant::now(); s.go(&format!("file://{}", file.display()))?; let load = t.elapsed().as_secs_f64(); for (where_, frac) in [("start", 0.0), ("middle", 0.5), ("end", 1.0)] { if name == "textarea" { s.js(&format!("const t = document.querySelector('textarea'); t.focus(); const at = Math.floor(t.value.length * {frac}); t.setSelectionRange(at, at); return true"))?; s.js(LATENCY.replace("#editor .ProseMirror", "textarea").as_str())?; s.keys("textarea", "abcdefghij")?; sleep(Duration::from_millis(300)); println!("{name:<26} load {load:5.1}s {where_:<6} {}", s.js(LAT_STATS)?); continue; } s.js(&format!("const pre = document.querySelector('[contenteditable]'); pre.focus(); const code = document.querySelector('pre code').firstChild ? document.querySelector('pre') : pre; \ const w = document.createTreeWalker(code, NodeFilter.SHOW_TEXT); const all = []; let n; while ((n = w.nextNode())) all.push(n); \ const tn = all[Math.floor((all.length - 1) * {frac})]; getSelection().collapse(tn, Math.floor(tn.length * {frac})); tn.parentElement.scrollIntoView({{block: 'center'}}); return true"))?; s.js(LATENCY.replace("#editor .ProseMirror", "[contenteditable]").as_str())?; for k in "abcdefghij".chars() { s.keys("[contenteditable]", &k.to_string())?; sleep(Duration::from_millis(60)); } sleep(Duration::from_millis(300)); println!("{name:<26} load {load:5.1}s {where_:<6} {}", s.js(LAT_STATS)?); } } s.close(); drop(gecko); Ok(()) }