//! Wire fixtures for transaction-scoped updates (native realtime audit, //! finding 7). Phase one writes an edited base document, then one update per //! command (each only what that command inserted and deleted) with the //! authority's snapshot after it; native/scripts/check-update-wire.mjs replays //! them in Yjs and writes the browser's own per-transaction updates back. //! Phase two (`--browser DIR`) applies those to the native engine. use docs_native_crdt::Editor; use serde_json::{json, Value}; use std::path::Path; fn plain(value: &Value) -> String { if let Some(runs) = value["runs"].as_array() { return runs.iter().filter_map(|run| run["insert"].as_str()).collect(); } value["children"].as_array().map(|children| children.iter().map(plain).collect()).unwrap_or_default() } fn length(value: &Value) -> u32 { // Display length: text, one per inline atom, two per rule, one per block end. fn walk(value: &Value) -> u32 { match value["type"].as_str().unwrap_or("") { "text" => plain(value).encode_utf16().count() as u32, "hard_break" | "image" => 1, "horizontal_rule" => 2, tag => value["children"].as_array().map(|c| c.iter().map(walk).sum()).unwrap_or(0) + u32::from(["paragraph","heading","code_block"].contains(&tag)), } } value["children"].as_array().unwrap().iter().map(walk).sum() } fn edited_base() -> Editor { // Three writers type and delete concurrently, so the base carries the // tombstones (a delete set) a state-vector diff would have resent. let mut writers: Vec = (0..3).map(|i| Editor::new("update-wire", 9_100 + i)).collect(); let first = writers[0].command(&json!({"op":"insert_element","at":0,"type":"paragraph"})).unwrap(); for writer in &writers[1..] { writer.apply(&first).unwrap(); } let mut seed: u64 = 7; let mut next = |n: u32| { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); ((seed >> 33) as u32) % n.max(1) }; for round in 0..60 { let mut updates = Vec::new(); for (index, writer) in writers.iter_mut().enumerate() { let total = length(&writer.projection()); let at = next(total); let command = if round % 4 == 3 && total > 6 { json!({"op":"display_edit","at":at.min(total - 4),"length":2,"text":""}) } else if round % 7 == 6 { json!({"op":"display_edit","at":at,"length":0,"text":"\n"}) } else { json!({"op":"display_edit","at":at,"length":0,"text":format!("w{index}r{round} ")}) }; if let Ok(update) = writer.command(&command) { updates.push((index, update)); } } for (index, writer) in writers.iter().enumerate() { for (from, update) in &updates { if *from != index { writer.apply(update).unwrap(); } } } } let base = Editor::new("update-wire", 9_000); base.apply(&writers[0].snapshot()).unwrap(); base } fn main() { let arguments: Vec = std::env::args().collect(); if arguments.get(1).map(String::as_str) == Some("--browser") { let directory = Path::new(&arguments[2]); let editor = Editor::new("update-wire", 9_500); editor.apply(&std::fs::read(directory.join("base.bin")).unwrap()).unwrap(); let mut index = 0; while let Ok(update) = std::fs::read(directory.join(format!("browser-{index}.bin"))) { editor.apply(&update).unwrap(); index += 1; } assert!(index > 0, "no browser updates"); let expected = std::fs::read_to_string(directory.join("browser-text.txt")).unwrap(); assert_eq!(plain(&editor.projection()), expected, "native applies the browser's per-transaction updates"); println!("Native applied {index} browser transaction updates."); return; } let directory = Path::new(&arguments[1]); std::fs::create_dir_all(directory).unwrap(); let mut authority = edited_base(); std::fs::write(directory.join("base.bin"), authority.snapshot()).unwrap(); let total = length(&authority.projection()); let middle = total / 2; // Each step: a command built from the authority's current projection, // run on a fresh source (a new client, as each presentation makes) or, // for undo and redo, on the authority. `Concurrent` runs two sources // from the same state, so their updates are concurrent. enum Step { Source(Value), Authority(Value), Concurrent(Value, Value) } fn find(value: &Value, test: &dyn Fn(&Value) -> bool) -> Option { if test(value) { return Some(value.clone()); } value["children"].as_array().into_iter().flatten().find_map(|child| find(child, test)) } let in_list = |p: &Value| find(p, &|v| v["type"] == "list_item").and_then(|item| find(&item, &|v| v["type"] == "paragraph")).map(|v| v["id"].clone()); let builders: Vec Step>> = vec![ Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle,"length":0,"text":"x"}))), Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle,"length":3,"text":""}))), Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle,"length":0,"text":"line\nsplit\u{2028}break"}))), Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle.saturating_sub(30),"length":60,"text":"joined"}))), Box::new(|_, _| Step::Source(json!({"op":"display_paste","at":5,"length":2,"blocks":[ {"type":"heading","attrs":{"level":"2"},"children":[{"type":"text","runs":[{"insert":"Pasted","marks":{"strong":{}}}]}]}, {"type":"bullet_list","children":[{"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"Item","marks":{}}]}]}]}]} ]}))), Box::new(|_, _| Step::Authority(json!({"op":"undo"}))), Box::new(|_, _| Step::Authority(json!({"op":"redo"}))), Box::new(|p, _| Step::Source(json!({"op":"batch","commands":[{"op":"block","node":p["children"][0]["id"],"type":"ordered_list"}]}))), Box::new(|p, _| Step::Source(json!({"op":"format","node":find(p, &|v| v["type"] == "text" && plain(v).encode_utf16().count() > 8).unwrap()["id"],"at":2,"length":5,"marks":{"em":{}}}))), Box::new(|p, _| Step::Source(json!({"op":"attribute","node":find(p, &|v| v["type"] == "paragraph").unwrap()["id"],"name":"align","value":"center"}))), Box::new(|p, _| Step::Source(json!({"op":"split","node":find(p, &|v| v["type"] == "text" && plain(v).encode_utf16().count() > 8).unwrap()["id"],"at":3}))), Box::new(move |p, _| Step::Source(json!({"op":"list_indent","node":in_list(p).unwrap(),"delta":-1}))), Box::new(|_, total| Step::Source(json!({"op":"display_edit","at":total - 1,"length":0,"text":"\n-"}))), Box::new(|_, total| Step::Source(json!({"op":"display_autoformat","at":total - 2,"length":1,"kind":"bullet_list","level":0}))), Box::new(|_, total| Step::Source(json!({"op":"display_revert_rule","at":total - 1,"kind":"bullet_list","prior_type":"paragraph","prior_attrs":{},"text":"- "}))), Box::new(move |_, _| Step::Concurrent(json!({"op":"display_edit","at":middle,"length":0,"text":"left"}), json!({"op":"display_edit","at":middle,"length":4,"text":"right"}))), Box::new(|_, _| Step::Authority(json!({"op":"undo"}))), Box::new(|_, _| Step::Authority(json!({"op":"undo"}))), ]; let mut manifest = Vec::new(); let mut index = 0; for (number, build) in builders.iter().enumerate() { let projection = authority.projection(); let step = build(&projection, length(&projection)); let commands: Vec<(Value, bool)> = match step { Step::Source(c) => vec![(c, true)], Step::Authority(c) => vec![(c, false)], Step::Concurrent(a, b) => vec![(a, true), (b, true)], }; let snapshot = authority.snapshot(); let mut updates = Vec::new(); for (offset, (command, from_source)) in commands.iter().enumerate() { let update = if *from_source { // Concurrent sources both start from the state before either. let mut source = Editor::new("update-wire", 9_200 + (number * 2 + offset) as u64); source.apply(&snapshot).unwrap(); source.command(command).unwrap_or_else(|e| panic!("{command}: {e}")) } else { authority.command(command).unwrap() }; updates.push((command.clone(), update)); } for (command, update) in updates { if command["op"] != "undo" && command["op"] != "redo" { authority.apply_local(&update).unwrap(); } index += 1; std::fs::write(directory.join(format!("{index}.bin")), &update).unwrap(); std::fs::write(directory.join(format!("{index}.snapshot")), authority.snapshot()).unwrap(); manifest.push(json!({"command": command["op"], "bytes": update.len()})); } } std::fs::write(directory.join("manifest.json"), Value::Array(manifest).to_string()).unwrap(); std::fs::write(directory.join("keystroke-at.txt"), middle.to_string()).unwrap(); }