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

138 lines
5.6 KiB
Rust

#![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 {
offset_min: None,
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
}