use serde_json::Value;
use crate::error::{Error, Result};
use crate::protocol::JsonMap;
use crate::store::{Change, ChangeBatch, DataStore, Origin};
#[derive(Debug, Clone, PartialEq)]
pub struct StoredRow {
pub fields: JsonMap,
pub trashed: bool,
}
pub fn check_data_store(
store: &dyn DataStore,
read: impl Fn(&str, &str) -> Option<StoredRow>,
table: &str,
row: Value,
patch: Value,
nullable: Option<&str>,
) -> Result<()> {
let row = match row {
Value::Object(m) => m,
_ => return Err(Error::config("row must be an object")),
};
let patch = match patch {
Value::Object(m) => m,
_ => return Err(Error::config("patch must be an object")),
};
let Some(kept) = row.keys().find(|k| !patch.contains_key(*k)).cloned() else {
return Err(Error::config("patch must leave at least one column of row unchanged"));
};
let space = "kovlet-check";
let mut tag = [0u8; 3];
let _ = getrandom::fill(&mut tag);
let tag = hex::encode(tag);
let (a, b, d, e) =
(format!("check-a-{tag}"), format!("check-b-{tag}"), format!("check-d-{tag}"), format!("check-e-{tag}"));
let t = table.to_string();
let mut failures: Vec<String> = Vec::new();
let merged = |base: &JsonMap, p: &JsonMap| {
let mut m = base.clone();
for (k, v) in p {
m.insert(k.clone(), v.clone());
}
m
};
let up = |id: &str, f: &JsonMap, deleted: bool| Change::Upsert {
table: t.clone(),
id: id.into(),
fields: f.clone(),
deleted,
};
let batch = |origin: Origin, changes: Vec<Change>, complete: bool| ChangeBatch {
space_id: space.into(),
origin,
changes,
complete,
};
let apply = |b: ChangeBatch, rule: &str, failures: &mut Vec<String>| {
if let Err(err) = store.apply(&b) {
failures.push(format!("{rule}: apply failed: {err}"));
}
};
let expect = |id: &str, fields: &JsonMap, trashed: bool, rule: &str, failures: &mut Vec<String>| match read(&t, id)
{
None => failures.push(format!("{rule}: row {id} is missing")),
Some(got) => {
for (k, v) in fields {
let have = got.fields.get(k).cloned().unwrap_or(Value::Null);
if &have != v {
failures.push(format!("{rule}: {id}.{k} is {have}, want {v}"));
}
}
if got.trashed != trashed {
failures.push(format!("{rule}: {id} trashed is {}, want {trashed}", got.trashed));
}
}
};
let r = "1. fields are patches";
apply(batch(Origin::Remote, vec![up(&a, &row, false)], false), r, &mut failures);
apply(batch(Origin::Remote, vec![up(&a, &patch, false)], false), r, &mut failures);
expect(&a, &merged(&row, &patch), false, r, &mut failures);
if let Some(n) = nullable {
let mut nul = JsonMap::new();
nul.insert(n.into(), Value::Null);
apply(batch(Origin::Remote, vec![up(&a, &nul, false)], false), r, &mut failures);
let mut want = JsonMap::new();
want.insert(kept.clone(), row[&kept].clone());
want.insert(n.into(), Value::Null);
expect(&a, &want, false, "1. null empties a field", &mut failures);
}
apply(batch(Origin::Local, vec![up(&b, &row, false)], false), "2", &mut failures);
apply(batch(Origin::Remote, vec![Change::Delete { table: t.clone(), id: b.clone() }], false), "2", &mut failures);
expect(&b, &row, true, "2. delete keeps the values", &mut failures);
apply(batch(Origin::Remote, vec![up(&b, &patch, true)], false), "2", &mut failures);
expect(&b, &merged(&row, &patch), true, "2. an upsert with deleted: true stays hidden", &mut failures);
apply(batch(Origin::Remote, vec![Change::Restore { table: t.clone(), id: b.clone() }], false), "2", &mut failures);
expect(&b, &merged(&row, &patch), false, "2. restore brings the values back", &mut failures);
apply(batch(Origin::Snapshot, vec![up(&e, &row, true)], false), "2", &mut failures);
expect(&e, &row, true, "2. a new row can arrive trashed", &mut failures);
let b3 = batch(
Origin::Remote,
vec![up(&d, &row, false), up(&d, &patch, false), Change::Delete { table: t.clone(), id: d.clone() }],
false,
);
apply(b3.clone(), "3", &mut failures);
apply(b3, "3", &mut failures);
expect(&d, &merged(&row, &patch), true, "3. apply is idempotent (and in order)", &mut failures);
apply(batch(Origin::Snapshot, vec![Change::Purge { table: t.clone(), id: d.clone() }], true), "4", &mut failures);
if read(&t, &d).is_some() {
failures.push(format!("4. purge: row {d} still exists"));
}
apply(
batch(
Origin::Remote,
vec![up(&d, &row, false), Change::Purge { table: t.clone(), id: d.clone() }, up(&d, &row, false)],
false,
),
"4",
&mut failures,
);
expect(&d, &row, false, "4. changes apply in order", &mut failures);
for id in [&a, &b, &d, &e] {
let _ = store.apply(&batch(Origin::Remote, vec![Change::Purge { table: t.clone(), id: id.clone() }], false));
}
if failures.is_empty() {
Ok(())
} else {
Err(Error::new("data_store_contract", format!("DataStore contract violations:\n- {}", failures.join("\n- "))))
}
}