extern crate std; use super::backup; use super::*; use alloc::string::ToString; use std::collections::BTreeMap as Map; use std::vec; /// A device's vault in memory: files and their times of change. #[derive(Default, Clone)] struct Disk { files: Map, u64)>, now: u64, /// Writes to this path fail. broken: Option, } impl Files for Disk { fn read(&mut self, path: &str) -> Option> { self.files.get(path).map(|f| f.0.clone()) } fn write(&mut self, path: &str, data: &[u8]) -> bool { if self.broken.as_deref() == Some(path) { return false; } self.files.insert(path.into(), (data.to_vec(), self.now)); true } fn remove(&mut self, path: &str) -> bool { self.files.remove(path).is_some() } } impl Disk { fn with(files: &[(&str, &str)]) -> Disk { let mut d = Disk { now: 100, ..Disk::default() }; for (p, c) in files { d.write(p, c.as_bytes()); } d } fn put(&mut self, path: &str, text: &str) { self.now += 10; self.write(path, text.as_bytes()); } fn text(&self, path: &str) -> Option<&str> { self.files.get(path).map(|f| core::str::from_utf8(&f.0).unwrap()) } fn manifest(&self) -> Vec { let stats: Vec<(String, u64, u64)> = self .files .iter() .map(|(p, (d, t))| (p.clone(), d.len() as u64, *t)) .collect(); let mut index = Index::default(); let files = self.files.clone(); index.refresh(&stats, self.now + 1000, &mut |p| { files.get(p).map(|f| f.0.clone()) }) } } /// Runs one sync between `a` (which decides) and `b` until both are done, /// passing every message; returns both outcomes. `cut` stops it after that /// many messages, as a network lost. fn sync(a: &mut Disk, b: &mut Disk, base: &[Agreed], cut: Option) -> (Outcome, Outcome) { let mut x = Sync::new(true, "Laptop", a.manifest(), base.to_vec()); let mut y = Sync::new(false, "Phone", b.manifest(), Vec::new()); let mut passed = 0; loop { let mut moved = false; while let Some(m) = x.output(a) { assert!(m.len() <= 4096, "a message of {} bytes", m.len()); y.receive(&m, b); moved = true; passed += 1; if cut == Some(passed) { return (Outcome::default(), Outcome::default()); } } while let Some(m) = y.output(b) { assert!(m.len() <= 4096, "a message of {} bytes", m.len()); x.receive(&m, a); moved = true; passed += 1; } if !moved { break; } } ( x.outcome().expect("the deciding side finished").clone(), y.outcome().expect("the other side finished").clone(), ) } fn same(a: &Disk, b: &Disk) { let fa: Map<&String, &Vec> = a.files.iter().map(|(p, f)| (p, &f.0)).collect(); let fb: Map<&String, &Vec> = b .files .iter() .filter(|(p, _)| synced(p)) .map(|(p, f)| (p, &f.0)) .collect(); let fa: Map<&String, &Vec> = fa.into_iter().filter(|(p, _)| synced(p)).collect(); assert_eq!(fa, fb); } #[test] fn a_new_device_gets_everything() { let big: String = (0..20_000).map(|i| char::from(b'a' + (i % 26) as u8)).collect(); let mut laptop = Disk::with(&[ ("/apps/notes/shopping", "bread\nmilk\n"), ("/apps/notes/long", &big), ("/p2p/book.vcf", "BEGIN:VCARD\nFN:Bo\nEND:VCARD\n"), ("/p2p/identity", "laptop's own key"), ]); let mut phone = Disk::with(&[("/p2p/identity", "phone's own key")]); let (a, b) = sync(&mut laptop, &mut phone, &[], None); same(&laptop, &phone); assert_eq!(phone.text("/apps/notes/long"), Some(big.as_str())); assert_eq!(phone.text("/p2p/identity"), Some("phone's own key")); assert_eq!(b.copied, 3); assert_eq!(b.changed.len(), 3); assert_eq!(a.base.as_ref().unwrap().len(), 3); assert_eq!(a.failed + b.failed, 0); } #[test] fn changes_go_both_ways_and_removals_follow() { let mut laptop = Disk::with(&[ ("/apps/notes/a", "one"), ("/apps/notes/b", "two"), ("/apps/notes/c", "three"), ]); let mut phone = Disk::default(); let (o, _) = sync(&mut laptop, &mut phone, &[], None); let base = o.base.unwrap(); laptop.put("/apps/notes/a", "one, changed on the laptop"); phone.put("/apps/notes/b", "two, changed on the phone"); phone.files.remove("/apps/notes/c"); laptop.put("/apps/notes/d", "new on the laptop"); let (o, p) = sync(&mut laptop, &mut phone, &base, None); same(&laptop, &phone); assert_eq!(laptop.text("/apps/notes/b"), Some("two, changed on the phone")); assert_eq!(phone.text("/apps/notes/a"), Some("one, changed on the laptop")); assert_eq!(laptop.text("/apps/notes/c"), None); assert_eq!(o.conflicts, 0); assert!(o.changed.contains(&"/apps/notes/c".to_string())); assert!(p.changed.contains(&"/apps/notes/d".to_string())); // A second sync right after has nothing to do. let base = o.base.unwrap(); let (o, p) = sync(&mut laptop, &mut phone, &base, None); assert_eq!( (o.copied, p.copied, o.changed.len(), p.changed.len()), (0, 0, 0, 0) ); assert_eq!(o.base.unwrap(), base); } #[test] fn a_log_both_added_to_is_merged() { let mut laptop = Disk::with(&[("/p2p/messages/bo", "hi\n")]); let mut phone = Disk::default(); let base = sync(&mut laptop, &mut phone, &[], None).0.base.unwrap(); laptop.put("/p2p/messages/bo", "hi\nfrom the laptop\n"); phone.put("/p2p/messages/bo", "hi\nfrom the phone\n"); let (o, _) = sync(&mut laptop, &mut phone, &base, None); same(&laptop, &phone); assert_eq!( laptop.text("/p2p/messages/bo"), Some("hi\nfrom the laptop\nfrom the phone\n") ); assert_eq!((o.merged, o.conflicts), (1, 0)); } #[test] fn both_changed_keeps_both() { let mut laptop = Disk::with(&[("/apps/notes/plan.txt", "monday")]); let mut phone = Disk::default(); let base = sync(&mut laptop, &mut phone, &[], None).0.base.unwrap(); laptop.put("/apps/notes/plan.txt", "tuesday"); phone.now = laptop.now + 50; phone.put("/apps/notes/plan.txt", "wednesday"); let (o, _) = sync(&mut laptop, &mut phone, &base, None); same(&laptop, &phone); // The phone's is newer: it keeps the name, the laptop's goes beside it. assert_eq!(laptop.text("/apps/notes/plan.txt"), Some("wednesday")); assert_eq!(laptop.text("/apps/notes/plan (from Laptop).txt"), Some("tuesday")); assert_eq!(o.conflicts, 1); // The other way round: the laptop's newer. let base = o.base.unwrap(); phone.put("/apps/notes/plan.txt", "thursday"); laptop.now = phone.now + 50; laptop.put("/apps/notes/plan.txt", "friday"); let (o, _) = sync(&mut laptop, &mut phone, &base, None); same(&laptop, &phone); assert_eq!(phone.text("/apps/notes/plan.txt"), Some("friday")); assert_eq!(phone.text("/apps/notes/plan (from Phone).txt"), Some("thursday")); assert_eq!(o.conflicts, 1); } #[test] fn two_new_files_of_one_name_are_both_kept() { // No base: never concatenated, though one starts with nothing. let mut laptop = Disk::with(&[("/apps/notes/todo", "laptop's")]); let mut phone = Disk::with(&[("/apps/notes/todo", "phone's")]); let (o, _) = sync(&mut laptop, &mut phone, &[], None); same(&laptop, &phone); assert_eq!((o.conflicts, o.merged), (1, 0)); assert_eq!(laptop.files.len(), 2); } #[test] fn removed_on_one_changed_on_the_other_stays() { let mut laptop = Disk::with(&[("/apps/notes/a", "one")]); let mut phone = Disk::default(); let base = sync(&mut laptop, &mut phone, &[], None).0.base.unwrap(); laptop.files.remove("/apps/notes/a"); phone.put("/apps/notes/a", "one, still wanted"); sync(&mut laptop, &mut phone, &base, None); same(&laptop, &phone); assert_eq!(laptop.text("/apps/notes/a"), Some("one, still wanted")); } #[test] fn a_sync_cut_off_is_finished_by_the_next() { let big: String = "x".repeat(100_000); let mut laptop = Disk::with(&[ ("/apps/notes/a", &big), ("/apps/notes/b", "two"), ("/apps/notes/c", "three"), ]); let mut phone = Disk::default(); sync(&mut laptop, &mut phone, &[], Some(20)); assert!(phone.files.len() < 3); // The base was never kept: the next starts from none, and what came // already is equal on both sides. let (o, _) = sync(&mut laptop, &mut phone, &[], None); same(&laptop, &phone); assert_eq!(o.conflicts, 0); } #[test] fn a_file_that_cannot_be_written_keeps_its_base() { let mut laptop = Disk::with(&[("/apps/notes/a", "one")]); let mut phone = Disk::default(); let base = sync(&mut laptop, &mut phone, &[], None).0.base.unwrap(); laptop.put("/apps/notes/a", "two"); phone.broken = Some("/apps/notes/a".into()); let (o, p) = sync(&mut laptop, &mut phone, &base, None); assert_eq!((o.failed, p.failed), (1, 1)); assert_eq!(o.base.as_ref().unwrap(), &base); // Once it can, the change goes over as a plain one, not a conflict. phone.broken = None; let (o, _) = sync(&mut laptop, &mut phone, &o.base.unwrap(), None); same(&laptop, &phone); assert_eq!(o.conflicts, 0); } #[test] fn the_plan_follows_the_table() { let e = |p: &str, h: u8| Entry { path: p.into(), size: 1, modified: 0, hash: [h; 32], }; let a = |p: &str, h: u8| Agreed { path: p.into(), size: 1, hash: [h; 32], }; let local = vec![ e("/same", 1), e("/mine", 2), e("/theirs", 1), e("/both", 2), e("/gone-there", 1), e("/new-here", 1), ]; let remote = vec![ e("/same", 1), e("/mine", 1), e("/theirs", 2), e("/both", 3), e("/gone-here", 1), e("/new-there", 1), ]; let base = vec![ a("/same", 1), a("/mine", 1), a("/theirs", 1), a("/both", 1), a("/gone-there", 1), a("/gone-here", 1), ]; let mut steps = plan(&local, &remote, &base); steps.sort_by_key(|s| alloc::format!("{s:?}")); assert_eq!( steps, vec![ Step::Both("/both".into()), Step::RemoveHere("/gone-there".into()), Step::RemoveThere("/gone-here".into()), Step::Send("/mine".into()), Step::Send("/new-here".into()), Step::Take("/new-there".into()), Step::Take("/theirs".into()), ] ); } #[test] fn the_index_hashes_only_what_changed() { let mut index = Index::default(); let mut reads = 0; let stats = vec![ ("/a".to_string(), 3, 10), ("/b".to_string(), 3, 20), ("/sync/base/x".to_string(), 3, 5), ]; let mut read = |_: &str| { reads += 1; Some(b"abc".to_vec()) }; let first = index.refresh(&stats, 100, &mut read); assert_eq!(first.len(), 2); let again = index.refresh(&stats, 100, &mut read); assert_eq!(first, again); // `/b` changed in this very second: read again, every time. let stats = vec![("/a".to_string(), 3, 10), ("/b".to_string(), 3, 100)]; index.refresh(&stats, 100, &mut read); index.refresh(&stats, 100, &mut read); assert_eq!(reads, 4); assert_eq!(Index::from_bytes(&index.to_bytes()), index); } #[test] fn beside_fits_a_name() { assert_eq!( beside("/apps/notes/plan.txt", "Ada's laptop"), "/apps/notes/plan (from Ada's laptop).txt" ); assert_eq!(beside("/apps/notes/plan", "Ada"), "/apps/notes/plan (from Ada)"); let long = beside( &alloc::format!("/n/{}.txt", "x".repeat(60)), "A very long device name", ); assert!(long.rsplit('/').next().unwrap().len() <= 58, "{long}"); assert!(long.ends_with(").txt")); } #[test] fn a_backup_restores_and_says_nothing() { let key = [7u8; 32]; let sealed = backup::seal_key("correct horse", [1; 16], 10, &key); assert_eq!(backup::open_key("correct horse", &sealed), Some(key)); assert_eq!(backup::open_key("wrong", &sealed), None); let laptop = Disk::with(&[ ("/apps/notes/a", "one"), ("/apps/notes/b", "one"), ("/apps/notes/c", "secret text"), ]); let files = laptop.manifest(); let (write, stale) = backup::backup_plan(&key, &files, &["old".to_string()]); // Two files alike are one blob. assert_eq!(write.len(), 2); assert_eq!(stale, vec!["old".to_string()]); let mut blobs = Map::new(); for e in write { let blob = backup::seal_blob(&key, laptop.files[&e.path].0.as_slice()); assert!(!blob.windows(6).any(|w| w == b"secret")); blobs.insert(backup::blob_name(&key, &e.hash), blob); } let index = backup::seal_index(&key, [3; 12], &backup::index_of(&files)); assert!(!index.windows(5).any(|w| w == b"notes")); // A new device: only its own identity. let mut phone = Disk::with(&[("/p2p/identity", "phone's")]); let index = backup::open_index(&key, &index).unwrap(); for a in backup::restore_plan(&index, &phone.manifest()) { let blob = &blobs[&backup::blob_name(&key, &a.hash)]; let data = backup::open_blob(&key, &a.hash, blob).unwrap(); phone.write(&a.path, &data); } same(&laptop, &phone); // A blob changed on the disk does not open. let mut bad = blobs.values().next().unwrap().clone(); bad[0] ^= 1; assert!(backup::open_blob(&key, &index[0].hash, &bad).is_none()); } /// Each device's Bluetooth identity and bonds stay its own: another device /// with the same identity would answer as this one. #[test] fn bluetooth_keys_stay_on_their_device() { let mut laptop = Disk::with(&[ ("/apps/notes/shopping", "bread\n"), ("/bt/identity", "laptop's radio"), ("/bt/bonds", "laptop's bonds"), ]); let mut phone = Disk::with(&[("/bt/identity", "phone's radio")]); sync(&mut laptop, &mut phone, &[], None); assert_eq!(phone.text("/apps/notes/shopping"), Some("bread\n")); assert_eq!(phone.text("/bt/identity"), Some("phone's radio")); assert_eq!(phone.text("/bt/bonds"), None); } /// Each device's list of past notifications stays its own: what it showed /// and what was seen there, which the display server writes whole. #[test] fn notifications_stay_on_their_device() { let mut laptop = Disk::with(&[ ("/apps/notes/shopping", "bread\n"), ("/display/notices", "laptop's list"), ]); let mut phone = Disk::with(&[("/display/notices", "phone's list")]); sync(&mut laptop, &mut phone, &[], None); assert_eq!(phone.text("/apps/notes/shopping"), Some("bread\n")); assert_eq!(phone.text("/display/notices"), Some("phone's list")); assert_eq!(laptop.text("/display/notices"), Some("laptop's list")); }