use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use legit_hamming::service::{
Catalog, ErrorType, Lane, Limits, LoadConfig, Service, ServiceError, SetSpec, log as change_log,
};
use legit_hamming::{Records, Value, snapshot};
use serde_json::{Value as Json, json};
use crate::service::SetDir;
use crate::support::{Rng, TempDir};
const INDEX: &str = "images";
pub struct Harness {
pub set: SetDir,
pub state: TempDir,
pub limits: Limits,
pub repeat_window: Duration,
pub service: Option<Service>,
pub events: Vec<String>,
}
impl Harness {
pub fn new(limits: Limits) -> Self {
let state = TempDir::new();
fs::create_dir_all(&state.0).expect("a state directory");
Self {
set: SetDir::new(),
state,
limits,
repeat_window: Duration::from_secs(3600),
service: None,
events: Vec::new(),
}
}
pub fn config(&self, write: bool) -> LoadConfig {
let mut config = crate::service::load_config(false);
config.state_dir = Some(self.state.0.clone());
config.write_changes = write;
config.repeat_window = self.repeat_window;
config.max_log_read_bytes = self.limits.log_read_bound();
config
}
pub fn open(&mut self) {
self.service = None;
let catalog =
Catalog::new(vec![SetSpec::index(INDEX, self.set.path())], self.config(true)).expect("the catalog opens");
let service = Service::new(Arc::new(catalog), self.limits, 2);
self.service = Some(service);
self.refresh();
}
pub fn refresh(&mut self) {
let mut events = Vec::new();
self.service()
.catalog()
.refresh(&mut |event| events.push(format!("{event:?}")));
self.events.extend(events);
}
pub fn service(&self) -> &Service {
self.service.as_ref().expect("open")
}
pub fn log_path(&self) -> PathBuf {
self.state.0.join(INDEX).join(change_log::LOG_FILE)
}
pub fn change(&self, task_id: &str, name: &str, options: &Json) -> Result<Json, ServiceError> {
self.service()
.change(task_id, name, &options.to_string())
.map(|json| serde_json::from_str(&json).expect("a result is JSON"))
}
pub fn stats(&self) -> Json {
let options = json!({"format": 1, "index": INDEX}).to_string();
serde_json::from_str(&self.service().stats(&options).expect("stats")).expect("JSON")
}
pub fn search(&self, options: &Json) -> Result<Json, ServiceError> {
crate::service::search(self.service(), options, Lane::Bulk)
}
}
fn records_options<V: Value>(records: &[(u64, V)]) -> Json {
json!({
"format": 1, "index": INDEX, "width": V::BITS,
"records": records.iter().map(|(id, value)| json!([id, value.to_hex()])).collect::<Vec<_>>(),
})
}
fn remove_options<V: Value>(ids: &[u64]) -> Json {
json!({"format": 1, "index": INDEX, "width": V::BITS, "ids": ids})
}
type Task<V> = (&'static str, Vec<(u64, Option<V>)>);
type Held<V> = Option<(BTreeMap<u64, V>, u64)>;
#[derive(Debug, Clone, PartialEq)]
enum Answer {
Applied(Json),
Conflict(Vec<u64>, u64),
}
fn answer(result: Result<Json, ServiceError>) -> Answer {
match result {
Ok(json) => Answer::Applied(json),
Err(error) if error.error_type == ErrorType::Conflict => {
Answer::Conflict(error.ids.clone().expect("ids"), error.count.expect("a count"))
}
Err(error) => panic!("a change was refused: {error}"),
}
}
struct Model<V> {
origin: BTreeMap<u64, V>,
history: BTreeMap<u64, Vec<(u64, Option<V>)>>,
truth: BTreeMap<u64, V>,
position: u64,
base: u64,
sent: Vec<(String, &'static str, Json, Answer)>,
}
impl<V: Value> Model<V> {
fn at(&self, id: u64, seq: u64) -> Option<V> {
match self
.history
.get(&id)
.and_then(|changes| changes.iter().rev().find(|(at, _)| *at <= seq))
{
Some((_, value)) => *value,
None => self.origin.get(&id).copied(),
}
}
fn apply(&mut self, name: &'static str, records: &[(u64, Option<V>)]) -> Answer {
let mut conflicts = Vec::new();
let (mut added, mut changed, mut removed, mut unchanged) = (0, 0, 0, 0);
for &(id, value) in records {
match (self.truth.get(&id), value) {
(Some(held), Some(value)) if *held == value => unchanged += 1,
(Some(_), Some(_)) if name == "append" => conflicts.push(id),
(Some(_), Some(_)) => changed += 1,
(None, Some(_)) => added += 1,
(Some(_), None) => removed += 1,
(None, None) => unchanged += 1,
}
}
if !conflicts.is_empty() {
let count = conflicts.len() as u64;
conflicts.truncate(100);
return Answer::Conflict(conflicts, count);
}
for &(id, value) in records {
self.position += 1;
self.history.entry(id).or_default().push((self.position, value));
match value {
Some(value) => self.truth.insert(id, value),
None => self.truth.remove(&id),
};
}
Answer::Applied(json!({
"format": 1, "index": INDEX, "seq": self.position,
"added": added, "changed": changed, "removed": removed, "unchanged": unchanged,
}))
}
}
fn reference<V: Value>(
truth: &BTreeMap<u64, V>,
query: V,
radius: u32,
limit: Option<usize>,
max_matches: usize,
exclude_zero: bool,
) -> (Vec<Json>, Option<&'static str>) {
let mut found: Vec<(u32, u64, V)> = truth
.iter()
.map(|(&id, &value)| (value.distance(&query), id, value))
.filter(|&(distance, _, value)| distance <= radius && !(exclude_zero && value.is_zero()))
.collect();
found.sort_unstable_by_key(|&(distance, id, _)| (distance, id));
let keep = match limit {
Some(limit) if limit <= max_matches => (limit, "limit"),
_ => (max_matches, "size"),
};
let cut = (found.len() > keep.0).then_some(keep.1);
found.truncate(keep.0);
let matches = found
.into_iter()
.map(|(distance, id, value)| json!({"id": id, "value": value.to_hex(), "distance": distance}))
.collect();
(matches, cut)
}
fn value<V: Value>(rng: &mut Rng, centres: &[V]) -> V {
if rng.below(40) == 0 {
return V::from_words(&[0; 4][..V::WORDS]);
}
let centre = centres[rng.below(centres.len())];
let flips = rng.below(V::BITS as usize / 10) as u32;
rng.flip(centre, flips)
}
fn id(rng: &mut Rng) -> u64 {
if rng.below(20) == 0 {
u64::MAX - rng.below(4) as u64
} else {
rng.below(240) as u64
}
}
fn ids(rng: &mut Rng, most: usize) -> Vec<u64> {
let mut ids: Vec<u64> = (0..1 + rng.below(most)).map(|_| id(rng)).collect();
ids.sort_unstable();
ids.dedup();
ids
}
fn records_of<V: Value>(map: &BTreeMap<u64, V>) -> Records<V> {
Records::from_records(map.iter().map(|(&id, &value)| (id, value))).expect("ids rise")
}
fn model<V: Value>(seed: u64, steps: usize, limits: Limits) {
let mut rng = Rng::new(seed);
let centres: Vec<V> = (0..6).map(|_| rng.value()).collect();
let max_radius = if V::BITS == 64 { 12 } else { 40 };
let mut origin = BTreeMap::new();
for _ in 0..150 {
origin.insert(id(&mut rng), value(&mut rng, ¢res));
}
let mut harness = Harness::new(limits);
harness.set.publish("s0", &records_of(&origin));
harness.open();
let mut model = Model {
truth: origin.clone(),
origin,
history: BTreeMap::new(),
position: 0,
base: 0,
sent: Vec::new(),
};
let mut snapshot = "s0".to_owned();
let mut snapshots = 0;
let mut counts = BTreeMap::<&str, usize>::new();
for step in 0..steps {
let roll = rng.below(100);
let what = match roll {
0..=19 => {
let records: Vec<(u64, Option<V>)> = ids(&mut rng, 12)
.into_iter()
.map(|id| {
let same = model.truth.get(&id).copied().filter(|_| rng.below(2) == 0);
(id, Some(same.unwrap_or_else(|| value(&mut rng, ¢res))))
})
.collect();
send(&harness, &mut model, "append", &records, step)
}
20..=37 => {
let records: Vec<(u64, Option<V>)> = ids(&mut rng, 12)
.into_iter()
.map(|id| {
let same = model.truth.get(&id).copied().filter(|_| rng.below(4) == 0);
(id, Some(same.unwrap_or_else(|| value(&mut rng, ¢res))))
})
.collect();
send(&harness, &mut model, "replace", &records, step)
}
38..=49 => {
let records: Vec<(u64, Option<V>)> = ids(&mut rng, 12).into_iter().map(|id| (id, None)).collect();
send(&harness, &mut model, "remove", &records, step)
}
50..=57 if !model.sent.is_empty() => {
let (task_id, name, options, first) = model.sent[rng.below(model.sent.len())].clone();
assert_eq!(
answer(harness.change(&task_id, name, &options)),
first,
"step {step}: a repeat"
);
"repeat"
}
58..=61 => {
snapshots += 1;
let name = format!("s{snapshots}");
let refused = swap(&mut harness, &mut model, &mut rng, &name);
if refused {
harness.set.point(&snapshot);
} else {
snapshot = name;
}
if refused { "refused snapshot" } else { "swap" }
}
62..=63 => {
harness.open();
"restart"
}
_ => "search",
};
*counts.entry(what).or_default() += 1;
check(&harness, &model, &mut rng, ¢res, &snapshot, max_radius, step);
}
for what in [
"append",
"replace",
"remove",
"repeat",
"swap",
"refused snapshot",
"restart",
] {
assert!(
counts.get(what).copied().unwrap_or(0) >= 3,
"too few `{what}` steps: {counts:?}"
);
}
}
fn send<V: Value>(
harness: &Harness,
model: &mut Model<V>,
name: &'static str,
records: &[(u64, Option<V>)],
step: usize,
) -> &'static str {
let task_id = format!("app_{step}");
let options = if name == "remove" {
remove_options::<V>(&records.iter().map(|&(id, _)| id).collect::<Vec<_>>())
} else {
let records: Vec<(u64, V)> = records
.iter()
.map(|&(id, value)| (id, value.expect("a value")))
.collect();
records_options(&records)
};
let expected = model.apply(name, records);
let got = answer(harness.change(&task_id, name, &options));
assert_eq!(got, expected, "step {step}: `{name}`");
model.sent.push((task_id, name, options, expected));
name
}
fn swap<V: Value>(harness: &mut Harness, model: &mut Model<V>, rng: &mut Rng, name: &str) -> bool {
let roll = rng.below(10);
let (covers, from, bad) = match roll {
0 => (Some(model.position + 1 + rng.below(3) as u64), model.position, true),
1 if model.base > 0 => (Some(model.base - 1), model.position, true),
2 if model.base > 0 => (None, model.position, true),
2..=3 if model.base == 0 => (None, 0, false),
_ => {
let covers = model.base + rng.below((model.position - model.base + 1) as usize) as u64;
(Some(covers), covers, false)
}
};
let mut ids: Vec<u64> = model.origin.keys().chain(model.history.keys()).copied().collect();
ids.sort_unstable();
ids.dedup();
let mut rows = BTreeMap::new();
for id in ids {
let read_at = from + rng.below((model.position - from + 1) as usize) as u64;
if let Some(value) = model.at(id, read_at) {
rows.insert(id, value);
}
}
snapshot::write_covering(&harness.set.path().join(name), &records_of(&rows), 61, covers).expect("written");
harness.set.point(name);
harness.refresh();
let stats = harness.stats();
if let Ok(metadata) = fs::metadata(harness.log_path()) {
assert_eq!(stats["changes"]["log"]["bytes"], metadata.len(), "{stats}");
}
if bad {
assert_eq!(stats["last_failure"]["snapshot"], name, "{stats}");
assert_eq!(stats["last_failure"]["code"], "covers_seq", "{stats}");
assert!(stats["last_failure"]["reason"].is_string());
assert_ne!(stats["snapshot"]["name"], name);
} else {
assert_eq!(stats["snapshot"]["name"], name, "{stats}");
assert_eq!(stats["seq"], model.position);
if let Some(covers) = covers {
model.base = model.base.max(covers);
}
assert_eq!(stats["changes"]["log"]["base_seq"], model.base, "{stats}");
}
bad
}
fn check<V: Value>(
harness: &Harness,
model: &Model<V>,
rng: &mut Rng,
centres: &[V],
snapshot: &str,
max_radius: usize,
step: usize,
) {
for _ in 0..2 {
let query: V = value(rng, centres);
let radius = rng.below(max_radius + 1) as u32;
let limit = (rng.below(3) == 0).then(|| 1 + rng.below(8));
let exclude_zero = rng.below(4) == 0;
let mut options = json!({
"format": 1, "index": INDEX, "width": V::BITS, "radius": radius,
"values": [query.to_hex()], "exclude_zero": exclude_zero,
});
if let Some(limit) = limit {
options["limit"] = json!(limit);
}
let result = harness.search(&options).expect("a search is answered");
let (matches, cut) = reference(
&model.truth,
query,
radius,
limit,
harness.limits.max_matches,
exclude_zero,
);
let entry = &result["queries"][0];
assert_eq!(result["snapshot"], snapshot, "step {step}");
assert_eq!(result["seq"], model.position, "step {step}");
assert_eq!(
entry["matches"],
Json::Array(matches),
"step {step}: radius {radius}, limit {limit:?}"
);
assert_eq!(entry["complete"], cut.is_none(), "step {step}");
assert_eq!(entry["cut_by"], cut.map_or(Json::Null, |cut| json!(cut)), "step {step}");
}
}
#[test]
fn the_model_at_64_bits() {
model::<u64>(1, 3_000, Limits::default());
}
#[test]
fn the_model_at_256_bits() {
model::<[u64; 4]>(2, 3_000, Limits::default());
}
#[test]
fn the_model_with_a_small_size_bound() {
let mut limits = Limits::default();
limits.max_matches = 4;
model::<u64>(3, 1_500, limits);
}
struct History<V> {
harness: Harness,
bytes: Vec<u8>,
whole: Vec<(usize, BTreeMap<u64, V>, u64)>,
}
fn wide_limits() -> Limits {
let mut limits = Limits::default();
limits.max_radius_64 = 64;
limits.max_radius_256 = 256;
limits
}
fn history<V: Value>(seed: u64) -> History<V> {
let mut rng = Rng::new(seed);
let mut harness = Harness::new(wide_limits());
let mut truth: BTreeMap<u64, V> = (0..6).map(|id| (id * 10, rng.value())).collect();
harness.set.publish("s0", &records_of(&truth));
harness.open();
let mut model = Model {
origin: truth.clone(),
history: BTreeMap::new(),
truth: truth.clone(),
position: 0,
base: 0,
sent: Vec::new(),
};
let mut whole = Vec::new();
let tasks: Vec<Task<V>> = vec![
("append", vec![(5, Some(rng.value())), (60, Some(rng.value()))]),
(
"replace",
vec![(0, Some(rng.value())), (5, Some(rng.value())), (99, Some(rng.value()))],
),
("append", vec![(10, Some(rng.value()))]),
("remove", vec![(20, None), (21, None), (60, None)]),
("append", vec![(20, Some(rng.value()))]),
("replace", vec![(30, Some(truth[&30]))]),
];
for (step, (name, records)) in tasks.iter().enumerate() {
send(&harness, &mut model, name, records, step);
let bytes = fs::read(harness.log_path()).expect("the log");
if whole.is_empty() {
let header = bytes[4..]
.windows(4)
.position(|window| window == change_log::MAGIC)
.expect("a second record")
+ 4;
whole.push((header, model.origin.clone(), 0));
}
whole.push((bytes.len(), model.truth.clone(), model.position));
}
assert!(
matches!(model.sent[2].3, Answer::Conflict(..)),
"the history holds a conflict"
);
let (task_id, name, options, first) = model.sent[1].clone();
assert_eq!(answer(harness.change(&task_id, name, &options)), first);
truth.clone_from(&model.truth);
let bytes = fs::read(harness.log_path()).expect("the log");
assert_eq!(bytes.len(), whole.last().expect("tasks").0);
History { harness, bytes, whole }
}
fn reopen<V: Value>(history: &History<V>, bytes: &[u8]) -> (Held<V>, Harness) {
let mut harness = Harness::new(wide_limits());
fs::remove_dir_all(harness.set.path()).expect("an empty set directory");
copy_dir(history.harness.set.path(), harness.set.path());
let dir = harness.state.0.join(INDEX);
fs::create_dir_all(&dir).expect("the index's state");
fs::write(dir.join(change_log::LOG_FILE), bytes).expect("the log");
harness.open();
let stats = harness.stats();
if stats["state"] == "refused" {
assert!(stats["refused"].is_string());
return (None, harness);
}
let options = json!({
"format": 1, "index": INDEX, "width": V::BITS, "radius": V::BITS,
"values": [V::from_words(&[0; 4][..V::WORDS]).to_hex()],
});
let result = harness.search(&options).expect("searched");
let held = result["queries"][0]["matches"]
.as_array()
.expect("matches")
.iter()
.map(|found| {
let id = found["id"].as_u64().expect("an id");
(id, V::from_hex(found["value"].as_str().expect("hex")).expect("hex"))
})
.collect();
(Some((held, result["seq"].as_u64().expect("seq"))), harness)
}
fn copy_dir(from: &Path, to: &Path) {
fs::create_dir_all(to).expect("a directory");
for entry in fs::read_dir(from).expect("a directory") {
let entry = entry.expect("an entry");
if entry.file_type().expect("a type").is_dir() {
copy_dir(&entry.path(), &to.join(entry.file_name()));
} else {
fs::copy(entry.path(), to.join(entry.file_name())).expect("copied");
}
}
}
fn cut_at_every_byte<V: Value>(seed: u64) {
let history = history::<V>(seed);
let header = history.whole[0].0;
for cut in 0..=history.bytes.len() {
let (held, harness) = reopen(&history, &history.bytes[..cut]);
if cut < header {
assert!(held.is_none(), "a log cut inside its header, at {cut}, is refused");
continue;
}
let (end, records, seq) = history
.whole
.iter()
.rev()
.find(|(end, _, _)| *end <= cut)
.expect("the header is whole");
assert_eq!(held.as_ref(), Some(&(records.clone(), *seq)), "cut at {cut}");
assert_eq!(
fs::read(harness.log_path()).expect("the log").len(),
*end,
"cut at {cut}"
);
if cut % 7 == 0 {
let next = harness
.change("next", "replace", &records_options(&[(3, rng_value::<V>(cut))]))
.expect("applied");
assert_eq!(next["seq"], *seq + 1, "cut at {cut}");
}
}
}
fn rng_value<V: Value>(seed: usize) -> V {
Rng::new(seed as u64).value()
}
fn damaged_at_every_byte<V: Value>(seed: u64) {
let history = history::<V>(seed);
let (last_start, before, seq) = history.whole[history.whole.len() - 2].clone();
for at in 0..history.bytes.len() {
let mut bytes = history.bytes.clone();
bytes[at] ^= 1 << (at % 8);
let (held, _) = reopen(&history, &bytes);
if at >= last_start {
assert_eq!(held, Some((before.clone(), seq)), "damaged at {at}");
} else {
assert!(
held.is_none(),
"damage at {at}, before the last task, refuses the index"
);
}
}
}
#[test]
fn a_log_cut_at_every_byte_keeps_exactly_its_whole_tasks() {
cut_at_every_byte::<u64>(10);
cut_at_every_byte::<[u64; 4]>(11);
}
#[test]
fn a_log_damaged_at_any_byte_is_cut_in_its_last_task_and_refused_before() {
damaged_at_every_byte::<u64>(12);
damaged_at_every_byte::<[u64; 4]>(13);
}
#[test]
fn zeros_and_a_stray_whole_record_after_the_last_task() {
let history = history::<u64>(14);
let mut bytes = history.bytes.clone();
bytes.extend_from_slice(&[0; 4096]);
let (held, _) = reopen(&history, &bytes);
let (_, records, seq) = history.whole.last().expect("tasks").clone();
assert_eq!(held, Some((records, seq)));
let mut bytes = history.bytes.clone();
let (first_end, second_end) = (history.whole[0].0, history.whole[1].0);
bytes.extend_from_slice(&[0; 100]);
bytes.extend_from_slice(&history.bytes[first_end..second_end]);
assert_eq!(reopen(&history, &bytes).0, None);
}
#[test]
fn a_task_logged_but_not_answered_is_answered_as_the_first_time_after_later_changes() {
let mut harness = Harness::new(Limits::default());
harness
.set
.publish("s0", &records_of(&BTreeMap::from([(1u64, 0xffu64)])));
harness.open();
let first = harness
.change("t1", "append", &records_options(&[(7, 0x0fu64)]))
.expect("applied");
harness.open();
let later = harness
.change("t2", "replace", &records_options(&[(7, 0xf0u64)]))
.expect("applied");
assert_eq!(later["seq"], 2);
let again = harness
.change("t1", "append", &records_options(&[(7, 0x0fu64)]))
.expect("answered");
assert_eq!(again, first);
let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 0, "values": ["00000000000000f0"]});
let found = harness.search(&options).expect("searched");
assert_eq!(
found["queries"][0]["matches"],
json!([{"id": 7, "value": "00000000000000f0", "distance": 0}])
);
assert_eq!(found["seq"], 2);
let conflict = harness
.change("t3", "append", &records_options(&[(7, 0x01u64)]))
.expect_err("a conflict");
assert_eq!(
(conflict.error_type, conflict.ids.clone(), conflict.count),
(ErrorType::Conflict, Some(vec![7]), Some(1))
);
harness
.change("t4", "remove", &remove_options::<u64>(&[7]))
.expect("removed");
let again = harness
.change("t3", "append", &records_options(&[(7, 0x01u64)]))
.expect_err("the same conflict");
assert_eq!(again, conflict);
}
#[test]
fn a_refusal_that_may_pass_later_keeps_its_task_id_or_a_stale_copy_lands_an_older_value() {
let search = |harness: &Harness| {
let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 4, "values": ["0000000000000000"]});
let found = harness.search(&options).expect("searched");
found["queries"][0]["matches"]
.as_array()
.expect("matches")
.iter()
.find(|found| found["id"] == 7)
.map(|found| found["value"].as_str().expect("a value").to_owned())
};
let (a, b) = (records_options(&[(7, 0x0au64)]), records_options(&[(7, 0x0bu64)]));
for keeps_its_task in [false, true] {
let mut harness = Harness::new(Limits::default());
harness.open();
let refused = harness.change("t1", "replace", &a).expect_err("not ready");
assert_eq!(refused.error_type, ErrorType::NotReady);
harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
harness.refresh();
let first = if keeps_its_task {
let first = harness.change("t1", "replace", &a).expect("applied");
harness.change("t2", "replace", &b).expect("applied");
Some(first)
} else {
harness.change("t2", "replace", &b).expect("applied");
None
};
let late = harness.change("t1", "replace", &a).expect("answered");
if let Some(first) = first {
assert_eq!(late, first, "a repeat, answered as the first time");
assert_eq!(search(&harness).as_deref(), Some("000000000000000b"), "B stands");
} else {
assert_eq!(late["seq"], 2, "applied for the first time, after B");
assert_eq!(
search(&harness).as_deref(),
Some("000000000000000a"),
"A, the older value, landed last"
);
}
}
}
#[test]
fn a_repeat_is_recognised_after_its_entries_are_dropped_within_the_window_only() {
for (window, recognised) in [(Duration::from_secs(3600), true), (Duration::ZERO, false)] {
let mut harness = Harness::new(Limits::default());
harness.repeat_window = window;
harness
.set
.publish("s0", &records_of(&BTreeMap::from([(1u64, 0xffu64)])));
harness.open();
let first = harness
.change("t1", "replace", &records_options(&[(7, 0x0fu64)]))
.expect("applied");
harness
.change("t2", "replace", &records_options(&[(7, 0xf0u64)]))
.expect("applied");
let rows = BTreeMap::from([(1u64, 0xffu64), (7, 0xf0)]);
snapshot::write_covering(&harness.set.path().join("s1"), &records_of(&rows), 10, Some(2)).expect("written");
harness.set.point("s1");
harness.refresh();
let stats = harness.stats();
assert_eq!(stats["changes"]["log"]["entries"], 0, "{stats}");
assert_eq!(
stats["changes"]["log"]["tasks"],
if recognised { 2 } else { 0 },
"{stats}"
);
let again = harness
.change("t1", "replace", &records_options(&[(7, 0x0fu64)]))
.expect("answered");
if recognised {
assert_eq!(again, first);
} else {
assert_eq!(again["seq"], 3);
assert_eq!(again["changed"], 1);
}
harness.open();
let next = harness
.change("t9", "remove", &remove_options::<u64>(&[1]))
.expect("removed");
assert_eq!(next["seq"], if recognised { 3 } else { 4 });
}
}
#[test]
fn a_change_that_changes_nothing_is_still_replayed_over_a_snapshot_read_before_it() {
let mut harness = Harness::new(wide_limits());
harness
.set
.publish("s0", &records_of(&BTreeMap::from([(7u64, 0xaau64)])));
harness.open();
let unchanged = harness
.change("t1", "replace", &records_options(&[(7, 0xaau64)]))
.expect("applied");
assert_eq!(
(unchanged["seq"].clone(), unchanged["unchanged"].clone()),
(json!(1), json!(1))
);
let unheld = harness
.change("t2", "remove", &remove_options::<u64>(&[8]))
.expect("applied");
assert_eq!(
(unheld["seq"].clone(), unheld["unchanged"].clone()),
(json!(2), json!(1))
);
let rows = BTreeMap::from([(7u64, 0xbbu64), (8, 0xcc)]);
snapshot::write_covering(&harness.set.path().join("s1"), &records_of(&rows), 10, Some(0)).expect("written");
harness.set.point("s1");
harness.refresh();
let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 64, "values": ["0000000000000000"]});
let found = harness.search(&options).expect("searched");
assert_eq!(found["snapshot"], "s1");
assert_eq!(
found["queries"][0]["matches"],
json!([{"id": 7, "value": "00000000000000aa", "distance": 4}])
);
}
#[test]
fn a_second_writer_of_an_index_is_refused_and_a_reader_is_not() {
let mut harness = Harness::new(Limits::default());
harness
.set
.publish("s0", &records_of(&BTreeMap::from([(7u64, 0xaau64)])));
harness.open();
harness
.change("t1", "append", &records_options(&[(9, 0x01u64)]))
.expect("applied");
let spec = || vec![SetSpec::index(INDEX, harness.set.path())];
let error = Catalog::new(spec(), harness.config(true)).expect_err("the lock is held");
assert!(error.contains("another process holds"), "{error}");
let reader = Catalog::new(spec(), harness.config(false)).expect("a reader opens");
reader.refresh(&mut |_| {});
let service = Service::new(Arc::new(reader), Limits::default(), 1);
let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 0, "values": ["0000000000000001"]});
let found = crate::service::search(&service, &options, Lane::Bulk).expect("searched");
assert_eq!(found["seq"], 1);
assert_eq!(found["queries"][0]["matches"][0]["id"], 9);
let refused = service
.change("t2", "append", &records_options(&[(10, 0x01u64)]).to_string())
.expect_err("a reader takes no change");
assert_eq!(refused.error_type, ErrorType::InvalidTask);
}
#[cfg(unix)]
#[test]
fn a_state_directory_that_is_a_symbolic_link_is_refused_by_a_reader_and_a_writer() {
let mut other = Harness::new(Limits::default());
other.set.publish("s0", &records_of(&BTreeMap::from([(7u64, 0xaau64)])));
other.open();
other
.change("t1", "append", &records_options(&[(9, 0x01u64)]))
.expect("applied");
other.service = None;
let harness = Harness::new(Limits::default());
harness
.set
.publish("s0", &records_of(&BTreeMap::from([(7u64, 0xaau64)])));
std::os::unix::fs::symlink(other.state.0.join(INDEX), harness.state.0.join(INDEX)).expect("a link");
let linked_to = format!(
"`{}` is a symbolic link to `{}`; it must be a directory, not a link",
harness.state.0.join(INDEX).display(),
other.state.0.join(INDEX).display()
);
let spec = || vec![SetSpec::index(INDEX, harness.set.path())];
let reader = Catalog::new(spec(), harness.config(false)).expect("a reader opens");
reader.refresh(&mut |_| {});
let service = Service::new(Arc::new(reader), Limits::default(), 1);
let options = json!({"format": 1, "index": INDEX}).to_string();
let stats: Json = serde_json::from_str(&service.stats(&options).expect("stats")).expect("JSON");
assert_eq!(stats["state"], "refused", "{stats}");
assert!(
stats["refused"]
.as_str()
.is_some_and(|reason| reason.contains(&linked_to)),
"{stats}"
);
let search = json!({"format": 1, "index": INDEX, "width": 64, "radius": 0, "values": ["0000000000000001"]});
let error = crate::service::search(&service, &search, Lane::Bulk).expect_err("refused");
assert_eq!(error.error_type, ErrorType::NotReady);
let error = Catalog::new(spec(), harness.config(true)).expect_err("refused");
assert!(error.contains(&linked_to), "{error}");
}
#[cfg(unix)]
#[test]
fn a_reader_refuses_a_log_that_is_a_dangling_link_or_a_pipe_and_reads_an_absent_one_as_empty() {
let harness = Harness::new(Limits::default());
harness
.set
.publish("s0", &records_of(&BTreeMap::from([(7u64, 0xaau64)])));
fs::create_dir_all(harness.state.0.join(INDEX)).expect("the state directory");
let spec = || vec![SetSpec::index(INDEX, harness.set.path())];
let read = || {
let (sender, received) = std::sync::mpsc::channel();
let (spec, config) = (spec(), harness.config(false));
std::thread::spawn(move || {
let reader = Catalog::new(spec, config).expect("a reader opens");
reader.refresh(&mut |_| {});
let service = Service::new(Arc::new(reader), Limits::default(), 1);
let options = json!({"format": 1, "index": INDEX}).to_string();
let stats: Json = serde_json::from_str(&service.stats(&options).expect("stats")).expect("JSON");
let _ = sender.send(stats);
});
received.recv_timeout(Duration::from_secs(10))
};
let stats = read().expect("read");
assert_eq!(
(&stats["state"], &stats["seq"]),
(&json!("ready"), &json!(0)),
"{stats}"
);
let log = harness.log_path();
std::os::unix::fs::symlink(harness.state.0.join("missing.log"), &log).expect("a link");
let stats = read().expect("read");
assert_eq!(stats["state"], "refused", "{stats}");
assert!(
stats["refused"]
.as_str()
.is_some_and(|reason| reason.contains("symbolic link")),
"{stats}"
);
fs::remove_file(&log).expect("removed");
let made = std::process::Command::new("mkfifo")
.arg(&log)
.status()
.expect("mkfifo runs");
assert!(made.success());
let stats = read();
if stats.is_err() {
drop(fs::OpenOptions::new().write(true).open(&log));
}
let stats = stats.expect("a pipe is refused, not waited on");
assert_eq!(stats["state"], "refused", "{stats}");
assert!(
stats["refused"]
.as_str()
.is_some_and(|reason| reason.contains("not a file")),
"{stats}"
);
}
#[test]
fn a_change_past_the_log_bound_is_refused_until_a_snapshot_covers_the_log() {
let mut limits = Limits::default();
limits.max_change_records = 10;
limits.max_remove_ids = 10;
limits.max_log_bytes = 1_000;
let mut harness = Harness::new(limits);
harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
harness.open();
let records: Vec<(u64, u64)> = (10..20).map(|id| (id, id)).collect();
harness
.change("t1", "append", &records_options(&records))
.expect("applied");
let full = harness
.change("t2", "replace", &records_options(&records))
.expect_err("past the bound");
assert_eq!(full.error_type, ErrorType::LogFull);
assert_eq!(harness.stats()["seq"], 10);
let mut rows: BTreeMap<u64, u64> = records.iter().copied().collect();
rows.insert(1, 1);
snapshot::write_covering(&harness.set.path().join("s1"), &records_of(&rows), 10, Some(10)).expect("written");
harness.set.point("s1");
harness.refresh();
let applied = harness
.change("t2", "replace", &records_options(&records))
.expect("room again");
assert_eq!(applied["seq"], 20);
}
#[test]
fn a_change_with_too_many_records_is_named_with_its_article() {
let mut limits = Limits::default();
limits.max_change_records = 1;
limits.max_remove_ids = 1;
let mut harness = Harness::new(limits);
harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
harness.open();
let records = json!({"format": 1, "index": INDEX, "width": 64,
"records": [[2, "0000000000000001"], [3, "0000000000000001"]]});
let ids = json!({"format": 1, "index": INDEX, "width": 64, "ids": [2, 3]});
for (name, options, message) in [
(
"append",
&records,
"the task holds 2 records; an `append` task takes at most 1",
),
(
"replace",
&records,
"the task holds 2 records; a `replace` task takes at most 1",
),
("remove", &ids, "the task holds 2 ids; a `remove` task takes at most 1"),
] {
let error = harness.change("t", name, options).expect_err("refused");
assert_eq!(
(error.error_type, error.message.as_str()),
(ErrorType::TooManyValues, message)
);
}
}
#[test]
fn change_tasks_are_checked_before_any_work() {
let mut limits = Limits::default();
limits.max_change_records = 3;
limits.max_remove_ids = 4;
let mut harness = Harness::new(limits);
harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
harness.open();
let refused = |name: &str, options: Json| harness.change("t", name, &options).expect_err("refused").error_type;
let pair = |id: u64| json!([id, "0000000000000001"]);
let options = |records: Json| json!({"format": 1, "index": INDEX, "width": 64, "records": records});
assert_eq!(refused("append", options(json!([]))), ErrorType::InvalidOptions);
assert_eq!(
refused("append", options(json!([pair(2), pair(2)]))),
ErrorType::InvalidOptions
);
assert_eq!(
refused("append", options(json!([pair(3), pair(2)]))),
ErrorType::InvalidOptions
);
assert_eq!(
refused("append", options(json!([[2, "zz"]]))),
ErrorType::InvalidOptions
);
assert_eq!(
refused("append", options(json!([[-2, "0000000000000001"]]))),
ErrorType::InvalidOptions
);
assert_eq!(
refused("append", options(json!([pair(1), pair(2), pair(3), pair(4)]))),
ErrorType::TooManyValues
);
let remove = |ids: Json| json!({"format": 1, "index": INDEX, "width": 64, "ids": ids});
assert_eq!(
refused("remove", remove(json!([1, 2, 3, 4, 5]))),
ErrorType::TooManyValues
);
assert_eq!(refused("remove", remove(json!(["1"]))), ErrorType::InvalidOptions);
assert_eq!(refused("remove", options(json!([pair(1)]))), ErrorType::InvalidOptions);
let subset = json!({"format": 1, "index": INDEX, "subset": "flagged", "width": 64, "records": [pair(1)]});
assert_eq!(refused("append", subset), ErrorType::InvalidOptions);
let wrong = json!({"format": 1, "index": INDEX, "width": 256, "records": [[1, "0".repeat(64)]]});
assert_eq!(refused("replace", wrong), ErrorType::WidthMismatch);
let unknown = json!({"format": 1, "index": "other", "width": 64, "records": [pair(1)]});
assert_eq!(refused("replace", unknown), ErrorType::UnknownIndex);
assert_eq!(refused("rename", options(json!([pair(1)]))), ErrorType::InvalidTask);
assert_eq!(harness.stats()["seq"], 0);
let taken = harness
.change("t", "append", &options(json!([pair(1), pair(2), pair(3)])))
.expect("applied");
assert_eq!(
taken,
json!({"format": 1, "index": INDEX, "seq": 3, "added": 2, "changed": 0, "removed": 0, "unchanged": 1})
);
}
#[test]
fn a_service_without_a_state_directory_takes_no_change() {
let set = SetDir::new();
set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
let service = crate::service::service(vec![SetSpec::index(INDEX, set.path())], Limits::default());
assert!(!service.takes_changes());
let error = service
.change("t", "append", &records_options(&[(2, 2u64)]).to_string())
.expect_err("no log");
assert_eq!(error.error_type, ErrorType::InvalidTask);
assert!(error.message.contains("--state-dir"));
}
#[test]
fn snapshots_an_index_with_changes_refuses() {
let mut harness = Harness::new(Limits::default());
harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
harness.open();
harness
.change("t1", "append", &records_options(&[(2, 2u64)]))
.expect("applied");
let failure = |harness: &mut Harness, name: &str| {
harness.set.point(name);
harness.refresh();
let stats = harness.stats();
assert_eq!(stats["snapshot"]["name"], "s0", "{stats}");
stats["last_failure"]["code"].as_str().expect("a code").to_owned()
};
snapshot::write(
&harness.set.path().join("bare"),
&Records::from_values([1u64, 2]).expect("values"),
10,
)
.expect("written");
assert_eq!(failure(&mut harness, "bare"), "ids");
let wide = Records::from_records([(1u64, [1u64, 0, 0, 0])]).expect("records");
snapshot::write(&harness.set.path().join("wide"), &wide, 10).expect("written");
assert_eq!(failure(&mut harness, "wide"), "width");
let rows = BTreeMap::from([(1u64, 1u64), (2, 2)]);
snapshot::write_covering(&harness.set.path().join("ahead"), &records_of(&rows), 10, Some(5)).expect("written");
assert_eq!(failure(&mut harness, "ahead"), "covers_seq");
let stats = harness.stats();
assert!(
stats["last_failure"]["reason"]
.as_str()
.is_some_and(|reason| reason.contains("never saw")),
"{stats}"
);
}
#[test]
fn a_log_damaged_in_the_middle_refuses_its_index_and_says_why() {
let history = history::<u64>(15);
let mut bytes = history.bytes.clone();
let middle = history.whole[2].0 + 20;
bytes[middle] ^= 0xff;
let (held, harness) = reopen(&history, &bytes);
assert_eq!(held, None);
let stats = harness.stats();
assert_eq!(stats["state"], "refused");
assert!(
stats["refused"]
.as_str()
.is_some_and(|reason| reason.contains("damaged")),
"{stats}"
);
let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 1, "values": ["0000000000000001"]});
let error = harness.search(&options).expect_err("refused");
assert_eq!((error.error_type, error.state), (ErrorType::NotReady, Some("refused")));
assert!(harness.events.iter().any(|event| event.contains("LogRefused")));
assert_eq!(fs::read(harness.log_path()).expect("the log"), bytes);
}
fn task_id_taken(task_id: &str) -> bool {
(1..=64).contains(&task_id.len())
&& task_id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}
#[test]
fn every_task_id_the_writer_takes_reads_back_and_every_other_leaves_the_log_as_it_was() {
let mut harness = Harness::new(Limits::default());
harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
harness.open();
let mut rng = Rng::new(31);
let valid: Vec<char> = "abzAZ09_-".chars().collect();
let invalid: Vec<char> = ":./ é\u{0}\u{1f600}".chars().collect();
let mut task_ids: Vec<String> = [0, 1, 64, 65, 255, 256]
.iter()
.map(|&length| "a".repeat(length))
.chain([
"é".repeat(10),
"\u{1f600}".repeat(16),
"a".repeat(63) + "é",
"task:1".to_owned(),
])
.collect();
for _ in 0..300 {
let length = rng.below(80);
let odd = rng.below(4) == 0;
task_ids.push(
(0..length)
.map(|_| {
if odd && rng.below(8) == 0 {
invalid[rng.below(invalid.len())]
} else {
valid[rng.below(valid.len())]
}
})
.collect(),
);
}
let mut taken = Vec::new();
for (step, task_id) in task_ids.iter().enumerate() {
let before = fs::read(harness.log_path()).unwrap_or_default();
let seq = harness.stats()["seq"].clone();
let id = step as u64 + 2;
match harness.change(task_id, "replace", &records_options(&[(id, id)])) {
Ok(answer) => {
assert!(task_id_taken(task_id), "{task_id:?} was taken");
if !taken.iter().any(|(taken, _)| taken == task_id) {
taken.push((task_id.clone(), answer));
}
}
Err(error) => {
assert!(!task_id_taken(task_id), "{task_id:?} was refused: {error}");
assert_eq!(error.error_type, ErrorType::InvalidTask, "{task_id:?}");
assert_eq!(fs::read(harness.log_path()).unwrap_or_default(), before, "{task_id:?}");
assert_eq!(harness.stats()["seq"], seq, "{task_id:?}");
}
}
}
assert!(taken.len() > 20, "the property took enough task ids to mean something");
harness.open();
assert_eq!(harness.stats()["state"], "ready");
for (task_id, answer) in &taken {
let id = 9_999;
assert_eq!(
&harness
.change(task_id, "replace", &records_options(&[(id, id)]))
.expect("answered"),
answer
);
}
}
#[derive(Debug, Clone, Copy)]
enum Mishap {
Deleted,
CutAtATask,
CutInATask,
Replaced,
}
#[test]
fn a_swap_never_steps_behind_what_the_live_writer_made_durable() {
for mishap in [
Mishap::Deleted,
Mishap::CutAtATask,
Mishap::CutInATask,
Mishap::Replaced,
] {
let mut harness = Harness::new(wide_limits());
let origin = BTreeMap::from([(1u64, 0x1u64), (2, 0x3)]);
harness.set.publish("s0", &records_of(&origin));
harness.open();
harness
.change("t1", "replace", &records_options(&[(7, 0x7u64)]))
.expect("applied");
let after_first = fs::read(harness.log_path()).expect("the log").len();
harness
.change("t2", "remove", &remove_options::<u64>(&[1]))
.expect("removed");
let path = harness.log_path();
match mishap {
Mishap::Deleted => fs::remove_file(&path).expect("deleted"),
Mishap::CutAtATask => fs::OpenOptions::new()
.write(true)
.open(&path)
.and_then(|file| file.set_len(after_first as u64))
.expect("cut"),
Mishap::CutInATask => fs::OpenOptions::new()
.write(true)
.open(&path)
.and_then(|file| file.set_len(after_first as u64 + 20))
.expect("cut"),
Mishap::Replaced => {
let copy = path.with_extension("copy");
fs::copy(&path, ©).expect("copied");
fs::rename(©, &path).expect("renamed");
}
}
harness.set.publish("s1", &records_of(&origin));
harness.set.point("s1");
harness.refresh();
let options = json!({"format": 1, "index": INDEX, "width": 64, "radius": 64, "values": ["0000000000000000"]});
let found = harness.search(&options).expect("searched");
let ids: Vec<u64> = found["queries"][0]["matches"]
.as_array()
.expect("matches")
.iter()
.map(|found| found["id"].as_u64().expect("an id"))
.collect();
assert_eq!(
(found["snapshot"].clone(), found["seq"].clone()),
(json!("s0"), json!(2)),
"{mishap:?}"
);
assert_eq!(ids, [2, 7], "{mishap:?}: no confirmed change is lost");
let stats = harness.stats();
let code = match mishap {
Mishap::Deleted => "log_missing",
Mishap::CutAtATask => "log_changed",
Mishap::CutInATask => "log_cut",
Mishap::Replaced => "log_replaced",
};
assert_eq!(stats["changes"]["writer"], "broken", "{mishap:?}: {stats}");
assert_eq!(stats["changes"]["writer_reason"], code, "{mishap:?}: {stats}");
assert_eq!(stats["last_failure"]["code"], "log", "{mishap:?}: {stats}");
assert!(stats["last_failure"]["reason"].is_string(), "{mishap:?}: {stats}");
let refused = harness
.change("t3", "replace", &records_options(&[(8, 0x8u64)]))
.expect_err("refused");
assert_eq!(refused.error_type, ErrorType::Internal, "{mishap:?}");
}
}
#[test]
fn a_log_longer_than_the_bound_read_is_refused_unread_until_the_bound_is_raised() {
let mut harness = Harness::new(Limits::default());
harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
harness.open();
for task in 0..5u64 {
let records: Vec<(u64, u64)> = (0..100).map(|id| (task * 1_000 + id + 10, id)).collect();
harness
.change(&format!("t{task}"), "append", &records_options(&records))
.expect("applied");
}
let bytes = fs::metadata(harness.log_path()).expect("the log").len();
harness.limits.max_change_records = 10;
harness.limits.max_remove_ids = 10;
harness.limits.max_log_bytes = 2_000;
assert!(harness.limits.log_read_bound() < bytes);
harness.open();
let stats = harness.stats();
assert_eq!(
(stats["state"].clone(), stats["refused_code"].clone()),
(json!("refused"), json!("too_large"))
);
assert!(
stats["refused"]
.as_str()
.is_some_and(|reason| reason.contains("--max-log-bytes")),
"{stats}"
);
assert_eq!(
fs::metadata(harness.log_path()).expect("the log").len(),
bytes,
"left as it was"
);
harness.limits = Limits::default();
harness.open();
assert_eq!(harness.stats()["seq"], 500);
}
#[test]
fn a_writer_dropped_and_opened_again_takes_its_lock_every_time_while_the_process_spawns_children() {
let mut harness = Harness::new(Limits::default());
harness.set.publish("s0", &records_of(&BTreeMap::from([(1u64, 1u64)])));
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let spawner = {
let stop = Arc::clone(&stop);
std::thread::spawn(move || {
let mut spawned = 0;
while !stop.load(std::sync::atomic::Ordering::Relaxed) {
if std::process::Command::new("true").status().is_ok() {
spawned += 1;
}
}
spawned
})
};
for round in 0..1_000 {
harness.service = None;
let catalog = Catalog::new(vec![SetSpec::index(INDEX, harness.set.path())], harness.config(true));
let catalog = catalog.unwrap_or_else(|error| panic!("round {round}: {error}"));
harness.service = Some(Service::new(Arc::new(catalog), harness.limits, 1));
}
stop.store(true, std::sync::atomic::Ordering::Relaxed);
assert!(
spawner.join().expect("the spawner") > 0,
"children were spawned meanwhile"
);
}