forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

stress.rs756 lines, 39.6 KiBHistoryRawDownload
1//! `cargo xtask stress [data|huge|flood|all] [--notes N] [--notebooks N] [--keep] [--start N]`:
2//! load tests against a release server on a scratch database, with the editor driven
3//! in headless Firefox (never on screen).
4//!
5//! - data: thousands of notebooks and many notes through the import endpoint, then the
6//! latency of the pages that list and search them.
7//! - huge: very large single notes (a 200k-line code block, 1M lorem paragraphs, ...):
8//! import, export, page size, time to editable and real keystroke latency.
9//! - billion / billion-check: a billion lines over a thousand notes on their own
10//! database (`billion.db`), imported in rounds of `--notes`, then read, searched and
11//! exported whole, with the exported zip's lines counted.
12//! - flood: an endless upload (a billion lines) must be refused without the server
13//! growing, and the server must stay responsive.
14
15use std::io::Read;
16use std::path::Path;
17use std::process::{Command, Stdio};
18use std::sync::atomic::{AtomicUsize, Ordering};
19use std::thread::sleep;
20use std::time::{Duration, Instant};
21
22use anyhow::{Context, Result, bail};
23use serde_json::{Value, json};
24
25use crate::e2e::{CAPTURE, EDITABLE, Kill, Session, agent, wait_http};
26
27const PORT: &str = "3918";
28const SERVER: &str = "http://127.0.0.1:3918";
29const DRIVER_PORT: &str = "4919";
30
31struct Opts {
32 notes: usize,
33 notebooks: usize,
34 keep: bool,
35 /// First note number of the data phase, to add more notes to a kept database.
36 start: usize,
37 build: bool,
38 only: Vec<String>,
39}
40
41pub fn run(root: &Path, target: &Path, args: &[String]) -> Result<()> {
42 let mut opts = Opts { notes: 20_000, notebooks: 2_000, keep: false, start: 0, build: true, only: Vec::new() };
43 let mut it = args.iter();
44 let mut phase = "all".to_owned();
45 while let Some(a) = it.next() {
46 match a.as_str() {
47 "--notes" => opts.notes = it.next().context("--notes N")?.parse()?,
48 "--notebooks" => opts.notebooks = it.next().context("--notebooks N")?.parse()?,
49 "--keep" => opts.keep = true,
50 "--start" => opts.start = it.next().context("--start N")?.parse()?,
51 "--no-build" => opts.build = false,
52 "--only" => opts.only.push(it.next().context("--only NAME")?.clone()),
53 p => phase = p.to_owned(),
54 }
55 }
56
57 // Builds the release server and bundles its assets next to the executable.
58 if opts.build {
59 let status = Command::new("topcoat").args(["asset", "bundle", "--release", "-p", "project_note"]).current_dir(root).status()?;
60 if !status.success() {
61 bail!("server build failed");
62 }
63 }
64 let dir = target.join("stress");
65 std::fs::create_dir_all(dir.join("profile"))?;
66 let db = if phase.starts_with("billion") { "billion.db" } else { "notes.db" };
67 if !opts.keep {
68 for f in ["", "-wal", "-shm"] {
69 let _ = std::fs::remove_file(dir.join(format!("{db}{f}")));
70 }
71 }
72 let server = Kill(
73 Command::new(target.join("release/project_note"))
74 .current_dir(root)
75 .env("NOTE_DB", dir.join(db))
76 .env("PORT", PORT)
77 .stdout(Stdio::null())
78 .spawn()
79 .context("starting the server")?,
80 );
81 let pid = server.0.id();
82 let agent = agent();
83 wait_http(&agent, &format!("{SERVER}/"))?;
84 println!("server pid {pid}, rss {} MB", rss_mb(pid));
85
86 match phase.as_str() {
87 "data" => data(&agent, &opts, pid)?,
88 "huge" => huge(&agent, &opts, &dir, pid)?,
89 "flood" => flood(&agent, pid)?,
90 "billion" => billion(&agent, &opts, pid)?,
91 "billion-check" => billion_check(&agent, &dir, pid)?,
92 "exp" => exp(&agent, &dir, &opts.only)?,
93 "all" => {
94 data(&agent, &opts, pid)?;
95 huge(&agent, &opts, &dir, pid)?;
96 flood(&agent, pid)?;
97 }
98 p => bail!("unknown phase {p}"),
99 }
100 println!("server rss at end {} MB", rss_mb(pid));
101 drop(server);
102 Ok(())
103}
104
105fn rss_mb(pid: u32) -> u64 {
106 let s = std::fs::read_to_string(format!("/proc/{pid}/status")).unwrap_or_default();
107 s.lines()
108 .find_map(|l| l.strip_prefix("VmRSS:"))
109 .and_then(|v| v.split_whitespace().next()?.parse::<u64>().ok())
110 .map_or(0, |kb| kb / 1024)
111}
112
113fn import(agent: &ureq::Agent, path: &str, text: &str) -> Result<String> {
114 let mut resp = agent.post(&format!("{SERVER}/import/file")).send_form([("path", path), ("text", text)])?;
115 let status = resp.status();
116 let body = resp.body_mut().with_config().limit(u64::MAX).read_to_string()?;
117 if !status.is_success() {
118 bail!("import {path}: {status} {}", body.chars().take(200).collect::<String>());
119 }
120 Ok(body.trim().to_owned())
121}
122
123/// GET `url`; returns (seconds, body bytes, status).
124fn timed_get(agent: &ureq::Agent, url: &str) -> Result<(f64, usize, u16)> {
125 let t = Instant::now();
126 let mut resp = agent.get(url).call()?;
127 let status = resp.status().as_u16();
128 let mut n = 0usize;
129 let mut buf = vec![0u8; 1 << 16];
130 let mut r = resp.body_mut().with_config().limit(u64::MAX).reader();
131 loop {
132 let k = r.read(&mut buf)?;
133 if k == 0 {
134 break;
135 }
136 n += k;
137 }
138 Ok((t.elapsed().as_secs_f64(), n, status))
139}
140
141fn report_get(agent: &ureq::Agent, label: &str, url: &str) -> Result<()> {
142 let mut times = Vec::new();
143 let mut size = 0;
144 for _ in 0..5 {
145 let (t, n, status) = timed_get(agent, url)?;
146 if status >= 400 {
147 bail!("{label}: HTTP {status}");
148 }
149 times.push(t * 1000.0);
150 size = n;
151 }
152 times.sort_by(f64::total_cmp);
153 println!(" {label:<28} median {:>8.1} ms max {:>8.1} ms {:>10} bytes", times[2], times[4], size);
154 Ok(())
155}
156
157// ---------------------------------------------------------------------------
158// data: many notes and notebooks
159// ---------------------------------------------------------------------------
160
161fn small_note(i: usize) -> String {
162 format!(
163 "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",
164 a = i % 97,
165 b = i % 13,
166 link = (i * 7 + 1) % (i + 1).max(1)
167 )
168}
169
170fn data(agent: &ureq::Agent, opts: &Opts, pid: u32) -> Result<()> {
171 println!("data: {} notes in {} notebooks", opts.notes, opts.notebooks);
172 let next = AtomicUsize::new(opts.start);
173 let end = opts.start + opts.notes;
174 let errors = AtomicUsize::new(0);
175 let t = Instant::now();
176 std::thread::scope(|s| {
177 for _ in 0..12 {
178 s.spawn(|| {
179 let agent = agent.clone();
180 loop {
181 let i = next.fetch_add(1, Ordering::Relaxed);
182 if i >= end {
183 break;
184 }
185 let path = format!("Notebook {}/Note {i}.md", i % opts.notebooks.max(1));
186 if let Err(e) = import(&agent, &path, &small_note(i)) {
187 if errors.fetch_add(1, Ordering::Relaxed) < 5 {
188 eprintln!(" {e}");
189 }
190 }
191 if i % 50000 == 49999 {
192 println!(" {} notes, {:.0}/s", i + 1, (i + 1 - opts.start) as f64 / t.elapsed().as_secs_f64());
193 }
194 }
195 });
196 }
197 });
198 let secs = t.elapsed().as_secs_f64();
199 println!(
200 " imported in {secs:.1}s ({:.0} notes/s), {} errors, server rss {} MB",
201 opts.notes as f64 / secs,
202 errors.load(Ordering::Relaxed),
203 rss_mb(pid)
204 );
205
206 let id = import(agent, "probe.md", "probe note")?;
207 report_get(agent, "GET / (all notes)", &format!("{SERVER}/"))?;
208 report_get(agent, "GET /unfiled", &format!("{SERVER}/unfiled"))?;
209 report_get(agent, "GET /notes/<id>", &format!("{SERVER}/notes/{id}"))?;
210 report_get(agent, "titles.json?q=Note 12", &format!("{SERVER}/notes/titles.json?q=Note%2012"))?;
211 report_get(agent, "titles.json?q=", &format!("{SERVER}/notes/titles.json?q="))?;
212 report_get(agent, "search alpha42", &format!("{SERVER}/search?q=alpha42"))?;
213 report_get(agent, "search gamma (all match)", &format!("{SERVER}/search?q=gamma"))?;
214 let nb = notebook_url(agent)?;
215 report_get(agent, "GET /notebooks/<id>", &format!("{SERVER}{nb}"))?;
216 let (t, n, _) = timed_get(agent, &format!("{SERVER}/export.zip"))?;
217 println!(" GET /export.zip {:>8.1} s {:>10} bytes, rss {} MB", t, n, rss_mb(pid));
218 Ok(())
219}
220
221// ---------------------------------------------------------------------------
222// billion: a billion lines over many notes
223// ---------------------------------------------------------------------------
224
225const BILLION_LINES_PER_NOTE: usize = 1_000_000;
226
227/// Note `i` of the billion-line set: a heading, a searchable line, then a code block.
228/// Every line of the code block and the two lines above it count.
229fn billion_note(i: usize) -> String {
230 let mut s = format!("# Billion {i}\n\nmarker{} of the billion set\n\n```\n", i % 97);
231 s.reserve(BILLION_LINES_PER_NOTE * 14);
232 for k in 0..BILLION_LINES_PER_NOTE - 2 {
233 s.push_str(" ret v");
234 s.push_str(&(k % 1000).to_string());
235 s.push('\n');
236 }
237 s + "```\n"
238}
239
240fn billion(agent: &ureq::Agent, opts: &Opts, pid: u32) -> Result<()> {
241 let end = opts.start + opts.notes;
242 println!("billion: notes {}..{end}, {} lines each", opts.start, BILLION_LINES_PER_NOTE);
243 let next = AtomicUsize::new(opts.start);
244 let errors = AtomicUsize::new(0);
245 let t = Instant::now();
246 std::thread::scope(|s| {
247 for _ in 0..4 {
248 s.spawn(|| {
249 let agent = agent.clone();
250 loop {
251 let i = next.fetch_add(1, Ordering::Relaxed);
252 if i >= end {
253 break;
254 }
255 let path = format!("Billion {}/Billion {i}.md", i % 50);
256 if let Err(e) = import(&agent, &path, &billion_note(i)) {
257 if errors.fetch_add(1, Ordering::Relaxed) < 5 {
258 eprintln!(" {e}");
259 }
260 }
261 if i % 50 == 49 {
262 println!(" {} notes, {:.1}/s, rss {} MB", i + 1, (i + 1 - opts.start) as f64 / t.elapsed().as_secs_f64(), rss_mb(pid));
263 }
264 }
265 });
266 }
267 });
268 println!(
269 " imported in {:.1}s, {} errors, server rss {} MB",
270 t.elapsed().as_secs_f64(),
271 errors.load(Ordering::Relaxed),
272 rss_mb(pid)
273 );
274 Ok(())
275}
276
277fn billion_check(agent: &ureq::Agent, dir: &Path, pid: u32) -> Result<()> {
278 println!("billion-check: server rss {} MB", rss_mb(pid));
279 report_get(agent, "GET / (all notes)", &format!("{SERVER}/"))?;
280 report_get(agent, "search marker42", &format!("{SERVER}/search?q=marker42"))?;
281 report_get(agent, "search v999 (in every line block)", &format!("{SERVER}/search?q=v999"))?;
282 report_get(agent, "search exact \"ret v999\"", &format!("{SERVER}/search?q=ret%20v999&exact=1"))?;
283 report_get(agent, "search regex absent zzq\\d+", &format!("{SERVER}/search?q=zzq%5Cd%2B&re=1"))?;
284 report_get(agent, "search regex ret v99\\d", &format!("{SERVER}/search?q=ret%20v99%5Cd&re=1"))?;
285 report_get(agent, "search regex (no literal) \\d{9}", &format!("{SERVER}/search?q=%5Cd%7B9%7D&re=1"))?;
286 report_get(agent, "search regex (no literal) v\\d{3}\\b", &format!("{SERVER}/search?q=v%5Cd%7B3%7D%5Cb&re=1"))?;
287 report_get(agent, "search regex (spans words) \\w+ \\w{9}", &format!("{SERVER}/search?q=%5Cw%2B%20%5Cw%7B9%7D&re=1"))?;
288 report_get(agent, " same, every note (all=1)", &format!("{SERVER}/search?q=%5Cw%2B%20%5Cw%7B9%7D&re=1&all=1"))?;
289 report_get(agent, "titles.json?q=Billion 7", &format!("{SERVER}/notes/titles.json?q=Billion%207"))?;
290 let nb = notebook_url(agent)?;
291 report_get(agent, "GET /notebooks/<id>", &format!("{SERVER}{nb}"))?;
292 let page = agent.get(&format!("{SERVER}{nb}")).call()?.body_mut().with_config().limit(u64::MAX).read_to_string()?;
293 let at = page.find("href=\"/notes/").context("no note link")?;
294 let rest = &page[at + 6..];
295 let note = &rest[..rest.find('"').unwrap()];
296 report_get(agent, "GET /notes/<id> (1M lines)", &format!("{SERVER}{note}"))?;
297 report_get(agent, "GET export.md (1M lines)", &format!("{SERVER}{note}/export.md"))?;
298
299 let zip = dir.join("billion.zip");
300 let t = Instant::now();
301 let mut resp = agent.get(&format!("{SERVER}/export.zip")).call()?;
302 let mut out = std::io::BufWriter::new(std::fs::File::create(&zip)?);
303 let n = std::io::copy(&mut resp.body_mut().with_config().limit(u64::MAX).reader(), &mut out)?;
304 drop(out);
305 println!(" GET /export.zip {:.1}s, {:.0} MB, rss {} MB", t.elapsed().as_secs_f64(), n as f64 / 1e6, rss_mb(pid));
306 let t = Instant::now();
307 let lines = Command::new("sh")
308 .arg("-c")
309 .arg("unzip -p \"$0\" | wc -l")
310 .arg(&zip)
311 .output()?;
312 println!(" lines in zip: {} ({:.1}s)", String::from_utf8_lossy(&lines.stdout).trim(), t.elapsed().as_secs_f64());
313 std::fs::remove_file(&zip)?;
314 Ok(())
315}
316
317fn notebook_url(agent: &ureq::Agent) -> Result<String> {
318 let html = agent.get(&format!("{SERVER}/")).call()?.body_mut().with_config().limit(u64::MAX).read_to_string()?;
319 let at = html.find("href=\"/notebooks/").context("no notebook link")?;
320 let rest = &html[at + 6..];
321 Ok(rest[..rest.find('"').unwrap()].to_owned())
322}
323
324// ---------------------------------------------------------------------------
325// huge: single very large notes
326// ---------------------------------------------------------------------------
327
328const WORDS: &[&str] = &[
329 "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor",
330 "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim", "veniam", "quis",
331];
332
333fn lorem_line(i: usize) -> String {
334 let n = 6 + i % 7;
335 let mut s = String::new();
336 for k in 0..n {
337 if k > 0 {
338 s.push(' ');
339 }
340 s.push_str(WORDS[(i * 31 + k * 7) % WORDS.len()]);
341 }
342 s
343}
344
345fn code_lines(n: usize) -> String {
346 let mut s = String::from("```rust\n");
347 for i in 0..n {
348 match i % 8 {
349 0 => s.push_str(&format!("pub fn handler_{i}(state: &State, id: u64) -> Result<Vec<Row>> {{\n")),
350 1 => s.push_str(" let rows = load_rows(state, id, 50)?;\n"),
351 2 => s.push_str(" let skipped = rows.iter().filter(|r| !r.name.is_empty()).count();\n"),
352 3 => s.push_str(" if skipped > 2000 {\n"),
353 4 => s.push_str(" return Err(anyhow!(\"too many rows: {skipped}\"));\n"),
354 5 => s.push_str(" }\n"),
355 6 => s.push_str(" Ok(rows.into_iter().map(|r| r.with_lang(\"en\")).collect())\n"),
356 _ => s.push_str("}\n"),
357 }
358 }
359 s.push_str("```\n");
360 s
361}
362
363/// The server, for RSS readings along a browser run.
364static SERVER_PID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
365
366fn server_rss() -> u64 {
367 rss_mb(SERVER_PID.load(Ordering::Relaxed))
368}
369
370fn huge(agent: &ureq::Agent, opts: &Opts, dir: &Path, pid: u32) -> Result<()> {
371 SERVER_PID.store(pid, Ordering::Relaxed);
372 let cases: Vec<(&str, Box<dyn Fn() -> String>)> = vec![
373 ("tiny", Box::new(|| (0..3).map(|i| lorem_line(i) + "\n\n").collect())),
374 ("p10k", Box::new(|| (0..10_000).map(|i| lorem_line(i) + "\n\n").collect())),
375 ("code200k", Box::new(|| code_lines(200_000))),
376 ("p100k", Box::new(|| (0..100_000).map(|i| lorem_line(i) + "\n\n").collect())),
377 ("lines1m", Box::new(|| (0..1_000_000).map(|i| lorem_line(i) + "\n").collect())),
378 ("p1m", Box::new(|| (0..1_000_000).map(|i| lorem_line(i) + "\n\n").collect())),
379 // Near the 128 MB upload limit once form-encoded: short lines, little punctuation.
380 ("code8m", Box::new(|| {
381 let mut s = String::from("```\n");
382 for i in 0..8_000_000 {
383 s.push_str(&format!(" ret v{}\n", i % 1000));
384 }
385 s + "```\n"
386 })),
387 ];
388 // The page's console (panics land there) goes to gecko.log.
389 let log = std::fs::File::create(dir.join("gecko.log"))?;
390 let gecko = Kill(
391 Command::new("geckodriver")
392 .args(["--port", DRIVER_PORT])
393 .env("MOZ_HEADLESS", "1")
394 .env_remove("DISPLAY")
395 .env_remove("WAYLAND_DISPLAY")
396 .stdout(log.try_clone()?)
397 .stderr(log)
398 .spawn()
399 .context("starting geckodriver")?,
400 );
401 wait_http(agent, &format!("http://127.0.0.1:{DRIVER_PORT}/status"))?;
402 let session = Session::new(agent, &format!("http://127.0.0.1:{DRIVER_PORT}"), &dir.join("profile"))?;
403 session.cmd("POST", "/timeouts", Some(json!({"script": 600_000, "pageLoad": 600_000})))?;
404 let result = (|| -> Result<()> {
405 for (name, make) in &cases {
406 if !opts.only.is_empty() && !opts.only.iter().any(|o| o == name) {
407 continue;
408 }
409 let text = make();
410 println!("huge {name}: {} lines, {:.1} MB", text.lines().count(), text.len() as f64 / 1e6);
411 let t = Instant::now();
412 let id = match import(agent, &format!("{name}.md"), &text) {
413 Ok(id) => id,
414 Err(e) => {
415 println!(" import failed after {:.1}s: {e}", t.elapsed().as_secs_f64());
416 continue;
417 }
418 };
419 println!(" import {:.2}s, server rss {} MB", t.elapsed().as_secs_f64(), rss_mb(pid));
420 let note = format!("{SERVER}/notes/{id}");
421 let (t, n, _) = timed_get(agent, &format!("{note}/export.md"))?;
422 println!(" export.md {:.2}s {:.1} MB", t, n as f64 / 1e6);
423 let (t, n, _) = timed_get(agent, &note)?;
424 println!(" page html {:.2}s {:.1} MB", t, n as f64 / 1e6);
425 browse(agent, &session, &note, name, dir)?;
426 let t = Instant::now();
427 session.go(&note)?;
428 session.wait_for(EDITABLE, "editable", 600)?;
429 println!(" reopen: editable after {:.2}s", t.elapsed().as_secs_f64());
430 println!(" server rss {} MB", rss_mb(pid));
431 // Kept DBs would otherwise gain 100+ MB per run.
432 session.go(&format!("{SERVER}/"))?;
433 agent.post(&format!("{note}/trash")).send_empty()?;
434 agent.post(&format!("{SERVER}/trash/empty")).send_empty()?;
435 }
436 Ok(())
437 })();
438 session.close();
439 drop(gecko);
440 result
441}
442
443/// Records, for each real keydown, the main-thread time it costs: our event handlers up
444/// to the next frame plus that frame (rAF callbacks, style, layout, paint) until a timer
445/// after it runs. `__raw` keeps keydown to that timer, which adds the idle wait for the
446/// browser's 60 Hz frame clock (0 to 16.7 ms, set by when the key happens to land).
447const LATENCY: &str = "window.__lat = []; window.__raw = []; if (!window.__latOn) { window.__latOn = true; let cur = null; \
448 for (const t of ['keydown', 'beforeinput', 'input', 'selectionchange']) { let s = 0; \
449 window.addEventListener(t, () => { s = performance.now(); if (t !== 'keydown') return; const c = cur = {t0: s, busy: 0}; \
450 requestAnimationFrame(() => { const t2 = performance.now(); if (cur === c) cur = null; \
451 setTimeout(() => { const t3 = performance.now(); __raw.push(t3 - c.t0); __lat.push(c.busy + t3 - t2); }, 0); }); }, true); \
452 window.addEventListener(t, () => { if (cur) cur.busy += performance.now() - s; }, false); } } return true";
453
454/// Splits the time: our handlers per event type (capture to bubble on window), rAF and
455/// timer callbacks, and the rest (browser style, layout and paint).
456const PROFILE: &str = "if (!window.__prof) { const P = window.__prof = {ev: {}, raf: 0, rafN: 0, tm: 0, tmN: 0}; \
457 for (const t of ['keydown', 'beforeinput', 'input', 'keyup', 'selectionchange', 'compositionend']) { let s = 0; \
458 window.addEventListener(t, () => { s = performance.now(); }, true); \
459 window.addEventListener(t, () => { const d = performance.now() - s; P.ev[t] = (P.ev[t] || 0) + d; }, false); } \
460 { 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); } \
461 const raf = window.requestAnimationFrame.bind(window); window.requestAnimationFrame = cb => raf(ts => { const s = performance.now(); cb(ts); P.raf += performance.now() - s; P.rafN++; }); \
462 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); } \
463 const P = window.__prof; P.ev = {}; P.raf = 0; P.rafN = 0; P.tm = 0; P.tmN = 0; return true";
464
465const PROF_STATS: &str = "const P = window.__prof; const r = x => +x.toFixed(1); const ev = {}; \
466 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}";
467
468/// Each key's time, then with the frame wait.
469const SERIES: &str = "const f = a => a.map(x => Math.round(x)).join(' '); return `${f(__lat)} | wait incl. ${f(__raw)}`";
470
471const LAT_STATS: &str = "const t = [...__lat].sort((a, b) => a - b); if (!t.length) return null; \
472 return {n: t.length, avg: +(t.reduce((a, b) => a + b, 0) / t.length).toFixed(2), p50: +t[t.length >> 1].toFixed(2), \
473 p95: +t[Math.floor(t.length * 0.95)].toFixed(2), max: +t[t.length - 1].toFixed(2)}";
474
475fn caret_at_block(s: &Session, frac: f64) -> Result<Value> {
476 // Scroll to `frac` of the editor's height (as a person would with the scrollbar);
477 // only blocks near the viewport are in the DOM, built on the next frames.
478 let n = s.js(&format!(
479 "const r = document.querySelector('#editor .ProseMirror'); r.focus(); \
480 let sc = r.parentElement; \
481 while (sc && !(sc.scrollHeight > sc.clientHeight && /(auto|scroll)/.test(getComputedStyle(sc).overflowY))) sc = sc.parentElement; \
482 sc = sc || document.scrollingElement; \
483 const top = sc === document.scrollingElement ? 0 : sc.getBoundingClientRect().top; \
484 const rr = r.getBoundingClientRect(); \
485 sc.scrollTop += rr.top - top + rr.height * {frac} - sc.clientHeight / 2; \
486 return r.querySelectorAll('p, pre, li, h1, h2, h3').length"
487 ))?;
488 sleep(Duration::from_millis(400));
489 // Units in document order among what is built: blocks, long ones chunk by chunk.
490 s.js(&format!(
491 "const r = document.querySelector('#editor .ProseMirror'); const units = []; \
492 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); }} \
493 const u = units[Math.floor((units.length - 1) * {frac})]; \
494 const w = document.createTreeWalker(u, NodeFilter.SHOW_TEXT); const tn = w.nextNode(); \
495 if (tn) getSelection().collapse(tn, Math.min(5, tn.length)); else getSelection().collapse(u, 0); return true"
496 ))?;
497 Ok(n)
498}
499
500fn keys_latency(s: &Session, keys: &str) -> Result<Value> {
501 s.js(LATENCY)?;
502 s.js(PROFILE)?;
503 // One key at a time, ~16 keys/s like a fast typist: a burst would queue keys behind
504 // each other and measure throughput instead of latency.
505 for k in keys.chars() {
506 s.keys("#editor .ProseMirror", &k.to_string())?;
507 sleep(Duration::from_millis(60));
508 }
509 sleep(Duration::from_millis(300));
510 let mut v = s.js(LAT_STATS)?;
511 v["with_frame_wait"] = s.js(&LAT_STATS.replace("__lat", "__raw"))?;
512 v["profile"] = s.js(PROF_STATS)?;
513 Ok(v)
514}
515
516fn browse(agent: &ureq::Agent, s: &Session, note: &str, name: &str, dir: &Path) -> Result<()> {
517 let t = Instant::now();
518 s.go(note)?;
519 let loaded = t.elapsed().as_secs_f64();
520 if let Err(e) = s.wait_for(EDITABLE, "editable", 600) {
521 println!(" browser: {e}");
522 return Ok(());
523 }
524 println!(" browser: load {loaded:.2}s, editable after {:.2}s, server rss {} MB", t.elapsed().as_secs_f64(), server_rss());
525 s.js(CAPTURE)?;
526 let blocks = caret_at_block(s, 0.5)?;
527 sleep(Duration::from_millis(500));
528 println!(" blocks in DOM {blocks}, {}", s.js("const c = document.querySelectorAll('.code-chunk, .text-chunk'); \
529 return c.length ? `${c.length} code chunks, ${getComputedStyle(c[0]).contentVisibility}, ${getComputedStyle(c[0]).containIntrinsicHeight}` : 'no code chunks'")?);
530 const MID: &str = "alpha bravo charlie delta echo foxtrot ";
531 const END: &str = "golf hotel india juliet kilo lima mike ";
532 const START: &str = "november oscar papa quebec romeo sierra";
533 let at_mid = s.js("const s = getSelection(); return s.anchorNode && s.anchorNode.textContent.slice(Math.max(0, s.anchorOffset - 20), s.anchorOffset)")?;
534 println!(" type 40 chars mid {}", keys_latency(s, MID)?);
535 // 40 presses: of 10, the 95th percentile would be the slowest one.
536 println!(" enter x40 mid {}", keys_latency(s, &"\u{E007}".repeat(40))?);
537 println!(" series {}", s.js(SERIES)?);
538 println!(" backspace x40 mid {}", keys_latency(s, &"\u{E003}".repeat(40))?);
539 println!(" series {}", s.js(SERIES)?);
540 // STRESS_PROBE="label=js;;label=js": run each snippet, then time typing again (bisecting).
541 if let Ok(probe) = std::env::var("STRESS_PROBE") {
542 for step in probe.split(";;") {
543 let (label, js) = step.split_once('=').unwrap_or((step, ""));
544 s.js(&format!("{js}; return true"))?;
545 caret_at_block(s, 0.5)?;
546 sleep(Duration::from_millis(300));
547 println!(" probe {label:<20} {}", keys_latency(s, "abcdefghijklmnopqrst")?);
548 println!(" series {}", s.js(SERIES)?);
549 }
550 }
551 caret_at_block(s, 1.0)?;
552 sleep(Duration::from_millis(300));
553 let at_end = s.js("const s = getSelection(); return s.anchorNode && s.anchorNode.textContent.slice(Math.max(0, s.anchorOffset - 20), s.anchorOffset)")?;
554 println!(" type 40 chars end {}", keys_latency(s, END)?);
555 caret_at_block(s, 0.0)?;
556 sleep(Duration::from_millis(300));
557 let at_start = s.js("const s = getSelection(); return s.anchorNode && s.anchorNode.textContent.slice(Math.max(0, s.anchorOffset - 20), s.anchorOffset)")?;
558 println!(" type 40 chars start {}", keys_latency(s, START)?);
559 println!(" after typing: server rss {} MB", server_rss());
560 // The model must hold each typed string once, right after where the caret was.
561 // The server applies updates a moment after the client sent them: wait for all
562 // three strings (a lost keystroke still shows as WRONG after the deadline).
563 let waited = Instant::now();
564 let mut md;
565 loop {
566 sleep(Duration::from_millis(250));
567 md = agent.get(&format!("{note}/export.md")).call()?.body_mut().with_config().limit(u64::MAX).read_to_string()?;
568 if [MID, END, START].iter().all(|x| md.contains(x)) || waited.elapsed() > Duration::from_secs(15) {
569 break;
570 }
571 }
572 println!(" server has the edits after {:.2}s, server rss {} MB", waited.elapsed().as_secs_f64(), server_rss());
573 println!(
574 " sync state {}, export {} MB, errors so far {}",
575 s.js("const e = document.querySelector('[data-state]'); return e && e.dataset.state")?,
576 md.len() >> 20,
577 s.js("return __log.filter(l => l.startsWith('error') || l.startsWith('uncaught')).length")?
578 );
579 for (what, text, before) in [("mid", MID, &at_mid), ("end", END, &at_end), ("start", START, &at_start)] {
580 let found: Vec<usize> = md.match_indices(text).map(|(i, _)| i).collect();
581 let ok = found.len() == 1 && before.as_str().is_some_and(|b| md[..found[0]].ends_with(b));
582 let ctx = found.first().map(|&i| md[i.saturating_sub(30)..(i + text.len() + 10).min(md.len())].replace('\n', "⏎")).unwrap_or_default();
583 let line = found.first().map_or(0, |&i| md[..i].matches('\n').count() + 1);
584 println!(" check {what:<5} {} (found {}x at line {line}, caret after {before}) …{ctx}…", if ok { "ok" } else { "WRONG" }, found.len());
585 if found.is_empty() {
586 let head: String = md.chars().take(160).collect();
587 println!(" export starts {:?}; dom starts {}", head, s.js("return document.querySelector('#editor .ProseMirror').textContent.slice(0, 160)")?);
588 }
589 }
590 // Select all, delete, undo: the heaviest structural edits.
591 let ops = s.js(
592 "const r = document.querySelector('#editor .ProseMirror'); r.focus(); \
593 const ev = (k, c, mod) => r.dispatchEvent(new KeyboardEvent('keydown', {key: k, code: c, ctrlKey: mod, cancelable: true, bubbles: true})); \
594 const time = f => { const s = performance.now(); f(); return +(performance.now() - s).toFixed(1); }; \
595 const all = time(() => ev('a', 'KeyA', true)); \
596 const del = time(() => ev('Backspace', 'Backspace', false)); \
597 const after = r.scrollHeight; \
598 const undo = time(() => ev('z', 'KeyZ', true)); \
599 return {select_all_ms: all, delete_ms: del, height_after_delete: after, undo_ms: undo, height_after_undo: r.scrollHeight}",
600 )?;
601 println!(" {ops}");
602 sleep(Duration::from_millis(3000));
603 println!(" after undo + 3 s: server rss {} MB", server_rss());
604 std::thread::sleep(Duration::from_millis(1500));
605 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}")?);
606 let _ = s.screenshot(&dir.join(format!("{name}.png")));
607 let err = s.js("return window.__log ? __log.filter(l => l.startsWith('error') || l.startsWith('uncaught')).slice(0, 40) : []")?;
608 if err.as_array().is_some_and(|a| !a.is_empty()) {
609 println!(" console errors: {err}");
610 }
611 Ok(())
612}
613
614// ---------------------------------------------------------------------------
615// flood: an upload that never ends
616// ---------------------------------------------------------------------------
617
618/// A urlencoded form body with `lines` lorem lines, produced on the fly.
619struct Endless {
620 prefix: Vec<u8>,
621 at: usize,
622 lines: u64,
623 line: Vec<u8>,
624 pos: usize,
625}
626
627impl Read for Endless {
628 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
629 if self.at < self.prefix.len() {
630 let n = (self.prefix.len() - self.at).min(buf.len());
631 buf[..n].copy_from_slice(&self.prefix[self.at..self.at + n]);
632 self.at += n;
633 return Ok(n);
634 }
635 let mut n = 0;
636 while n < buf.len() {
637 if self.pos == self.line.len() {
638 if self.lines == 0 {
639 break;
640 }
641 self.lines -= 1;
642 self.pos = 0;
643 }
644 let k = (self.line.len() - self.pos).min(buf.len() - n);
645 buf[n..n + k].copy_from_slice(&self.line[self.pos..self.pos + k]);
646 self.pos += k;
647 n += k;
648 }
649 Ok(n)
650 }
651}
652
653fn flood(agent: &ureq::Agent, pid: u32) -> Result<()> {
654 println!("flood: POST /import/file with 1e9 lines (~45 GB)");
655 let line = b"lorem+ipsum+dolor+sit+amet+consectetur+adipiscing%0A".to_vec();
656 let mut body = Endless { prefix: b"path=flood.md&text=".to_vec(), at: 0, lines: 1_000_000_000, pos: line.len(), line };
657 let t = Instant::now();
658 let res = agent
659 .post(&format!("{SERVER}/import/file"))
660 .header("content-type", "application/x-www-form-urlencoded")
661 .send(ureq::SendBody::from_reader(&mut body));
662 match res {
663 Ok(r) => println!(" answered {} after {:.2}s", r.status(), t.elapsed().as_secs_f64()),
664 Err(e) => println!(" connection ended after {:.2}s: {e}", t.elapsed().as_secs_f64()),
665 }
666 println!(" server rss {} MB", rss_mb(pid));
667 report_get(agent, "GET / after flood", &format!("{SERVER}/"))?;
668 Ok(())
669}
670
671
672// ---------------------------------------------------------------------------
673// exp: which DOM shape keeps native typing fast in a huge code block
674// ---------------------------------------------------------------------------
675
676fn exp(agent: &ureq::Agent, dir: &Path, only: &[String]) -> Result<()> {
677 let lines: Vec<String> = (0..200_000).map(|i| format!(" let rows_{i} = load_rows(state, id, 50)?;\n")).collect();
678 let esc = |s: &str| s.replace('&', "&amp;").replace('<', "&lt;");
679 let page = |body: String| format!("<!DOCTYPE html><html><body><pre contenteditable=true style='white-space:pre'><code>{body}</code></pre></body></html>");
680 let shapes: Vec<(&str, String)> = vec![
681 ("one text node", page(esc(&lines.concat()))),
682 ("text node per line", String::new()),
683 ("text node per 100 lines", String::new()),
684 ("span per line", page(lines.iter().map(|l| format!("<span>{}</span>", esc(l))).collect())),
685 ("div per line", page(lines.iter().map(|l| format!("<div>{}</div>", esc(l.trim_end_matches('\n')))).collect())),
686 ("cv chunk per 100 lines", page(lines.chunks(100).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto 1px auto 1500px'>{}</div>", esc(&c.concat()))).collect())),
687 ("cv chunk per 1000 lines", page(lines.chunks(1000).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto 1px auto 15000px'>{}</div>", esc(&c.concat()))).collect())),
688 ("cv in editable div", format!("<!DOCTYPE html><html><body><div contenteditable=true><h1>t</h1><pre><code style='display:block'>{}</code></pre></div></body></html>",
689 lines.chunks(1000).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto none auto 22000px'>{}</div>", esc(&c.concat()))).collect::<String>())),
690 ("cv in div, pre overflow", format!("<!DOCTYPE html><html><body><div contenteditable=true><h1>t</h1><pre style='overflow-x:auto;line-height:22px'><code style='display:block'>{}</code></pre></div></body></html>",
691 lines.chunks(1000).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto none auto 22000px'>{}</div>", esc(&c.concat()))).collect::<String>())),
692 ("cv in div, 20 chunks only", format!("<!DOCTYPE html><html><body><div contenteditable=true><h1>t</h1><pre style='overflow-x:auto;line-height:22px'><code style='display:block'>{}</code></pre></div></body></html>",
693 lines[..20_000].chunks(1000).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto none auto 22000px'>{}</div>", esc(&c.concat()))).collect::<String>())),
694 ("plain 1000 lines", page(esc(&lines[..1000].concat()))),
695 ("cv in div, nospell", format!("<!DOCTYPE html><html><body><div contenteditable=true spellcheck=false><h1>t</h1><pre style='overflow-x:auto;line-height:22px'><code style='display:block'>{}</code></pre></div></body></html>",
696 lines.chunks(1000).map(|c| format!("<div style='content-visibility:auto;contain-intrinsic-size:auto none auto 22000px'>{}</div>", esc(&c.concat()))).collect::<String>())),
697 ("cv in div, virtual", format!("<!DOCTYPE html><html><body><div contenteditable=true><h1>t</h1><pre style='overflow-x:auto;line-height:22px'><code style='display:block'>{}</code></pre></div></body></html>",
698 lines.chunks(1000).enumerate().map(|(i, c)| if (i == 0) || (98..103).contains(&i) || i == 199 { format!("<div style='height:22000px'>{}</div>", esc(&c.concat())) } else { "<div style='height:22000px'></div>".to_owned() }).collect::<String>())),
699 ("p100k text", format!("<!DOCTYPE html><html><body><div contenteditable=true><pre><code></code></pre>{}</div></body></html>",
700 (0..100_000).map(|i| format!("<p>Paragraph {i} lorem ipsum dolor sit amet consectetur adipiscing elit sed do</p>")).collect::<String>())),
701 ("p100k empty", format!("<!DOCTYPE html><html><body><div contenteditable=true><pre><code></code></pre>{}</div></body></html>",
702 (0..100_000).map(|i| if i < 50 || (50_000..50_050).contains(&i) { format!("<p>Paragraph {i} lorem ipsum dolor sit amet consectetur adipiscing elit sed do</p>") } else { "<p style='height:28px'></p>".to_owned() }).collect::<String>())),
703 ("p100k grouped", format!("<!DOCTYPE html><html><body><div contenteditable=true><pre><code></code></pre>{}</div></body></html>",
704 (0..100).map(|g| if g == 0 || g == 50 { format!("<div>{}</div>", (0..1000).map(|i| format!("<p>Paragraph {i} lorem ipsum dolor sit amet consectetur adipiscing elit sed do</p>")).collect::<String>()) } else { "<div style='height:28000px'></div>".to_owned() }).collect::<String>())),
705 ("textarea", format!("<!DOCTYPE html><html><body><textarea style='width:90vw;height:90vh'>{}</textarea></body></html>", esc(&lines.concat()))),
706 ];
707 let gecko = Kill(
708 Command::new("geckodriver").args(["--port", DRIVER_PORT]).env("MOZ_HEADLESS", "1")
709 .env_remove("DISPLAY").env_remove("WAYLAND_DISPLAY").stdout(Stdio::null()).stderr(Stdio::null()).spawn()?,
710 );
711 wait_http(agent, &format!("http://127.0.0.1:{DRIVER_PORT}/status"))?;
712 let s = Session::new(agent, &format!("http://127.0.0.1:{DRIVER_PORT}"), &dir.join("profile"))?;
713 s.cmd("POST", "/timeouts", Some(json!({"script": 600_000, "pageLoad": 600_000})))?;
714 for (name, html) in shapes {
715 if !only.is_empty() && !only.iter().any(|o| name.contains(o.as_str())) {
716 continue;
717 }
718 let html = if html.is_empty() {
719 // Text nodes are built by script: HTML parsing merges adjacent text.
720 let per = if name.contains("100") { 100 } else { 1 };
721 format!("<!DOCTYPE html><html><body><pre contenteditable=true style='white-space:pre'><code></code></pre><script>\
722 const c = document.querySelector('code'); const L = []; for (let i = 0; i < 200000; i++) L.push(' let rows_' + i + ' = load_rows(state, id, 50)?;\\n'); \
723 for (let i = 0; i < L.length; i += {per}) c.appendChild(document.createTextNode(L.slice(i, i + {per}).join('')));</script></body></html>")
724 } else {
725 html
726 };
727 let file = dir.join("exp.html");
728 std::fs::write(&file, html)?;
729 let t = Instant::now();
730 s.go(&format!("file://{}", file.display()))?;
731 let load = t.elapsed().as_secs_f64();
732 for (where_, frac) in [("start", 0.0), ("middle", 0.5), ("end", 1.0)] {
733 if name == "textarea" {
734 s.js(&format!("const t = document.querySelector('textarea'); t.focus(); const at = Math.floor(t.value.length * {frac}); t.setSelectionRange(at, at); return true"))?;
735 s.js(LATENCY.replace("#editor .ProseMirror", "textarea").as_str())?;
736 s.keys("textarea", "abcdefghij")?;
737 sleep(Duration::from_millis(300));
738 println!("{name:<26} load {load:5.1}s {where_:<6} {}", s.js(LAT_STATS)?);
739 continue;
740 }
741 s.js(&format!("const pre = document.querySelector('[contenteditable]'); pre.focus(); const code = document.querySelector('pre code').firstChild ? document.querySelector('pre') : pre; \
742 const w = document.createTreeWalker(code, NodeFilter.SHOW_TEXT); const all = []; let n; while ((n = w.nextNode())) all.push(n); \
743 const tn = all[Math.floor((all.length - 1) * {frac})]; getSelection().collapse(tn, Math.floor(tn.length * {frac})); tn.parentElement.scrollIntoView({{block: 'center'}}); return true"))?;
744 s.js(LATENCY.replace("#editor .ProseMirror", "[contenteditable]").as_str())?;
745 for k in "abcdefghij".chars() {
746 s.keys("[contenteditable]", &k.to_string())?;
747 sleep(Duration::from_millis(60));
748 }
749 sleep(Duration::from_millis(300));
750 println!("{name:<26} load {load:5.1}s {where_:<6} {}", s.js(LAT_STATS)?);
751 }
752 }
753 s.close();
754 drop(gecko);
755 Ok(())
756}