| 1 | //! Wire fixtures for transaction-scoped updates (native realtime audit, |
| 2 | //! finding 7). Phase one writes an edited base document, then one update per |
| 3 | //! command (each only what that command inserted and deleted) with the |
| 4 | //! authority's snapshot after it; native/scripts/check-update-wire.mjs replays |
| 5 | //! them in Yjs and writes the browser's own per-transaction updates back. |
| 6 | //! Phase two (`--browser DIR`) applies those to the native engine. |
| 7 | use docs_native_crdt::Editor; |
| 8 | use serde_json::{json, Value}; |
| 9 | use std::path::Path; |
| 10 | |
| 11 | fn plain(value: &Value) -> String { |
| 12 | if let Some(runs) = value["runs"].as_array() { return runs.iter().filter_map(|run| run["insert"].as_str()).collect(); } |
| 13 | value["children"].as_array().map(|children| children.iter().map(plain).collect()).unwrap_or_default() |
| 14 | } |
| 15 | fn length(value: &Value) -> u32 { |
| 16 | // Display length: text, one per inline atom, two per rule, one per block end. |
| 17 | fn walk(value: &Value) -> u32 { |
| 18 | match value["type"].as_str().unwrap_or("") { |
| 19 | "text" => plain(value).encode_utf16().count() as u32, |
| 20 | "hard_break" | "image" => 1, |
| 21 | "horizontal_rule" => 2, |
| 22 | tag => value["children"].as_array().map(|c| c.iter().map(walk).sum()).unwrap_or(0) + u32::from(["paragraph","heading","code_block"].contains(&tag)), |
| 23 | } |
| 24 | } |
| 25 | value["children"].as_array().unwrap().iter().map(walk).sum() |
| 26 | } |
| 27 | fn edited_base() -> Editor { |
| 28 | // Three writers type and delete concurrently, so the base carries the |
| 29 | // tombstones (a delete set) a state-vector diff would have resent. |
| 30 | let mut writers: Vec<Editor> = (0..3).map(|i| Editor::new("update-wire", 9_100 + i)).collect(); |
| 31 | let first = writers[0].command(&json!({"op":"insert_element","at":0,"type":"paragraph"})).unwrap(); |
| 32 | for writer in &writers[1..] { writer.apply(&first).unwrap(); } |
| 33 | let mut seed: u64 = 7; |
| 34 | let mut next = |n: u32| { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); ((seed >> 33) as u32) % n.max(1) }; |
| 35 | for round in 0..60 { |
| 36 | let mut updates = Vec::new(); |
| 37 | for (index, writer) in writers.iter_mut().enumerate() { |
| 38 | let total = length(&writer.projection()); |
| 39 | let at = next(total); |
| 40 | let command = if round % 4 == 3 && total > 6 { json!({"op":"display_edit","at":at.min(total - 4),"length":2,"text":""}) } |
| 41 | else if round % 7 == 6 { json!({"op":"display_edit","at":at,"length":0,"text":"\n"}) } |
| 42 | else { json!({"op":"display_edit","at":at,"length":0,"text":format!("w{index}r{round} ")}) }; |
| 43 | if let Ok(update) = writer.command(&command) { updates.push((index, update)); } |
| 44 | } |
| 45 | for (index, writer) in writers.iter().enumerate() { |
| 46 | for (from, update) in &updates { if *from != index { writer.apply(update).unwrap(); } } |
| 47 | } |
| 48 | } |
| 49 | let base = Editor::new("update-wire", 9_000); |
| 50 | base.apply(&writers[0].snapshot()).unwrap(); |
| 51 | base |
| 52 | } |
| 53 | fn main() { |
| 54 | let arguments: Vec<String> = std::env::args().collect(); |
| 55 | if arguments.get(1).map(String::as_str) == Some("--browser") { |
| 56 | let directory = Path::new(&arguments[2]); |
| 57 | let editor = Editor::new("update-wire", 9_500); |
| 58 | editor.apply(&std::fs::read(directory.join("base.bin")).unwrap()).unwrap(); |
| 59 | let mut index = 0; |
| 60 | while let Ok(update) = std::fs::read(directory.join(format!("browser-{index}.bin"))) { |
| 61 | editor.apply(&update).unwrap(); |
| 62 | index += 1; |
| 63 | } |
| 64 | assert!(index > 0, "no browser updates"); |
| 65 | let expected = std::fs::read_to_string(directory.join("browser-text.txt")).unwrap(); |
| 66 | assert_eq!(plain(&editor.projection()), expected, "native applies the browser's per-transaction updates"); |
| 67 | println!("Native applied {index} browser transaction updates."); |
| 68 | return; |
| 69 | } |
| 70 | let directory = Path::new(&arguments[1]); |
| 71 | std::fs::create_dir_all(directory).unwrap(); |
| 72 | let mut authority = edited_base(); |
| 73 | std::fs::write(directory.join("base.bin"), authority.snapshot()).unwrap(); |
| 74 | let total = length(&authority.projection()); |
| 75 | let middle = total / 2; |
| 76 | // Each step: a command built from the authority's current projection, |
| 77 | // run on a fresh source (a new client, as each presentation makes) or, |
| 78 | // for undo and redo, on the authority. `Concurrent` runs two sources |
| 79 | // from the same state, so their updates are concurrent. |
| 80 | enum Step { Source(Value), Authority(Value), Concurrent(Value, Value) } |
| 81 | fn find(value: &Value, test: &dyn Fn(&Value) -> bool) -> Option<Value> { |
| 82 | if test(value) { return Some(value.clone()); } |
| 83 | value["children"].as_array().into_iter().flatten().find_map(|child| find(child, test)) |
| 84 | } |
| 85 | 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()); |
| 86 | let builders: Vec<Box<dyn Fn(&Value, u32) -> Step>> = vec![ |
| 87 | Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle,"length":0,"text":"x"}))), |
| 88 | Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle,"length":3,"text":""}))), |
| 89 | Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle,"length":0,"text":"line\nsplit\u{2028}break"}))), |
| 90 | Box::new(move |_, _| Step::Source(json!({"op":"display_edit","at":middle.saturating_sub(30),"length":60,"text":"joined"}))), |
| 91 | Box::new(|_, _| Step::Source(json!({"op":"display_paste","at":5,"length":2,"blocks":[ |
| 92 | {"type":"heading","attrs":{"level":"2"},"children":[{"type":"text","runs":[{"insert":"Pasted","marks":{"strong":{}}}]}]}, |
| 93 | {"type":"bullet_list","children":[{"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"Item","marks":{}}]}]}]}]} |
| 94 | ]}))), |
| 95 | Box::new(|_, _| Step::Authority(json!({"op":"undo"}))), |
| 96 | Box::new(|_, _| Step::Authority(json!({"op":"redo"}))), |
| 97 | Box::new(|p, _| Step::Source(json!({"op":"batch","commands":[{"op":"block","node":p["children"][0]["id"],"type":"ordered_list"}]}))), |
| 98 | 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":{}}}))), |
| 99 | Box::new(|p, _| Step::Source(json!({"op":"attribute","node":find(p, &|v| v["type"] == "paragraph").unwrap()["id"],"name":"align","value":"center"}))), |
| 100 | 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}))), |
| 101 | Box::new(move |p, _| Step::Source(json!({"op":"list_indent","node":in_list(p).unwrap(),"delta":-1}))), |
| 102 | Box::new(|_, total| Step::Source(json!({"op":"display_edit","at":total - 1,"length":0,"text":"\n-"}))), |
| 103 | Box::new(|_, total| Step::Source(json!({"op":"display_autoformat","at":total - 2,"length":1,"kind":"bullet_list","level":0}))), |
| 104 | Box::new(|_, total| Step::Source(json!({"op":"display_revert_rule","at":total - 1,"kind":"bullet_list","prior_type":"paragraph","prior_attrs":{},"text":"- "}))), |
| 105 | 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"}))), |
| 106 | Box::new(|_, _| Step::Authority(json!({"op":"undo"}))), |
| 107 | Box::new(|_, _| Step::Authority(json!({"op":"undo"}))), |
| 108 | ]; |
| 109 | let mut manifest = Vec::new(); |
| 110 | let mut index = 0; |
| 111 | for (number, build) in builders.iter().enumerate() { |
| 112 | let projection = authority.projection(); |
| 113 | let step = build(&projection, length(&projection)); |
| 114 | let commands: Vec<(Value, bool)> = match step { |
| 115 | Step::Source(c) => vec![(c, true)], |
| 116 | Step::Authority(c) => vec![(c, false)], |
| 117 | Step::Concurrent(a, b) => vec![(a, true), (b, true)], |
| 118 | }; |
| 119 | let snapshot = authority.snapshot(); |
| 120 | let mut updates = Vec::new(); |
| 121 | for (offset, (command, from_source)) in commands.iter().enumerate() { |
| 122 | let update = if *from_source { |
| 123 | // Concurrent sources both start from the state before either. |
| 124 | let mut source = Editor::new("update-wire", 9_200 + (number * 2 + offset) as u64); |
| 125 | source.apply(&snapshot).unwrap(); |
| 126 | source.command(command).unwrap_or_else(|e| panic!("{command}: {e}")) |
| 127 | } else { authority.command(command).unwrap() }; |
| 128 | updates.push((command.clone(), update)); |
| 129 | } |
| 130 | for (command, update) in updates { |
| 131 | if command["op"] != "undo" && command["op"] != "redo" { authority.apply_local(&update).unwrap(); } |
| 132 | index += 1; |
| 133 | std::fs::write(directory.join(format!("{index}.bin")), &update).unwrap(); |
| 134 | std::fs::write(directory.join(format!("{index}.snapshot")), authority.snapshot()).unwrap(); |
| 135 | manifest.push(json!({"command": command["op"], "bytes": update.len()})); |
| 136 | } |
| 137 | } |
| 138 | std::fs::write(directory.join("manifest.json"), Value::Array(manifest).to_string()).unwrap(); |
| 139 | std::fs::write(directory.join("keystroke-at.txt"), middle.to_string()).unwrap(); |
| 140 | } |
| 141 | |