//! `cargo xtask e2e`: drives the editor in headless Firefox through geckodriver. //! Starts the server on a scratch database; nothing is shown on screen //! (`-headless`, and DISPLAY/WAYLAND_DISPLAY are removed for the browser). use std::io::Read; use std::path::Path; use std::process::{Child, Command, Stdio}; use std::thread::sleep; use std::time::{Duration, Instant}; use anyhow::{Context, Result, bail}; use serde_json::{Value, json}; const SERVER: &str = "http://127.0.0.1:3917"; const ELEMENT: &str = "element-6066-11e4-a52e-4f735466cecf"; const ENTER: &str = "\u{E007}"; const BACKSPACE: &str = "\u{E003}"; const CONTROL: &str = "\u{E009}"; pub(crate) struct Kill(pub(crate) Child); impl Drop for Kill { fn drop(&mut self) { let _ = self.0.kill(); let _ = self.0.wait(); } } pub(crate) fn agent() -> ureq::Agent { ureq::Agent::config_builder().http_status_as_error(false).build().into() } pub(crate) struct Session { agent: ureq::Agent, driver: String, id: String, } impl Session { pub(crate) fn new(agent: &ureq::Agent, driver: &str, profile_dir: &Path) -> Result { let caps = json!({"capabilities": {"alwaysMatch": { "browserName": "firefox", "moz:firefoxOptions": { "args": ["-headless", "-profile", profile_dir.to_str().unwrap()], // Page console output goes to geckodriver's log (see `run`). "prefs": { "devtools.console.stdout.content": true, "media.navigator.streams.fake": true, "media.navigator.permission.disabled": true } } }}}); let v = call(agent, "POST", &format!("{driver}/session"), Some(caps))?; let id = v["sessionId"].as_str().context("no session id")?.to_owned(); Ok(Session { agent: agent.clone(), driver: driver.to_owned(), id }) } pub(crate) fn cmd(&self, method: &str, path: &str, body: Option) -> Result { call(&self.agent, method, &format!("{}/session/{}{path}", self.driver, self.id), body) } pub(crate) fn go(&self, url: &str) -> Result<()> { self.cmd("POST", "/url", Some(json!({"url": url})))?; Ok(()) } pub(crate) fn js(&self, script: &str) -> Result { self.cmd("POST", "/execute/sync", Some(json!({"script": script, "args": []}))) } fn wait(&self, script: &str, what: &str) -> Result<()> { self.wait_for(script, what, 15) } pub(crate) fn wait_for(&self, script: &str, what: &str, secs: u64) -> Result<()> { let t = Instant::now(); while t.elapsed() < Duration::from_secs(secs) { if self.js(script)? == Value::Bool(true) { return Ok(()); } sleep(Duration::from_millis(100)); } bail!("timed out waiting for {what}") } pub(crate) fn keys(&self, css: &str, text: &str) -> Result<()> { let el = self.cmd("POST", "/element", Some(json!({"using": "css selector", "value": css})))?; let id = el[ELEMENT].as_str().context("element not found")?; self.cmd("POST", &format!("/element/{id}/value"), Some(json!({"text": text})))?; Ok(()) } pub(crate) fn screenshot(&self, path: &Path) -> Result<()> { let v = self.cmd("GET", "/screenshot", None)?; let b64 = v.as_str().context("no screenshot")?; std::fs::write(path, decode_b64(b64))?; Ok(()) } pub(crate) fn close(&self) { let _ = self.cmd("DELETE", "", None); } } fn call(agent: &ureq::Agent, method: &str, url: &str, body: Option) -> Result { let mut resp = match method { "POST" => agent.post(url).send_json(body.unwrap_or(json!({})))?, "DELETE" => agent.delete(url).call()?, _ => agent.get(url).call()?, }; let v: Value = resp.body_mut().read_json()?; if let Some(err) = v["value"].get("error") { bail!("webdriver {method} {url}: {err} {}", v["value"]["message"]); } Ok(v["value"].clone()) } fn decode_b64(s: &str) -> Vec { let val = |c: u8| match c { b'A'..=b'Z' => c - b'A', b'a'..=b'z' => c - b'a' + 26, b'0'..=b'9' => c - b'0' + 52, b'+' => 62, _ => 63, }; let bytes: Vec = s.bytes().filter(|&c| c != b'=' && !c.is_ascii_whitespace()).map(val).collect(); let mut out = Vec::with_capacity(bytes.len() * 3 / 4); for ch in bytes.chunks(4) { let n = ch.iter().enumerate().fold(0u32, |n, (i, &b)| n | (b as u32) << (18 - 6 * i)); for i in 0..ch.len().saturating_sub(1) { out.push((n >> (16 - 8 * i)) as u8); } } out } pub(crate) fn wait_http(agent: &ureq::Agent, url: &str) -> Result<()> { let t = Instant::now(); while t.elapsed() < Duration::from_secs(30) { if agent.get(url).call().is_ok() { return Ok(()); } sleep(Duration::from_millis(200)); } bail!("{url} did not come up") } pub(crate) const CAPTURE: &str = "window.__log = []; for (const k of ['error', 'warn', 'log']) { const o = console[k]; \ console[k] = (...a) => { __log.push(k + ': ' + a.join(' ')); o(...a) } } \ addEventListener('error', e => __log.push('uncaught: ' + e.message)); \ for (const t of ['keydown', 'beforeinput', 'input']) document.addEventListener(t, e => \ __log.push(t + ':' + (e.inputType || e.key) + (e.defaultPrevented ? '!' : '')), true); return true"; pub(crate) const EDITABLE: &str = "return document.querySelector('#editor .ProseMirror')?.contentEditable === 'true'"; const CARET_END: &str = "const r = document.querySelector('#editor .ProseMirror'); r.focus(); \ const s = getSelection(); s.selectAllChildren(r); s.collapseToEnd(); return true"; /// The server on the scratch database. `run` and the restart in `media` both start it this way. fn spawn_server(root: &Path, target: &Path, dir: &Path) -> Result { Ok(Kill( Command::new(target.join("debug/project_note")) .current_dir(root) .env("NOTE_DB", dir.join("notes.db")) .env("NOTE_MEDIA", dir.join("media")) .env("PORT", "3917") .stdout(Stdio::null()) .spawn() .context("starting the server")?, )) } pub fn run(root: &Path, target: &Path) -> Result<()> { // Builds the server and bundles its assets next to the executable. let status = Command::new("topcoat") .args(["asset", "bundle", "-p", "project_note"]) .current_dir(root) .status()?; if !status.success() { bail!("server build failed"); } let dir = target.join("e2e"); let _ = std::fs::remove_file(dir.join("notes.db")); let _ = std::fs::remove_dir_all(dir.join("media/rec")); std::fs::create_dir_all(dir.join("profile-a"))?; std::fs::create_dir_all(dir.join("profile-b"))?; let start = || spawn_server(root, target, &dir); let mut server = start()?; // geckodriver runs one session per process: one per client. let gecko = |port: &str| -> Result { let log = std::fs::File::create(dir.join(format!("gecko-{port}.log")))?; Ok(Kill( Command::new("geckodriver") .args(["--port", port]) .env("MOZ_HEADLESS", "1") .env_remove("DISPLAY") .env_remove("WAYLAND_DISPLAY") .stdout(log.try_clone()?) .stderr(log) .spawn() .context("starting geckodriver (cargo install geckodriver)")?, )) }; let drivers = [gecko("4917")?, gecko("4918")?]; let agent = agent(); wait_http(&agent, &format!("{SERVER}/"))?; for port in ["4917", "4918"] { wait_http(&agent, &format!("http://127.0.0.1:{port}/status"))?; } let id = agent .post(&format!("{SERVER}/notes/quick")) .send_form([("title", "E2E")])? .body_mut() .read_to_string()? .trim() .to_owned(); let note = format!("{SERVER}/notes/{id}"); println!("note {id}"); let a = Session::new(&agent, "http://127.0.0.1:4917", &dir.join("profile-a"))?; let result = scenario(&agent, &a, ¬e, &dir) .and_then(|_| media(&agent, &a, &dir, &mut server, &start)) .and_then(|_| code(&agent, &a, &dir)) .and_then(|_| perf(&agent, &a)); let _ = a.screenshot(&dir.join("a.png")); if let Ok(log) = a.js("return window.__log") { println!("console: {log}"); } if let Ok(html) = a.js("return document.querySelector('#editor .ProseMirror').innerHTML") { println!("dom: {}", html.as_str().unwrap_or_default()); } a.close(); drop(drivers); drop(server); if result.is_err() { // The page's console (panics land there), from the first client's browser. let log = std::fs::read_to_string(dir.join("gecko-4917.log")).unwrap_or_default(); for l in log.lines().filter(|l| l.starts_with("console.") || l.contains("JavaScript") || l.contains("panicked")).take(40) { println!("browser: {l}"); } } result?; println!("e2e ok (screenshot in {})", dir.join("a.png").display()); Ok(()) } fn markdown(agent: &ureq::Agent, note: &str) -> Result { Ok(agent.get(&format!("{note}/export.md")).call()?.body_mut().read_to_string()?) } fn expect_md(agent: &ureq::Agent, note: &str, want: &str) -> Result<()> { let t = Instant::now(); let mut got = String::new(); while t.elapsed() < Duration::from_secs(5) { got = markdown(agent, note)?; if got.trim() == want.trim() { return Ok(()); } sleep(Duration::from_millis(200)); } bail!("markdown mismatch\n--- want\n{want}\n--- got\n{got}") } fn scenario(agent: &ureq::Agent, a: &Session, note: &str, dir: &Path) -> Result<()> { let ed = "#editor .ProseMirror"; a.go(note)?; a.wait(EDITABLE, "the editor to become editable")?; a.js(CAPTURE)?; a.js(CARET_END)?; a.keys(ed, &format!("{ENTER}hello world{ENTER}- item one{ENTER}item two{ENTER}{ENTER}**bold** done"))?; expect_md(agent, note, "# E2E\n\nhello world\n\n- item one\n- item two\n\n**bold** done")?; // Deleting is its own undo step once typing has paused past the merge interval. sleep(Duration::from_millis(1200)); a.js(CARET_END)?; a.keys(ed, &BACKSPACE.repeat(5))?; expect_md(agent, note, "# E2E\n\nhello world\n\n- item one\n- item two\n\n**bold**")?; a.keys(ed, &format!("{CONTROL}z{CONTROL}"))?; expect_md(agent, note, "# E2E\n\nhello world\n\n- item one\n- item two\n\n**bold** done")?; // A second client sees the same content. let b = Session::new(agent, "http://127.0.0.1:4918", &dir.join("profile-b"))?; let seen = (|| -> Result<()> { b.go(note)?; b.wait(EDITABLE, "the second editor")?; b.wait( "return document.querySelector('#editor .ProseMirror').textContent.includes('bold done')", "the second client to show the text", )?; b.js(CARET_END)?; b.keys(ed, " from b")?; a.wait( "return document.querySelector('#editor .ProseMirror').textContent.includes('done from b')", "the first client to see the second's edit", ) })(); b.close(); seen } const MEASURE: &str = "const root = document.querySelector('#editor .ProseMirror'); \ const mo = new MutationObserver(() => {}); \ mo.observe(root, {subtree: true, childList: true, characterData: true, attributes: true}); \ const run = (n, f) => { const t = []; let m = 0; for (let i = 0; i < n; i++) { \ const s = performance.now(); f(); t.push(performance.now() - s); m += mo.takeRecords().length; } \ t.sort((a, b) => a - b); \ return {avg: t.reduce((a, b) => a + b, 0) / n, p95: t[Math.floor(n * 0.95)], mutations_per_op: m / n}; }; \ const type = run(50, () => root.dispatchEvent(new InputEvent('beforeinput', \ {inputType: 'insertText', data: ' ', cancelable: true, bubbles: true}))); \ const enter = run(20, () => root.dispatchEvent(new KeyboardEvent('keydown', \ {key: 'Enter', code: 'Enter', cancelable: true, bubbles: true}))); \ mo.disconnect(); \ return {type, enter, blocks: root.querySelectorAll(':scope > .pm-page > *').length}"; const AUDIOS: &str = "document.querySelectorAll('#editor audio.note-media').length"; const RECORD: &str = "document.querySelector('[data-command=record]').click(); return true"; const TAKES: &str = "document.querySelectorAll('#editor .note-take').length"; const RECS: &str = "document.querySelectorAll('#editor audio[src^=\"/media/rec/\"]').length"; /// The state of the note's last take. const TAKE_STATE: &str = "[...document.querySelectorAll('#editor .note-take')].pop()?.dataset.takeState"; /// Waits until the `n`th (from 1) recording audio of the note has loaded with a duration in `want` /// seconds, and returns its src and duration. fn loaded_take(a: &Session, n: usize, want: (f64, f64), wait: u64) -> Result<(String, f64)> { let t = Instant::now(); let mut last = Value::Null; while t.elapsed() < Duration::from_secs(wait) { last = a.js(&format!( "const x = [...document.querySelectorAll('#editor audio[src^=\"/media/rec/\"]')][{}]; \ return x ? {{src: x.getAttribute('src'), ready: x.readyState, duration: x.duration}} : null", n - 1 ))?; if let (Some(d), Some(r)) = (last["duration"].as_f64(), last["ready"].as_u64()) { if r >= 1 && d >= want.0 && d <= want.1 { return Ok((last["src"].as_str().unwrap_or_default().to_owned(), d)); } } sleep(Duration::from_millis(100)); } bail!("recording {n} did not load as {want:?} s: {last}") } /// Uploads, Range, import rewriting, recording, and a recording cut off by leaving the note. fn media(agent: &ureq::Agent, a: &Session, dir: &Path, server: &mut Kill, start: &dyn Fn() -> Result) -> Result<()> { let upload = |name: &str, bytes: &[u8]| -> Result { let url = format!("{SERVER}/media?name={name}"); Ok(agent.post(&url).send(bytes)?.body_mut().read_to_string()?.trim().to_owned()) }; let cat = upload("cat.PNG", b"not really a png")?; if !cat.starts_with("/media/") || !cat.ends_with(".png") || upload("again.png", b"not really a png")? != cat { bail!("upload answered {cat}"); } let resp = agent.get(&format!("{SERVER}{cat}")).header("range", "bytes=4-9").call()?; if resp.status() != 206 || resp.headers()["content-range"] != "bytes 4-9/16" { bail!("range: {:?}", resp.headers()); } let svg = upload("evil.svg", b"")?; let resp = agent.get(&format!("{SERVER}{svg}")).call()?; if resp.headers()["content-disposition"] != "attachment" || resp.headers()["content-type"] != "application/octet-stream" { bail!("svg served as {:?}", resp.headers()); } let song = upload("song.mp3", b"not really an mp3")?; let text = "# Media\n\n![a cat](../att/cat.png)\n\n![[song.mp3|tune]]\n\n`![[song.mp3]]`\n"; let map = json!({"att/cat.png": cat, "vault/song.mp3": song}).to_string(); let id = agent .post(&format!("{SERVER}/import/file")) .send_form([("path", "vault/note.md"), ("text", text), ("media", map.as_str())])? .body_mut() .read_to_string()? .trim() .to_owned(); let note = format!("{SERVER}/notes/{id}"); expect_md(agent, ¬e, &format!("# Media\n\n![a cat]({cat})\n\n![tune]({song})\n\n`![[song.mp3]]`"))?; a.go(¬e)?; a.wait(EDITABLE, "the media note")?; a.wait(&format!("return {AUDIOS} === 1 && !!document.querySelector('#editor img')"), "the embeds to show")?; // Dropped file. a.js(CARET_END)?; a.js("const dt = new DataTransfer(); dt.items.add(new File(['pasted'], 'p.png', {type: 'image/png'})); \ document.querySelector('#editor .ProseMirror').dispatchEvent(new DragEvent('drop', \ {dataTransfer: dt, bubbles: true, cancelable: true})); return true")?; a.wait("return document.querySelectorAll('#editor img').length === 2", "the dropped image")?; // Recording from the fake microphone. The take's embed appears at its first ack and stays. a.js(CARET_END)?; a.js(RECORD)?; a.wait("return !!document.querySelector('[data-recording=true]')", "recording to start")?; sleep(Duration::from_millis(2500)); a.wait(&format!("return {TAKE_STATE} === 'live'"), "the take to show as live while recording")?; a.js(RECORD)?; a.wait(&format!("return {RECS} === 1 && {TAKES} === 1"), "the recording to appear")?; let (src, d) = loaded_take(a, 1, (2.0, 3.2), 40)?; println!("recorded {src} {d:.2} s"); let src1 = src; // Continue the take: same embed, one more part. a.js("document.querySelector('#editor .note-take-continue').click(); return true")?; a.wait("return !!document.querySelector('[data-recording=true]')", "the continued recording")?; sleep(Duration::from_millis(2000)); a.js(RECORD)?; a.wait(&format!("return {TAKES} === 1 && {RECS} === 1 && {TAKE_STATE} === 'absent'"), "the continued take to end")?; a.go(¬e)?; a.wait(EDITABLE, "the note after continuing")?; let (_, d) = loaded_take(a, 1, (4.0, 5.2), 40)?; println!("continued take {d:.2} s"); a.js("const x = document.querySelector('#editor audio[src^=\"/media/rec/\"]'); window.__seeked = false; \ x.addEventListener('seeked', () => window.__seeked = true, {once: true}); x.currentTime = 3.5; return true")?; a.wait("return window.__seeked === true", "the continued take to seek")?; // The server restarts mid-take: the client reconnects to the same part and the gap arrives. a.js(CARET_END)?; a.js(RECORD)?; a.wait("return !!document.querySelector('[data-recording=true]')", "the restart recording")?; sleep(Duration::from_millis(2000)); server.0.kill()?; server.0.wait()?; sleep(Duration::from_millis(3000)); *server = start()?; wait_http(agent, &format!("{SERVER}/"))?; sleep(Duration::from_millis(3000)); a.js(RECORD)?; a.wait(&format!("return {TAKES} === 2 && {TAKE_STATE} === 'absent'"), "the restart take to end")?; let n = a.js(&format!("return {RECS}"))?.as_u64().unwrap_or(0) as usize; let (_, d) = loaded_take(a, n, (7.0, 9.5), 40)?; println!("restart take {d:.2} s"); // A browser killed outright mid-recording: the embed in the other client shows the take as lost, // and the audio is whatever reached the server. let b = Session::new(agent, "http://127.0.0.1:4918", &dir.join("profile-b"))?; b.go(¬e)?; b.wait(EDITABLE, "the recording client")?; b.js(CARET_END)?; b.js(RECORD)?; b.wait("return !!document.querySelector('[data-recording=true]')", "the crash recording")?; sleep(Duration::from_millis(4000)); a.wait(&format!("return {TAKES} === 3"), "the crash take to reach the other client")?; let killed = Command::new("pkill").args(["-9", "-f", dir.join("profile-b").to_str().unwrap()]).status()?; if !killed.success() { bail!("no browser to kill"); } a.wait( "const t = [...document.querySelectorAll('#editor .note-take')].pop(); return !!t && t.dataset.takeState !== 'live'", "the crash take to stop being live", )?; let n = a.js(&format!("return {RECS}"))?.as_u64().unwrap_or(0) as usize; let (_, d) = loaded_take(a, n, (3.0, 4.2), 45)?; println!("crash take {d:.2} s"); let _ = a.screenshot(&dir.join("media.png")); // The import page: a note and the image it references, then a lone media file. let vault = dir.join("vault"); std::fs::create_dir_all(&vault)?; let (picked, pic, tone) = (vault.join("Picked.md"), vault.join("my pic.png"), vault.join("tone.mp3")); std::fs::write(&picked, "# Picked\n\n![pic](my%20pic.png)\n")?; std::fs::write(&pic, "picked image")?; std::fs::write(&tone, "picked audio")?; let import = format!("{SERVER}/import"); let done = "return !document.querySelector('#import-link').classList.contains('hidden')"; a.go(&import)?; a.keys("#import-files", &format!("{}\n{}", picked.display(), pic.display()))?; a.wait(done, "the import to finish")?; a.go(&format!("{SERVER}/notes/by-title/Picked"))?; a.wait(EDITABLE, "the imported note")?; a.wait("return !!document.querySelector('#editor img[src^=\"/media/\"]')", "the imported image")?; a.go(&import)?; a.keys("#import-files", &tone.display().to_string())?; a.wait(done, "the media import to finish")?; a.go(&format!("{SERVER}/notes/by-title/tone"))?; a.wait(EDITABLE, "the note of the lone file")?; a.wait(&format!("return {AUDIOS} === 1"), "the imported audio")?; let mut zip = Vec::new(); agent.get(&format!("{SERVER}/export.zip")).call()?.into_body().into_reader().read_to_end(&mut zip)?; std::fs::write(dir.join("export.zip"), &zip)?; let entry = format!("media/rec/{}", src1.trim_start_matches("/media/rec/")); if !zip.windows(entry.len()).any(|w| w == entry.as_bytes()) { bail!("the export has no {entry}"); } Ok(()) } /// Code blocks: the language is detected and Format rewrites the code through the server. fn code(agent: &ureq::Agent, a: &Session, dir: &Path) -> Result<()> { let text = "Code\n\n```\nlet x=foo( a,b );\nlet y = x.map(|s|s.len());\n```\n"; let id = agent .post(&format!("{SERVER}/import/file")) .send_form([("path", "code.md"), ("text", text)])? .body_mut() .read_to_string()? .trim() .to_owned(); let note = format!("{SERVER}/notes/{id}"); a.go(¬e)?; a.wait(EDITABLE, "the code note")?; a.wait( "const s = document.querySelector('.code-head .code-lang'); return !!s && s.options[0].text.includes('Rust')", "the header to show the detected language", )?; let _ = a.screenshot(&dir.join("code.png")); a.js("document.querySelector('.code-head .code-format').click(); return true")?; expect_md(agent, ¬e, "# code\n\nCode\n\n```rust\nlet x = foo(a, b);\nlet y = x.map(|s| s.len());\n```") } /// Typing latency on a 5000-paragraph note. fn perf(agent: &ureq::Agent, a: &Session) -> Result<()> { let text: String = (0..5000).map(|i| format!("Paragraph {i} with some ordinary words in it.\n\n")).collect(); let id = agent .post(&format!("{SERVER}/import/file")) .send_form([("path", "big.md"), ("text", text.as_str())])? .body_mut() .read_to_string()? .trim() .to_owned(); a.go(&format!("{SERVER}/notes/{id}"))?; a.wait(EDITABLE, "the big note to become editable")?; let ready = a.js("return performance.now()")?; // Top-level blocks live in pages that are built near the viewport: scroll there first. a.js("const r = document.querySelector('#editor .ProseMirror'); r.focus(); \ const pages = r.querySelectorAll(':scope > .pm-page'); pages[pages.length >> 1].scrollIntoView({block: 'center'}); return true")?; sleep(Duration::from_millis(300)); a.js("const pages = document.querySelectorAll('#editor .ProseMirror > .pm-page'); \ const p = pages[pages.length >> 1].firstElementChild; getSelection().collapse(p.firstChild, 9); return true")?; sleep(Duration::from_millis(100)); let m = a.js(MEASURE)?; println!("perf: editable after {ready} ms; {m}"); Ok(()) }