use crate::store::ValueRef;
use xxhash_rust::xxh3::{Xxh3, xxh3_64};
fn value_digest(h: &mut Xxh3, value: crate::store::ValueRef<'_>) {
match value {
ValueRef::String(bytes) => {
h.update(b"s");
match crate::commands::hyperloglog::hll_cache_range(&bytes) {
Some(cache) => {
h.update(&bytes[..cache.start]);
h.update(&bytes[cache.end..]);
}
None => h.update(&bytes),
}
}
ValueRef::List(list) => {
h.update(b"l");
for item in list.read().iter() {
h.update(&(item.len() as u64).to_le_bytes());
h.update(item);
}
}
ValueRef::Hash(hash) => {
h.update(b"h");
let mut sum = 0u64;
for (field, value) in hash.read().iter() {
let mut e = Xxh3::new();
e.update(&(field.len() as u64).to_le_bytes());
e.update(field.as_bytes());
e.update(value);
sum = sum.wrapping_add(e.digest());
}
h.update(&sum.to_le_bytes());
}
ValueRef::Set(set) => {
h.update(b"S");
let sum = set
.read()
.iter()
.fold(0u64, |sum, member| sum.wrapping_add(xxh3_64(member)));
h.update(&sum.to_le_bytes());
}
ValueRef::SortedSet(zset) => {
h.update(b"z");
for (score, member) in zset.read().by_score.keys() {
h.update(&score.to_bits().to_le_bytes());
h.update(&(member.len() as u64).to_le_bytes());
h.update(member);
}
}
other => {
let mut laid_out = 0u32.to_le_bytes().to_vec();
if crate::snapshot::write_kdb_value(&mut laid_out, other).is_ok() {
h.update(b"o");
h.update(&laid_out);
}
}
}
}
pub fn value_hex(value: ValueRef<'_>) -> String {
let mut h = Xxh3::new();
value_digest(&mut h, value);
format!("{:040x}", h.digest128())
}
pub fn dataset_digest(store: &crate::store::Store) -> u64 {
let threads = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
.clamp(1, 8);
let mut total = 0u64;
for (db_index, db) in store.iter().enumerate() {
let shards: Vec<_> = db.iter().collect();
let per = shards.len().div_ceil(threads).max(1);
let keys_sum: u64 = std::thread::scope(|scope| {
let handles: Vec<_> = shards
.chunks(per)
.map(|run| {
scope.spawn(move || {
let mut sum = 0u64;
for shard in run {
for entry in crate::read_lock!(shard).entries() {
let key = entry.key();
let mut h = Xxh3::new();
h.update(&(db_index as u64).to_le_bytes());
h.update(&(key.len() as u64).to_le_bytes());
h.update(key);
value_digest(&mut h, entry.value());
sum = sum.wrapping_add(h.digest());
if let Some(ms) = entry.expires() {
let mut h = Xxh3::new();
h.update(b"ttl");
h.update(&(db_index as u64).to_le_bytes());
h.update(key);
h.update(&ms.to_le_bytes());
sum = sum.wrapping_add(h.digest());
}
}
}
sum
})
})
.collect();
handles
.into_iter()
.map(|h| h.join().unwrap_or(0))
.fold(0u64, u64::wrapping_add)
});
total = total.wrapping_add(keys_sum);
}
total
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::KiviDBValue;
#[test]
fn a_values_digest_follows_the_value() {
let a = crate::store::new_store(1);
let b = crate::store::new_store(1);
let set = |store: &crate::store::Store, k: &str, v: &str| {
crate::write_lock!(crate::store::get_shard(&store[0], k)).insert_str(k, v.as_bytes());
};
set(&a, "k", "one");
set(&b, "k", "one");
set(&b, "other", "two");
let hex = |store: &crate::store::Store, k: &str| {
let shard = crate::store::get_shard(&store[0], k);
let map = crate::read_lock!(shard);
value_hex(map.get(k).unwrap())
};
assert_eq!(hex(&a, "k"), hex(&b, "k"));
assert_ne!(hex(&b, "k"), hex(&b, "other"));
assert_eq!(hex(&a, "k").len(), 40);
assert!(hex(&a, "k").bytes().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn the_fingerprint_follows_the_data_not_its_order() {
let a = crate::store::new_store(1);
let b = crate::store::new_store(1);
let set = |store: &crate::store::Store, k: &str, v: &str| {
crate::write_lock!(crate::store::get_shard(&store[0], k)).insert_str(k, v.as_bytes());
};
for i in 0..100 {
set(&a, &format!("k{i}"), "v");
}
for i in (0..100).rev() {
set(&b, &format!("k{i}"), "v");
}
assert_eq!(dataset_digest(&a), dataset_digest(&b));
set(&b, "k7", "w");
assert_ne!(dataset_digest(&a), dataset_digest(&b));
crate::write_lock!(crate::store::get_shard(&a[0], "k7")).insert_str("k7", b"w");
assert_eq!(dataset_digest(&a), dataset_digest(&b));
crate::write_lock!(crate::store::get_shard(&a[0], "k7")).set_expires("k7", 99);
assert_ne!(dataset_digest(&a), dataset_digest(&b));
crate::write_lock!(crate::store::get_shard(&b[0], "k7")).set_expires("k7", 99);
assert_eq!(dataset_digest(&a), dataset_digest(&b));
}
#[test]
fn a_hyperloglogs_cached_count_is_not_part_of_the_fingerprint() {
let (a, b) = (crate::store::new_store(1), crate::store::new_store(1));
let hll = |cache: u8, register: u8| {
let mut blob = vec![0u8; 16 + 12288];
blob[..4].copy_from_slice(b"HYLL");
blob[4] = 1;
blob[8] = cache;
blob[15] = if cache == 0 { 0x80 } else { 0 };
blob[100] = register;
KiviDBValue::String(crate::types::SharedBytes::from(blob.as_slice()))
};
let put = |store: &crate::store::Store, v: KiviDBValue| {
crate::write_lock!(crate::store::get_shard(&store[0], "h")).insert("h", v);
};
put(&a, hll(0, 1));
put(&b, hll(7, 1));
assert_eq!(dataset_digest(&a), dataset_digest(&b));
put(&b, hll(7, 2));
assert_ne!(dataset_digest(&a), dataset_digest(&b));
let sparse = |cache: u8, register: u8| {
let mut blob = vec![0u8; 18];
blob[..4].copy_from_slice(b"HYLL");
blob[4] = 1;
blob[8] = cache;
blob[15] = if cache == 0 { 0x80 } else { 0 };
blob[16] = 0x7f;
blob[17] = register;
KiviDBValue::String(crate::types::SharedBytes::from(blob.as_slice()))
};
put(&a, sparse(0, 0xff));
put(&b, sparse(7, 0xff));
assert_eq!(dataset_digest(&a), dataset_digest(&b));
put(&b, sparse(7, 0xfe));
assert_ne!(dataset_digest(&a), dataset_digest(&b));
}
}