Files
Liber-public/crates/liber-library/tests/sync.rs
T

193 lines
7.2 KiB
Rust

//! Mandatory test 5 (the core's half): devices with clock skew and dropped connections converge; highlights made
//! offline on both merge; positions keep the furthest with a "jump back" offer; concurrent text edits keep both.
//! (The app's `liber-store` tests the relay: ciphertext only on the wire.)
mod common;
use common::{Rng, events, info};
use liber_library::library::{Colour, Field, Mark};
use liber_library::{Clock, Event, Library, Op};
use proptest::prelude::*;
use serde_json::json;
fn shuffle(mut v: Vec<Event>, r: &mut Rng) -> Vec<Event> {
for i in (1..v.len()).rev() {
let j = r.below(i as u64 + 1) as usize;
v.swap(i, j);
}
v
}
proptest! {
#![proptest_config(ProptestConfig { cases: 200, ..ProptestConfig::default() })]
/// Two devices, skewed clocks, events delivered in random order, with duplicates, in several partial rounds
/// (dropped connections): once both hold every event, both hold the same library.
#[test]
fn devices_converge(seed in any::<u64>(), skew in -180_000i64..180_000, na in 1usize..60, nb in 1usize..60) {
let a = events(seed, "phone", na, 0);
let b = events(seed.rotate_left(17) ^ 0x9e37, "desk", nb, skew);
let mut r = Rng(seed ^ 0xabcdef | 1);
// Device A's view: its own events, then B's arriving in random batches, some twice.
let mut on_a = a.clone();
let mut incoming = shuffle(b.clone(), &mut r);
while !incoming.is_empty() {
let k = 1 + r.below(incoming.len() as u64) as usize;
let batch: Vec<Event> = incoming.drain(..k).collect();
on_a.extend(batch.iter().cloned());
if r.below(3) == 0 {
on_a.extend(batch); // a retried upload
}
// A partial library after each round never panics.
let _ = Library::from_events(&on_a);
}
let mut on_b = b.clone();
on_b.extend(shuffle(a.clone(), &mut r));
let la = Library::from_events(&on_a);
let lb = Library::from_events(&on_b);
prop_assert_eq!(&la, &lb);
// And the stats agree.
prop_assert_eq!(liber_library::stats::stats(&la, Some(2025)), liber_library::stats::stats(&lb, Some(2025)));
}
}
fn ev(id: &str, dev: &str, c: &mut Clock, t: u64, op: Op) -> Event {
Event { id: id.into(), hlc: c.tick(t), device: dev.into(), op }
}
fn add(book: &str) -> Op {
Op::BookAdd { book: book.into(), info: info(0), restore: false }
}
#[test]
fn highlights_made_offline_on_both_devices_merge() {
let (mut pc, mut dc) = (Clock::default(), Clock::default());
let base = ev("p0", "phone", &mut pc, 1000, add("b"));
let hl = |id: &str, dev: &str, c: &mut Clock, t: u64, q: &str| {
ev(
&format!("{dev}-{id}"),
dev,
c,
t,
Op::HighlightAdd {
id: id.into(),
book: "b".into(),
kind: Mark::Highlight,
anchor: json!({"quote": {"exact": q}}),
colour: Colour::Yellow,
note: String::new(),
created: t,
},
)
};
let p = [base.clone(), hl("h1", "phone", &mut pc, 2000, "na telefonu")];
let d = [base, hl("h2", "desk", &mut dc, 1500, "na počítači")];
let all: Vec<Event> = p.iter().chain(d.iter()).cloned().collect();
let lib = Library::from_events(&all);
assert_eq!(lib.highlights.len(), 2);
// A deletion on one device and an edit on the other: the deletion wins, everywhere.
let mut more = all.clone();
more.push(ev("d-del", "desk", &mut dc, 3000, Op::HighlightRemove { id: "h1".into() }));
more.push(ev(
"p-edit",
"phone",
&mut pc,
3500,
Op::HighlightSet { id: "h1".into(), colour: Some(Colour::Blue), note: None, base: None },
));
let l = Library::from_events(&more);
assert!(!l.highlights.contains_key("h1"));
assert!(l.highlights.contains_key("h2"));
}
#[test]
fn positions_keep_the_furthest_and_offer_a_jump_back() {
let mut c = Clock::default();
let pos = |id: &str, c: &mut Clock, t: u64, p: f64| {
ev(
id,
"x",
c,
t,
Op::Position {
book: "b".into(),
cfi: format!("epubcfi(/6/2!/4/2/1:{})", (p * 100.0) as u32),
chapter: 0,
progress: p,
label: Some(format!("{}", (p * 300.0) as u32)),
},
)
};
let events = vec![ev("a", "x", &mut c, 1, add("b")), pos("p1", &mut c, 10, 0.6), pos("p2", &mut c, 20, 0.3)];
let l = Library::from_events(&events);
let b = &l.books["b"];
assert_eq!(b.position.as_ref().unwrap().progress, 0.6);
assert_eq!(b.jump_back().unwrap().progress, 0.3, "the newest position is behind: offer to jump back");
let mut ev2 = events.clone();
ev2.push(pos("p3", &mut c, 30, 0.7));
assert!(Library::from_events(&ev2).books["b"].jump_back().is_none());
}
#[test]
fn concurrent_text_edits_keep_both_versions() {
let (mut pc, mut dc) = (Clock::default(), Clock::default());
let a = ev("a", "phone", &mut pc, 1, add("b"));
let r0 = ev(
"r0",
"phone",
&mut pc,
2,
Op::BookSet { book: "b".into(), field: Field::Review, value: json!("first"), base: None },
);
// Both devices saw r0, then edited offline.
let rp = ev(
"rp",
"phone",
&mut pc,
10,
Op::BookSet {
book: "b".into(),
field: Field::Review,
value: json!("phone's version"),
base: Some("r0".into()),
},
);
dc.observe(r0.hlc);
let rd = ev(
"rd",
"desk",
&mut dc,
9,
Op::BookSet { book: "b".into(), field: Field::Review, value: json!("desk's version"), base: Some("r0".into()) },
);
let l = Library::from_events(&[a.clone(), r0.clone(), rp.clone(), rd.clone()]);
let review = &l.books["b"].review;
let mut both = vec![review.value.clone(), review.conflict.clone().unwrap()];
both.sort();
assert_eq!(both, vec!["desk's version", "phone's version"]);
// The next edit, made seeing the merged state, clears the marker.
let v = l.version("b", Field::Review).map(str::to_owned);
let fix = ev(
"fix",
"desk",
&mut dc,
20,
Op::BookSet { book: "b".into(), field: Field::Review, value: json!("merged"), base: v },
);
let l = Library::from_events(&[a, r0, rp, rd, fix]);
assert_eq!(l.books["b"].review.value, "merged");
assert!(l.books["b"].review.conflict.is_none());
}
#[test]
fn the_same_book_added_on_two_devices_merges() {
let (mut pc, mut dc) = (Clock::default(), Clock::default());
let p = ev("p", "phone", &mut pc, 5, Op::BookAdd { book: "phone-id".into(), info: info(1), restore: false });
let d = ev("d", "desk", &mut dc, 3, Op::BookAdd { book: "desk-id".into(), info: info(1), restore: false });
let s = ev("s", "phone", &mut pc, 6, Op::ShelfAdd { book: "phone-id".into(), shelf: "sci-fi".into() });
let l = Library::from_events(&[p, d, s]);
assert_eq!(l.books.len(), 1);
let b = l.books.values().next().unwrap();
assert_eq!(b.id, "desk-id", "the earlier add wins; the other id is an alias");
assert!(b.shelves.contains("sci-fi"));
}