[format][library] Books: EPUB/FB2/TXT/MOBI/AZW3 into one sanitized model, CFI anchors, the event-log library, stats, CSV import, export

This commit is contained in:
2026-11-17 01:36:21 +01:00
parent 0b0e35d727
commit 8729119984
35 changed files with 7956 additions and 0 deletions
+136
View File
@@ -0,0 +1,136 @@
#![allow(dead_code)]
//! A seeded generator of plausible operations from several devices.
use liber_library::library::{BookFile, BookInfo, Colour, Field, GoalKind, Mark, Outcome, Person, Possession, Series};
use liber_library::{Clock, Event, Op};
use serde_json::json;
pub struct Rng(pub u64);
impl Rng {
pub fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
pub fn below(&mut self, n: u64) -> u64 {
self.next() % n.max(1)
}
pub fn pick<'a, T>(&mut self, v: &'a [T]) -> &'a T {
&v[self.below(v.len() as u64) as usize]
}
}
pub const BOOKS: &[&str] = &["b-valka", "b-dune", "b-rur", "b-babicka"];
pub fn info(i: usize) -> BookInfo {
let titles = ["Válka s mloky", "Dune", "R.U.R.", "Babička"];
BookInfo {
title: titles[i].into(),
authors: vec![["Karel Čapek", "Frank Herbert", "Karel Čapek", "Božena Němcová"][i].into()],
isbn13: [Some("9788020712479"), Some("9780441172719"), None, None][i].map(str::to_owned),
fingerprint: [None, None, Some("fp-rur"), None][i].map(str::to_owned),
pages: Some([280, 604, 100, 320][i]),
series: (i == 1).then(|| Series { name: "Dune".into(), index: Some(1.0) }),
genres: vec!["classic".into()],
added: 1_700_000_000_000 + i as u64,
..BookInfo::default()
}
}
/// One random operation by `dev` (its own ids carry the device name, so they never collide).
pub fn op(r: &mut Rng, dev: &str, n: usize) -> Op {
let bi = r.below(BOOKS.len() as u64) as usize;
let book = BOOKS[bi].to_string();
let hl = format!("h-{dev}-{}", r.below(6));
let date = format!("2025-{:02}-{:02}", 1 + r.below(12), 1 + r.below(28));
match r.below(17) {
0 | 1 => Op::BookAdd { book, info: info(bi), restore: false },
2 => Op::BookSet { book, field: Field::Review, value: json!(format!("review {dev} {n}")), base: None },
3 => Op::BookSet { book, field: Field::Rating, value: json!(1 + r.below(10)), base: None },
4 => Op::ShelfAdd { book, shelf: r.pick(&["klasika", "sci-fi", "favourites"]).to_string() },
5 => Op::ShelfRemove { book, shelf: r.pick(&["klasika", "sci-fi", "favourites"]).to_string() },
6 => Op::Position {
book,
cfi: format!("epubcfi(/6/{}!/4/2/1:{})", 2 * (1 + r.below(5)), r.below(100)),
chapter: r.below(5) as u32,
progress: r.below(1000) as f64 / 1000.0,
label: Some(format!("{}", r.below(300))),
},
7 => Op::HighlightAdd {
id: hl,
book,
kind: *r.pick(&[Mark::Highlight, Mark::Note, Mark::Bookmark]),
anchor: json!({"chapter": r.below(5), "quote": {"exact": format!("quote {dev} {n}"), "prefix": "", "suffix": ""}}),
colour: *r.pick(&[Colour::Yellow, Colour::Green, Colour::Blue, Colour::Pink]),
note: format!("note {dev} {n}"),
created: 1_700_000_000_000 + n as u64,
},
8 => Op::HighlightSet { id: hl, colour: Some(Colour::Pink), note: Some(format!("edit {dev} {n}")), base: None },
9 => Op::HighlightRemove { id: hl },
10 => Op::ReadStart { book, read: format!("r-{dev}-{n}"), date: Some(date) },
11 => Op::ReadEnd {
read: format!("r-{dev}-{}", n.saturating_sub(1 + r.below(4) as usize)),
date: Some(date),
outcome: *r.pick(&[Outcome::Read, Outcome::DidNotFinish]),
},
12 => Op::Lend {
loan: format!("l-{dev}-{n}"),
book,
person: Person { id: None, name: "Jana".into() },
since: date,
due: None,
},
13 => Op::Return { loan: format!("l-{dev}-{}", n.saturating_sub(1 + r.below(4) as usize)), date },
14 => Op::Session {
id: format!("s-{dev}-{n}"),
book,
start: 1000,
end: 1000 + r.below(600_000),
active_ms: r.below(400_000),
pages: r.below(30) as u32,
date,
},
15 => Op::BookSet {
book,
field: Field::Possession,
value: serde_json::to_value(r.pick(&[
Possession::Owned,
Possession::Wishlist,
Possession::Borrowed {
from: Person { id: Some("p1".into()), name: "Petr".into() },
due: Some("2025-12-01".into()),
},
]))
.unwrap(),
base: None,
},
_ => match r.below(3) {
0 => Op::Goal { year: 2025, kind: GoalKind::Books, target: 10 + r.below(40) as u32 },
1 => Op::BookFileAdd {
book,
file: BookFile {
sha256: format!("{:064x}", r.below(4)),
format: "epub".into(),
size: 1000,
name: "x.epub".into(),
},
},
_ => Op::BookSet { book, field: Field::Notes, value: json!(format!("notes {dev} {n}")), base: None },
},
}
}
/// `count` events from device `dev`, its clock `skew_ms` off the shared timeline.
pub fn events(seed: u64, dev: &str, count: usize, skew_ms: i64) -> Vec<Event> {
let mut r = Rng(seed | 1);
let mut c = Clock::default();
let mut out = Vec::new();
let mut t: i64 = 1_750_000_000_000;
for n in 0..count {
t += r.below(5_000) as i64;
let hlc = c.tick((t + skew_ms) as u64);
out.push(Event { id: format!("{dev}-{n}"), hlc, device: dev.into(), op: op(&mut r, dev, n) });
}
out
}
+139
View File
@@ -0,0 +1,139 @@
//! Mandatory test 4: export, then import into an empty library, reproduces books, states, shelves, highlights and
//! stats exactly.
mod common;
use common::{events, info};
use liber_library::export::{from_json, to_json, write_zip};
use liber_library::library::{Colour, Field, Mark};
use liber_library::stats::stats;
use liber_library::{Clock, Event, Library, Op};
use proptest::prelude::*;
use serde_json::json;
use std::io::Read;
fn assert_round_trip(lib: &Library) {
let json = to_json(lib, "2026-11-17T10:00:00Z");
let back = from_json(&json).expect("import");
assert_eq!(&back, lib);
for y in [None, Some(2024), Some(2025), Some(2026)] {
assert_eq!(stats(&back, y), stats(lib, y), "stats {y:?}");
}
// Exporting the imported library gives the same file.
assert_eq!(to_json(&back, "2026-11-17T10:00:00Z"), json);
}
proptest! {
#![proptest_config(ProptestConfig { cases: 150, ..ProptestConfig::default() })]
#[test]
fn random_libraries_round_trip(seed in any::<u64>(), n in 1usize..120) {
let mut all = events(seed, "phone", n, 0);
all.extend(events(seed ^ 0x5555, "desk", n / 2, 90_000));
let lib = Library::from_events(&all);
assert_round_trip(&lib);
}
}
#[test]
fn a_library_with_conflicts_round_trips() {
let mut c = Clock::default();
let mut d = Clock::default();
let mut e = |id: &str, dev: &str, t: u64, op: Op| {
let hlc = if dev == "a" { c.tick(t) } else { d.tick(t) };
Event { id: id.into(), hlc, device: dev.into(), op }
};
let evs = vec![
e("1", "a", 1, Op::BookAdd { book: "b".into(), info: info(0), restore: false }),
e("2", "a", 2, Op::BookSet { book: "b".into(), field: Field::Review, value: json!("A"), base: None }),
e(
"3",
"a",
3,
Op::BookSet { book: "b".into(), field: Field::Review, value: json!("B"), base: Some("2".into()) },
),
e(
"4",
"b",
3,
Op::BookSet { book: "b".into(), field: Field::Review, value: json!("C"), base: Some("2".into()) },
),
e(
"5",
"a",
4,
Op::HighlightAdd {
id: "h".into(),
book: "b".into(),
kind: Mark::Note,
anchor: json!({"quote": {"exact": "slovo"}}),
colour: Colour::Green,
note: "x".into(),
created: 4,
},
),
e(
"6",
"a",
5,
Op::HighlightSet { id: "h".into(), colour: None, note: Some("y".into()), base: Some("5".into()) },
),
e(
"7",
"b",
5,
Op::HighlightSet { id: "h".into(), colour: None, note: Some("z".into()), base: Some("5".into()) },
),
e("8", "a", 6, Op::BookAdd { book: "same-isbn".into(), info: info(1), restore: false }),
e(
"9",
"a",
7,
Op::BookSet { book: "b".into(), field: Field::Isbn13, value: json!("9780441172719"), base: None },
),
];
let lib = Library::from_events(&evs);
assert!(lib.books["b"].review.conflict.is_some());
assert!(lib.highlights["h"].note.conflict.is_some());
assert_eq!(lib.books.len(), 2, "two books share an ISBN after an edit; the export keeps both");
assert_round_trip(&lib);
}
#[test]
fn the_zip_holds_json_csv_markdown_and_files() {
let mut all = events(42, "phone", 200, 0);
all.push(Event {
id: "file".into(),
hlc: liber_library::Hlc { wall: u64::MAX / 2, logical: 0 },
device: "phone".into(),
op: Op::BookFileAdd {
book: "b-valka".into(),
file: liber_library::library::BookFile {
sha256: "ab".repeat(32),
format: "epub".into(),
size: 5,
name: "v.epub".into(),
},
},
});
let lib = Library::from_events(&all);
let bytes = write_zip(&lib, Vec::new(), "2026-11-17T10:00:00Z", &mut |_, f| {
(f.sha256 == "ab".repeat(32)).then(|| Box::new(&b"EPUB!"[..]) as Box<dyn Read>)
})
.unwrap();
let z = liber_format::zip::Zip::parse(&bytes, &liber_format::Limits::default()).unwrap();
let names: Vec<&str> = z.entries().iter().map(|e| e.name.as_str()).collect();
assert!(names.contains(&"library.json") && names.contains(&"books.csv"));
if !lib.highlights.is_empty() {
assert!(names.iter().any(|n| n.starts_with("highlights/") && n.ends_with(".md")));
}
let file = names.iter().find(|n| n.starts_with("files/")).expect("the book file");
assert_eq!(z.read_name(file).unwrap().unwrap(), b"EPUB!");
let json = String::from_utf8(z.read_name("library.json").unwrap().unwrap()).unwrap();
assert_eq!(from_json(&json).unwrap(), lib);
}
#[test]
fn a_foreign_or_newer_export_is_refused() {
assert!(from_json("{}").is_err());
assert!(from_json(r#"{"format":"liber-export","version":2,"exported_at":"x","library":{"books":{},"highlights":{},"sessions":{},"goals":{}}}"#).is_err());
assert!(from_json(r#"{"format":"liber-export","version":1,"exported_at":"x","library":{"books":{},"highlights":{},"sessions":{},"goals":{}},"extra":1}"#).is_err());
}
+152
View File
@@ -0,0 +1,152 @@
//! Mandatory test 3: Goodreads and StoryGraph CSVs (quotes, commas, Czech) import every row; unknown columns are
//! reported and kept; hostile CSVs (formula injection, a 100 MB line) are handled safely.
use liber_library::import::{ImportError, Source, import_csv};
use liber_library::{Clock, Event, Library, Op, ReadStatus};
pub const GOODREADS: &str = "\u{feff}Book Id,Title,Author,Author l-f,Additional Authors,ISBN,ISBN13,My Rating,Average Rating,Publisher,Binding,Number of Pages,Year Published,Original Publication Year,Date Read,Date Added,Bookshelves,Bookshelves with positions,Exclusive Shelf,My Review,Spoiler,Private Notes,Read Count,Owned Copies,My Custom Column\n\
1,\"Válka s mloky\",Karel Čapek,\"Čapek, Karel\",,\"=\"\"802071247X\"\"\",\"=\"\"\"\"\",5,4.10,\"Československý spisovatel\",Paperback,280,2004,1936,2023/05/14,2023/01/02,\"klasika, favourites\",\"klasika (#3), favourites (#1)\",read,\"Skvělé!<br/><br/>Mloci, \"\"lidé\"\" a obchod.\",,soukromá poznámka,2,1,custom value\n\
2,\"Dune, Part One\",Frank Herbert,\"Herbert, Frank\",\"Someone Else\",\"=\"\"0441172717\"\"\",\"=\"\"9780441172719\"\"\",0,4.25,Ace,Mass Market Paperback,604,1990,1965,,2024/02/03,to-read,to-read (#4),to-read,,,,0,0,\n\
3,R.U.R.,Karel Čapek,\"Čapek, Karel\",,,,3,3.80,,Kindle Edition,100,2010,1920,,2024/03/01,currently-reading,,currently-reading,,,,1,0,\n";
pub const STORYGRAPH: &str = "Title,Authors,Contributors,ISBN/UID,Format,Read Status,Date Added,Last Date Read,Dates Read,Read Count,Moods,Pace,Character- or Plot-Driven?,Strong Character Development?,Loveable Characters?,Diverse Characters?,Flawed Characters?,Star Rating,Review,Content Warnings,Content Warning Description,Tags,Owned?\n\
Babička,Božena Němcová,,9788020712479,paperback,read,2023/01/01,2023/02/10,\"2022/12/01-2022/12/20, 2023/01/15-2023/02/10\",2,\"reflective, emotional, cozy\",slow,Character,Yes,Yes,No,Yes,4.25,\"Krásná, \"\"klidná\"\" kniha.\",,,\"czech, classics\",Yes\n\
Neznámá kniha,\"A. Author, B. Author\",,abc-uid-123,digital,did-not-finish,2023/03/01,2023/03/05,,0,,,,,,,,0,,,,,No\n\
Další,C. Author,,,audio,to-read,2023/04/01,,,0,,,,,,,,,,,,,No\n";
fn ids() -> impl FnMut() -> String {
let mut n = 0;
move || {
n += 1;
format!("id{n:04}")
}
}
pub fn apply(lib_ops: Vec<Op>) -> Library {
let mut c = Clock::default();
let events: Vec<Event> = lib_ops
.into_iter()
.enumerate()
.map(|(i, op)| Event { id: format!("e{i}"), hlc: c.tick(1_700_000_000_000), device: "d".into(), op })
.collect();
Library::from_events(&events)
}
#[test]
fn goodreads_imports_every_row() {
let (ops, r) = import_csv(GOODREADS.as_bytes(), &Library::default(), &mut ids(), 0).unwrap();
assert_eq!(r.source, Source::Goodreads);
assert_eq!((r.rows, r.imported), (3, 3), "{:?}", r.skipped);
assert_eq!(r.unknown_columns, vec!["My Custom Column"]);
assert!(r.unused_columns.contains(&"Average Rating".to_owned()));
let lib = apply(ops);
let valka = lib.books.values().find(|b| b.info.title == "Válka s mloky").unwrap();
assert_eq!(valka.info.isbn13.as_deref(), Some("9788020712479"));
assert_eq!(valka.info.authors, vec!["Karel Čapek"]);
assert_eq!(valka.info.publisher.as_deref(), Some("Československý spisovatel"));
assert_eq!(valka.info.published.as_deref(), Some("1936"));
assert_eq!(valka.rating, Some(10));
assert_eq!(valka.review.value, "Skvělé!\n\nMloci, \"lidé\" a obchod.");
assert_eq!(valka.notes.value, "soukromá poznámka");
assert_eq!(valka.status(), ReadStatus::Read);
assert_eq!(valka.reads.len(), 2, "read twice");
assert_eq!(valka.reads[1].finished.as_deref(), Some("2023-05-14"));
assert!(valka.paper);
assert_eq!(valka.shelves.iter().cloned().collect::<Vec<_>>(), vec!["favourites", "klasika"]);
assert_eq!(valka.info.import_extra.get("goodreads:My Custom Column").map(String::as_str), Some("custom value"));
assert_eq!(valka.info.import_extra.get("goodreads:Book Id").map(String::as_str), Some("1"));
let dune = lib.books.values().find(|b| b.info.title == "Dune, Part One").unwrap();
assert_eq!(dune.info.authors, vec!["Frank Herbert", "Someone Else"]);
assert_eq!(dune.status(), ReadStatus::ToRead);
assert_eq!(dune.rating, None);
let rur = lib.books.values().find(|b| b.info.title == "R.U.R.").unwrap();
assert_eq!(rur.status(), ReadStatus::Reading);
assert!(!rur.paper);
}
#[test]
fn storygraph_imports_every_row() {
let (ops, r) = import_csv(STORYGRAPH.as_bytes(), &Library::default(), &mut ids(), 0).unwrap();
assert_eq!(r.source, Source::StoryGraph);
assert_eq!((r.rows, r.imported), (3, 3), "{:?}", r.skipped);
assert!(r.unknown_columns.is_empty());
let lib = apply(ops);
let b = lib.books.values().find(|b| b.info.title == "Babička").unwrap();
assert_eq!(b.reads.len(), 2);
assert_eq!(b.reads[0].started.as_deref(), Some("2022-12-01"));
assert_eq!(b.reads[1].finished.as_deref(), Some("2023-02-10"));
assert_eq!(b.rating, Some(9), "4.25 stars rounds to 4.5");
assert_eq!(b.moods.iter().cloned().collect::<Vec<_>>(), vec!["emotional", "reflective"]);
assert!(b.tags.contains("cozy") && b.tags.contains("czech"));
assert_eq!(b.review.value, "Krásná, \"klidná\" kniha.");
assert_eq!(b.info.import_extra.get("storygraph:Pace").map(String::as_str), Some("slow"));
let n = lib.books.values().find(|b| b.info.title == "Neznámá kniha").unwrap();
assert_eq!(n.status(), ReadStatus::DidNotFinish);
assert_eq!(n.info.authors, vec!["A. Author", "B. Author"]);
assert_eq!(n.info.import_extra.get("storygraph:ISBN/UID").map(String::as_str), Some("abc-uid-123"));
}
#[test]
fn windows_1250_csv() {
let plain = GOODREADS.replace('\u{feff}', "");
let (bytes, _, _) = encoding_rs::WINDOWS_1250.encode(&plain);
let (ops, r) = import_csv(&bytes, &Library::default(), &mut ids(), 0).unwrap();
assert_eq!(r.imported, 3);
assert!(apply(ops).books.values().any(|b| b.info.title == "Válka s mloky"));
}
#[test]
fn importing_twice_adds_nothing() {
let (ops, _) = import_csv(GOODREADS.as_bytes(), &Library::default(), &mut ids(), 0).unwrap();
let lib = apply(ops);
let (ops2, r) = import_csv(GOODREADS.as_bytes(), &lib, &mut ids(), 0).unwrap();
assert!(ops2.is_empty());
assert_eq!(r.skipped.len(), 3);
}
#[test]
fn formula_injection_is_stored_as_text_and_exported_inert() {
let csv = "Title,Authors,ISBN/UID,Read Status,Review\n\"=HYPERLINK(\"\"http://evil\"\",\"\"x\"\")\",@SUM(A1),,to-read,+cmd|' /C calc'!A0\n";
let (ops, r) = import_csv(csv.as_bytes(), &Library::default(), &mut ids(), 0).unwrap();
assert_eq!(r.imported, 1);
let lib = apply(ops);
let b = lib.books.values().next().unwrap();
assert_eq!(b.info.title, "=HYPERLINK(\"http://evil\",\"x\")");
let out = liber_library::export::books_csv(&lib);
assert!(out.contains("'=HYPERLINK"), "{out}");
assert!(out.contains("'@SUM(A1)"));
assert!(out.contains("'+cmd"));
for line in out.lines().skip(1) {
for cell in line.split(',') {
let c = cell.trim_start_matches('"');
assert!(!c.starts_with(['=', '+', '@']), "{cell}");
}
}
}
#[test]
fn a_100_mb_line_is_refused_early_and_a_huge_field_is_cut() {
let mut csv = String::from("Title,Authors,ISBN/UID,Read Status,Review\n");
csv.push_str(&"x".repeat(100 * 1024 * 1024));
let t = std::time::Instant::now();
assert_eq!(import_csv(csv.as_bytes(), &Library::default(), &mut ids(), 0).unwrap_err(), ImportError::TooLarge);
assert!(t.elapsed().as_secs() < 5);
let mut csv = String::from("Title,Authors,ISBN/UID,Read Status,Review\nBig,A,,read,\"");
csv.push_str(&"ř".repeat(5 * 1024 * 1024));
csv.push_str("\"\n");
let (ops, r) = import_csv(csv.as_bytes(), &Library::default(), &mut ids(), 0).unwrap();
assert_eq!(r.imported, 1);
assert_eq!(r.truncated, vec![(1, "Review".to_owned())]);
let lib = apply(ops);
assert!(lib.books.values().next().unwrap().review.value.len() <= 64 * 1024);
}
#[test]
fn not_an_export() {
assert_eq!(
import_csv(b"a,b,c\n1,2,3\n", &Library::default(), &mut ids(), 0).unwrap_err(),
ImportError::UnknownFormat
);
let junk: Vec<u8> = (0..50_000u32).map(|i| (i * 31 % 251) as u8).collect();
assert!(import_csv(&junk, &Library::default(), &mut ids(), 0).is_err());
}
+69
View File
@@ -0,0 +1,69 @@
mod common;
use common::info;
use liber_library::library::{GoalKind, Outcome};
use liber_library::stats::{active_ms, stats};
use liber_library::{Clock, Event, Library, Op};
use serde_json::json;
#[test]
fn yearly_and_all_time() {
let mut c = Clock::default();
let mut n = 0;
let mut e = |op: Op| {
n += 1;
Event { id: format!("e{n}"), hlc: c.tick(n), device: "d".into(), op }
};
let evs = vec![
e(Op::BookAdd { book: "a".into(), info: info(0), restore: false }),
e(Op::BookAdd { book: "b".into(), info: info(1), restore: false }),
e(Op::BookAdd { book: "c".into(), info: info(2), restore: false }),
e(Op::BookSet {
book: "a".into(),
field: liber_library::library::Field::Moods,
value: json!(["dark", "tense"]),
base: None,
}),
e(Op::ReadStart { book: "a".into(), read: "r1".into(), date: Some("2025-01-02".into()) }),
e(Op::ReadEnd { read: "r1".into(), date: Some("2025-02-01".into()), outcome: Outcome::Read }),
e(Op::ReadStart { book: "b".into(), read: "r2".into(), date: Some("2025-03-01".into()) }),
e(Op::ReadEnd { read: "r2".into(), date: Some("2025-04-01".into()), outcome: Outcome::Read }),
e(Op::ReadStart { book: "c".into(), read: "r3".into(), date: None }),
e(Op::ReadEnd { read: "r3".into(), date: Some("2024-05-01".into()), outcome: Outcome::DidNotFinish }),
e(Op::ReadStart { book: "a".into(), read: "r4".into(), date: Some("2026-01-01".into()) }),
e(Op::ReadEnd { read: "r4".into(), date: Some("2026-01-20".into()), outcome: Outcome::Read }),
e(Op::Session {
id: "s1".into(),
book: "a".into(),
start: 0,
end: 3_600_000,
active_ms: 1_800_000,
pages: 30,
date: "2025-01-10".into(),
}),
e(Op::Session {
id: "s2".into(),
book: "b".into(),
start: 0,
end: 3_600_000,
active_ms: 9_999_999_999,
pages: 60,
date: "2025-03-10".into(),
}),
e(Op::Goal { year: 2025, kind: GoalKind::Books, target: 12 }),
];
let lib = Library::from_events(&evs);
let s = stats(&lib, Some(2025));
assert_eq!((s.books, s.did_not_finish, s.pages), (2, 0, 280 + 604));
assert_eq!(s.active_minutes, 30 + 60, "a session's active time is capped at its length");
assert_eq!(s.pace, Some(60.0));
assert_eq!(s.longest, Some(("b".into(), 604)));
assert_eq!(s.shortest, Some(("a".into(), 280)));
assert_eq!(s.moods.get("dark"), Some(&1));
assert_eq!(s.genres.get("classic"), Some(&2));
let g = s.goal.unwrap();
assert_eq!((g.target, g.done), (12, 2));
let all = stats(&lib, None);
assert_eq!((all.books, all.did_not_finish), (3, 1), "a re-read counts again");
assert_eq!(stats(&lib, Some(2024)).did_not_finish, 1);
assert_eq!(active_ms(10 * 60_000), 2 * 60_000, "two minutes per page at most");
}
+192
View File
@@ -0,0 +1,192 @@
//! 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"));
}