//! Engine cost per keystroke and per remote change, through the production //! interpreter and fuel (native realtime audit, findings 2, 7 and 9). //! //! cargo run --release --example realtime -- /tmp/rt-audit/docs/p*.bin //! //! Documents come from fixtures/generate-large-doc.mjs. Each keystroke is //! what CRDTReplica does for one typed character: `display_edit` on the //! displayed source, the update applied to the authority, the selection's //! two anchors resolved, and the authority's presentation (`project_delta` //! where the module has it, else the whole projection). use docs_native_host::Host; use serde_json::{json, Value}; use std::time::Instant; fn call(host: &mut Host, request: &Value) -> Result, &'static str> { host.call(&serde_json::to_vec(request).unwrap()).map(<[u8]>::to_vec) } fn median(mut v: Vec) -> f64 { v.sort_by(|a, b| a.partial_cmp(b).unwrap()); if v.is_empty() { f64::NAN } else { v[v.len() / 2] } } fn open(bytes: &[u8], client: u64) -> Result { let mut host = Host::new()?; call(&mut host, &json!({"op":"open","guid":"bench","client":client}))?; let mut envelope = vec![255]; envelope.extend_from_slice(bytes); host.call(&envelope)?; Ok(host) } fn text_offset(projection: &Value) -> u32 { // The middle of the document, inside a text run. fn walk(v: &Value, offset: &mut u32, out: &mut Vec<(u32, u32)>) { match v["type"].as_str().unwrap_or("") { "text" => { let n: u32 = v["runs"].as_array().unwrap().iter().map(|r| r["insert"].as_str().unwrap().encode_utf16().count() as u32).sum(); out.push((*offset, n)); *offset += n; }, "hard_break" | "image" => *offset += 1, "horizontal_rule" => *offset += 2, tag => { for c in v["children"].as_array().into_iter().flatten() { walk(c, offset, out); } if ["paragraph","heading","code_block"].contains(&tag) { *offset += 1; } }, } } let mut offset = 0; let mut texts = Vec::new(); for c in projection["children"].as_array().unwrap() { walk(c, &mut offset, &mut texts); } let (start, n) = texts.iter().copied().filter(|(_, n)| *n > 20).nth(texts.len() / 2).unwrap_or(texts[0]); start + n / 2 } fn main() { for path in std::env::args().skip(1) { let name = std::path::Path::new(&path).file_stem().unwrap().to_string_lossy().to_string(); let bytes = std::fs::read(&path).unwrap(); let t = Instant::now(); let (mut authority, mut source) = match (open(&bytes, 11), open(&bytes, 12)) { (Ok(a), Ok(s)) => (a, s), _ => { println!("{name:6} open FAILED (fuel)"); continue; } }; let opened = t.elapsed().as_secs_f64() * 1e3 / 2.0; // An unknown op poisons a host, so ask a throwaway one. let delta = open(b"\0\0", 13).ok().and_then(|mut probe| call(&mut probe, &json!({"op":"project_delta"})).ok()).is_some(); let projection: Value = match call(&mut authority, &json!({"op":"project"})) { Ok(p) => serde_json::from_slice(&p).unwrap(), Err(e) => { println!("{name:6} project FAILED ({e})"); continue; } }; let mut at = text_offset(&projection); let (mut command, mut apply, mut anchors, mut present, mut sizes) = (vec![], vec![], vec![], vec![], vec![]); let mut failed = None; for _ in 0..12 { let t = Instant::now(); let update = match call(&mut source, &json!({"op":"display_edit","at":at,"length":0,"text":"x"})) { Ok(u) => u, Err(e) => { failed = Some(e); break; } }; command.push(t.elapsed().as_secs_f64() * 1e3); sizes.push(update.len()); let t = Instant::now(); let mut envelope = vec![254]; envelope.extend(&update); if let Err(e) = authority.call(&envelope) { failed = Some(e); break; } apply.push(t.elapsed().as_secs_f64() * 1e3); let t = Instant::now(); for end in [at + 1, at + 1] { let anchor: Value = match call(&mut source, &json!({"op":"anchor","at":end})) { Ok(a) => serde_json::from_slice(&a).unwrap(), Err(e) => { failed = Some(e); break; } }; if let Err(e) = call(&mut authority, &json!({"op":"resolve","anchor":anchor})) { failed = Some(e); break; } } anchors.push(t.elapsed().as_secs_f64() * 1e3); let t = Instant::now(); let op = if delta { "project_delta" } else { "project" }; match call(&mut authority, &json!({"op":op})) { Ok(_) => present.push(t.elapsed().as_secs_f64() * 1e3), Err(e) => { failed = Some(e); break; } } at += 1; } let keystroke: f64 = median(command.clone()) + median(apply.clone()) + median(anchors.clone()) + median(present.clone()); println!("{name:6} open {opened:7.1} ms | display_edit {:7.2} | authority apply {:6.2} | 2 anchors {:7.2} | {} {:7.2} | keystroke {keystroke:7.2} ms | update {} B{}", median(command), median(apply), median(anchors), if delta { "delta" } else { "project" }, median(present), sizes.iter().max().unwrap_or(&0), failed.map(|e| format!(" | FAILED: {e}")).unwrap_or_default()); } }