//! Finding 2(c) of the native realtime audit: after the first projection the //! authority reports only the top-level blocks that changed. Replaying the //! deltas onto the first projection must give exactly the whole projection //! after any mix of local commands, peers' updates, undo and redo. mod support; use docs_native_crdt::Editor; use serde_json::{json, Value}; use support::{generate, legacy_projection, oracle, Random}; fn open(bytes: &[u8], client: u64) -> Editor { let editor = Editor::new("large-document", client); editor.apply(bytes).unwrap(); editor } fn replay(children: &mut Vec, delta: &Value) -> usize { assert_eq!(delta["base"].as_u64().unwrap() as usize, children.len()); let mut next = Vec::new(); let mut at = 0; let mut projected = 0; for op in delta["ops"].as_array().unwrap() { if let Some(n) = op["keep"].as_u64() { next.extend_from_slice(&children[at..at + n as usize]); at += n as usize; } else if let Some(n) = op["remove"].as_u64() { at += n as usize; } else { let nodes = op["insert"].as_array().unwrap(); projected += nodes.len(); next.extend(nodes.iter().cloned()); } } assert_eq!(at, children.len(), "every previous block is kept or removed"); assert_eq!(next.len(), delta["count"].as_u64().unwrap() as usize); *children = next; projected } /// The current projection without touching the editor's delta base. fn truth(editor: &Editor) -> Value { legacy_projection(&editor.snapshot())["children"].clone() } #[test] fn typing_reprojects_only_the_block_typed_in() { let mut editor = open(&generate(20, 300, 21), 501); let mut children = editor.projection()["children"].as_array().unwrap().clone(); let (ranges, _) = oracle(&json!({"children": children})); let at = ranges[ranges.len() / 2].start + 3; for _ in 0..5 { editor.command(&json!({"op":"display_edit","at":at,"length":0,"text":"k"})).unwrap(); let delta = editor.projection_delta(); assert_eq!(replay(&mut children, &delta), 1, "one block re-projected: {}", delta["ops"]); assert_eq!(delta["ops"].as_array().unwrap().len(), 4, "keep, insert, remove, keep: {}", delta["ops"]); } assert_eq!(Value::Array(children), truth(&editor)); let unchanged = editor.projection_delta(); assert_eq!(unchanged["ops"], json!([{"keep": unchanged["count"]}])); } /// Seeds: a bounded run in the gate; DOCS_DELTA_SEEDS=1..100 locally. fn seeds() -> std::ops::RangeInclusive { match std::env::var("DOCS_DELTA_SEEDS") { Ok(v) => match v.split_once("..") { Some((a, b)) => a.parse().unwrap()..=b.parse().unwrap(), None => { let s = v.parse().unwrap(); s..=s } }, Err(_) => 1..=4, } } #[test] fn deltas_replay_to_the_whole_projection_through_every_kind_of_change() { for seed in seeds() { deltas_replay(seed); } } fn deltas_replay(seed: u64) { let base = generate(6, 400, 20 + seed); let mut authority = open(&base, 601); let peers: Vec = (0..3).map(|i| open(&base, 610 + i)).collect(); let mut peers = peers; let mut children = authority.projection()["children"].as_array().unwrap().clone(); let mut random = Random::new(seed * 7 + 2); let mut applied = std::collections::HashMap::::new(); for step in 0..160 { let p = json!({"children": children.clone()}); let (ranges, total) = oracle(&p); let texts: Vec<_> = ranges.iter().filter(|r| !r.atomic).collect(); let span = texts[random.below(texts.len() as u64) as usize]; let at = span.start + random.below(span.length as u64 + 1) as u32; let command = match step % 11 { 0 => json!({"op":"display_edit","at":at,"length":0,"text":"\nnew block"}), 1 => json!({"op":"display_edit","at":at.min(total.saturating_sub(200)),"length":150,"text":"J"}), 2 => json!({"op":"display_paste","at":at,"length":0,"blocks":[ {"type":"paragraph","children":[{"type":"text","runs":[{"insert":"pasted","marks":{"em":{}}}]}]}, {"type":"horizontal_rule"}, {"type":"bullet_list","children":[{"type":"list_item","children":[{"type":"paragraph","children":[{"type":"text","runs":[{"insert":"item","marks":{}}]}]}]}]}]}), 3 => json!({"op":"undo"}), 4 => json!({"op":"redo"}), 5 => json!({"op":"block","node":children[random.below(children.len() as u64) as usize]["id"],"type":"heading","level":2}), 6 => json!({"op":"attribute","node":children[random.below(children.len() as u64) as usize]["id"],"name":"align","value":"center"}), _ => json!({"op":"display_edit","at":at,"length":if step % 3 == 0 { span.length.min(2) } else { 0 },"text":"typed"}), }; let local = authority.command(&command); if local.is_ok() { *applied.entry(command["op"].as_str().unwrap().to_owned()).or_default() += 1; } // Peers edit concurrently; their updates arrive in between. let peer = &mut peers[step % 3]; let peer_p = peer.projection(); let (peer_ranges, _) = oracle(&peer_p); let peer_texts: Vec<_> = peer_ranges.iter().filter(|r| !r.atomic && r.length > 0).collect(); let peer_span = peer_texts[random.below(peer_texts.len() as u64) as usize]; // A position inside an emoji is refused; the peer then edits at the // text's start, which is always a boundary. let remote = peer.command(&json!({"op":"display_edit","at":peer_span.start + 1,"length":if step % 4 == 0 { 1 } else { 0 },"text":"p"})) .or_else(|_| peer.command(&json!({"op":"display_edit","at":peer_span.start,"length":0,"text":"p"}))).unwrap(); authority.apply(&remote).unwrap(); if let Ok(update) = local { for peer in &peers { peer.apply(&update).unwrap(); } } for other in peers.iter().enumerate().filter(|(i, _)| *i != step % 3).map(|(_, p)| p) { other.apply(&remote).unwrap(); } if step % 5 != 4 { replay(&mut children, &authority.projection_delta()); assert_eq!(Value::Array(children.clone()), truth(&authority), "seed {seed} step {step}: {command}"); } } for op in ["display_edit", "display_paste", "undo", "redo", "block", "attribute"] { assert!(applied.get(op).copied().unwrap_or(0) >= 3, "seed {seed}: {op} ran: {applied:?}"); } let delta = authority.projection_delta(); assert_eq!(delta["canUndo"], authority.projection()["canUndo"]); } #[test] fn a_full_projection_resets_the_delta_base() { let mut editor = open(&generate(2, 0, 23), 701); let _ = editor.projection(); editor.command(&json!({"op":"display_edit","at":5,"length":0,"text":"a"})).unwrap(); let mut children = editor.projection()["children"].as_array().unwrap().clone(); let delta = editor.projection_delta(); assert_eq!(delta["ops"], json!([{"keep": children.len()}])); replay(&mut children, &delta); }