cultcache-rs: redb stores hold one record per key (cut-rs-redb-one-record-per-key) (#181)
This commit is contained in:
parent
9fc4bdda6a
commit
ba1f0a4cfd
2 changed files with 177 additions and 6 deletions
|
|
@ -11,6 +11,10 @@ only in git history.
|
||||||
- `CultCache::update_with_attempts` and the conditional `update`: each attempt reads the record from its home store with its content version in one read, applies a function to a copy and commits only over that version, rerunning on a lost race (default five attempts). The result is `CultUpdateResult<T>`, outcome `Updated`, `Declined` (the function returned `None`) or `LostRace`, with the cache's document. Public types `CultStoredRecord`, `CultCommitIf`, `CultUpdateOutcome`, `CultUpdateResult`.
|
- `CultCache::update_with_attempts` and the conditional `update`: each attempt reads the record from its home store with its content version in one read, applies a function to a copy and commits only over that version, rerunning on a lost race (default five attempts). The result is `CultUpdateResult<T>`, outcome `Updated`, `Declined` (the function returned `None`) or `LostRace`, with the cache's document. Public types `CultStoredRecord`, `CultCommitIf`, `CultUpdateOutcome`, `CultUpdateResult`.
|
||||||
- `CacheBackingStore::read(key)` and `commit_if(entry, expected)`, provided methods whose defaults refuse with an error naming the store kind; `SingleFileMessagePackBackingStore` implements both. The content version is the lowercase hex SHA-256 of the record re-encoded as the store file writes it (key, schema id, `stored_at`, payload). It equals the SHA-256 of the record's bytes in the file, and so the C# reference's `tests/vectors/content-version`, whenever the file's MessagePack encodings are minimal, which every runtime's writer produces; a hand-edited file with a non-minimal encoding (for example a `str8` key that fits a fixstr) hashes differently from its slice here. New dependency `sha2` 0.10 and eight new lockfile crates: `sha2`, `digest`, `block-buffer`, `crypto-common`, `generic-array`, `typenum`, `cpufeatures`, `version_check`.
|
- `CacheBackingStore::read(key)` and `commit_if(entry, expected)`, provided methods whose defaults refuse with an error naming the store kind; `SingleFileMessagePackBackingStore` implements both. The content version is the lowercase hex SHA-256 of the record re-encoded as the store file writes it (key, schema id, `stored_at`, payload). It equals the SHA-256 of the record's bytes in the file, and so the C# reference's `tests/vectors/content-version`, whenever the file's MessagePack encodings are minimal, which every runtime's writer produces; a hand-edited file with a non-minimal encoding (for example a `str8` key that fits a fixstr) hashes differently from its slice here. New dependency `sha2` 0.10 and eight new lockfile crates: `sha2`, `digest`, `block-buffer`, `crypto-common`, `generic-array`, `typenum`, `cpufeatures`, `version_check`.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- The redb stores refuse, inside the write transaction, a write that would put a second type under a key another writer holds (a `SchemaConflictError` naming the key and both types, nothing committed), as the single-file store does; a row under the same schema id and another type name is replaced. Before, a cache that pulled before another writer added a type at the key wrote beside it and every later pull refused the store.
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
- `CultCache::delete::<T>` of a key nothing holds now refuses, as `put` and `is_writable` do, when `T` has no home store ("No backing store is registered…") or when a store carries a foreign record at the key or another registered type holds it (before: `Ok(false)`).
|
- `CultCache::delete::<T>` of a key nothing holds now refuses, as `put` and `is_writable` do, when `T` has no home store ("No backing store is registered…") or when a store carries a foreign record at the key or another registered type holds it (before: `Ok(false)`).
|
||||||
|
|
|
||||||
|
|
@ -3014,10 +3014,56 @@ fn read_redb_entry(
|
||||||
.transpose()
|
.transpose()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Every row a redb table holds at `key`, whatever its type. Identities sort by their encoded (type, key), and every row of one
|
||||||
|
/// type shares the prefix `0x92` + msgpack str(type), so the types are walked by skip-scan: read the first row at or after a
|
||||||
|
/// bound, point-get that type's row at `key`, then continue from the successor of the type's prefix. O(types x log n), not O(n).
|
||||||
|
fn rows_at_key(table: &impl ReadableTable<&'static [u8], &'static [u8]>, key: &str) -> Result<Vec<CultCacheEnvelope>> {
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
let mut lower = Vec::<u8>::new();
|
||||||
|
loop {
|
||||||
|
let first = match table.range::<&[u8]>(lower.as_slice()..)?.next() {
|
||||||
|
Some(row) => row?.0.value().to_vec(),
|
||||||
|
None => return Ok(rows),
|
||||||
|
};
|
||||||
|
let (held_type, _): (String, String) =
|
||||||
|
rmp_serde::from_slice(&first).context("failed to decode redb CultCache identity")?;
|
||||||
|
let identity = rmp_serde::to_vec(&entry_id_parts(&held_type, key)).context("failed to encode CultCache identity")?;
|
||||||
|
if let Some(value) = table.get(identity.as_slice())? {
|
||||||
|
rows.push(
|
||||||
|
decode_grown(value.value())
|
||||||
|
.map_err(opaque_decode_error)
|
||||||
|
.context("failed to decode redb CultCache envelope")?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut prefix = vec![0x92u8];
|
||||||
|
prefix.extend(rmp_serde::to_vec(&held_type).context("failed to encode CultCache type")?);
|
||||||
|
while prefix.last() == Some(&0xFF) {
|
||||||
|
prefix.pop();
|
||||||
|
}
|
||||||
|
match prefix.last_mut() {
|
||||||
|
Some(last) => *last += 1,
|
||||||
|
None => return Ok(rows),
|
||||||
|
}
|
||||||
|
lower = prefix;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one insert of a redb row, and the store's own judge of one record per key (the rule `settle_one_record_per_key` holds
|
||||||
|
/// for the single-file store): the write transaction is the lock. A row at the key under another schema id refuses the write
|
||||||
|
/// as a retype, nothing committed; a row under the same schema id and another type name (a rename) is replaced.
|
||||||
fn insert_redb_entry(
|
fn insert_redb_entry(
|
||||||
table: &mut redb::Table<&[u8], &[u8]>,
|
table: &mut redb::Table<&[u8], &[u8]>,
|
||||||
entry: &CultCacheEnvelope,
|
entry: &CultCacheEnvelope,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
for held in rows_at_key(&*table, &entry.key)? {
|
||||||
|
if held.r#type == entry.r#type {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if schema_identity(&held) != schema_identity(entry) {
|
||||||
|
return Err(retype_conflict(&held, entry));
|
||||||
|
}
|
||||||
|
table.remove(redb_identity(&held)?.as_slice())?;
|
||||||
|
}
|
||||||
let key = redb_identity(entry)?;
|
let key = redb_identity(entry)?;
|
||||||
let value = rmp_serde::to_vec(entry).context("failed to encode redb CultCache envelope")?;
|
let value = rmp_serde::to_vec(entry).context("failed to encode redb CultCache envelope")?;
|
||||||
table.insert(key.as_slice(), value.as_slice())?;
|
table.insert(key.as_slice(), value.as_slice())?;
|
||||||
|
|
@ -4591,7 +4637,7 @@ fn retype_conflict(held: &CultCacheEnvelope, written: &CultCacheEnvelope) -> any
|
||||||
/// The commit guard every single-file write passes: a store holds one record per key. Two entries under a key whose schema
|
/// The commit guard every single-file write passes: a store holds one record per key. Two entries under a key whose schema
|
||||||
/// ids differ are a retype and are refused with the key and both types, nothing written. Two under one schema id are one
|
/// ids differ are a retype and are refused with the key and both types, nothing written. Two under one schema id are one
|
||||||
/// record: a written entry replaces the held one it owns (a type renamed under a stable id), the held one being what the file
|
/// record: a written entry replaces the held one it owns (a type renamed under a stable id), the held one being what the file
|
||||||
/// already carries.
|
/// already carries. The redb stores pass the same rule in `insert_redb_entry`.
|
||||||
fn settle_one_record_per_key(entries: &[CultCacheEnvelope], disk: &DiskStore) -> Result<Vec<CultCacheEnvelope>> {
|
fn settle_one_record_per_key(entries: &[CultCacheEnvelope], disk: &DiskStore) -> Result<Vec<CultCacheEnvelope>> {
|
||||||
let arrived: BTreeMap<(String, String), &CultCacheEnvelope> = disk.envelopes.iter().map(|entry| (entry_id(entry), entry)).collect();
|
let arrived: BTreeMap<(String, String), &CultCacheEnvelope> = disk.envelopes.iter().map(|entry| (entry_id(entry), entry)).collect();
|
||||||
let held = |entry: &CultCacheEnvelope| arrived.get(&entry_id(entry)) == Some(&entry);
|
let held = |entry: &CultCacheEnvelope| arrived.get(&entry_id(entry)) == Some(&entry);
|
||||||
|
|
@ -5564,9 +5610,16 @@ mod tests {
|
||||||
let (mut stamped, _) = cache.prepare_entry("shared", ¬e_one())?;
|
let (mut stamped, _) = cache.prepare_entry("shared", ¬e_one())?;
|
||||||
stamped.schema_id = Some(Settings::TYPE.to_string());
|
stamped.schema_id = Some(Settings::TYPE.to_string());
|
||||||
{
|
{
|
||||||
let mut store = RedbMessagePackBackingStore::new(&path)?;
|
// Written under the store's own guard this pair is refused, so the foreign state is put in the table directly.
|
||||||
store.push(&settings)?;
|
let database = redb::Database::create(&path)?;
|
||||||
store.push(&stamped)?;
|
let write = database.begin_write()?;
|
||||||
|
{
|
||||||
|
let mut table = write.open_table(REDB_ENVELOPES)?;
|
||||||
|
for row in [&settings, &stamped] {
|
||||||
|
table.insert(redb_identity(row)?.as_slice(), rmp_serde::to_vec(row)?.as_slice())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
write.commit()?;
|
||||||
}
|
}
|
||||||
cache.add_generic_backing_store(RedbMessagePackBackingStore::new(&path)?)?;
|
cache.add_generic_backing_store(RedbMessagePackBackingStore::new(&path)?)?;
|
||||||
let error = cache.pull_all_backing_stores().unwrap_err();
|
let error = cache.pull_all_backing_stores().unwrap_err();
|
||||||
|
|
@ -6157,7 +6210,7 @@ mod tests {
|
||||||
let temp = tempfile::tempdir()?;
|
let temp = tempfile::tempdir()?;
|
||||||
let path = temp.path().join("keyed.cc");
|
let path = temp.path().join("keyed.cc");
|
||||||
let model = test_envelope("model", "shared", b"one");
|
let model = test_envelope("model", "shared", b"one");
|
||||||
let receipt = test_envelope("receipt", "shared", b"two");
|
let receipt = test_envelope("receipt", "other", b"two");
|
||||||
{
|
{
|
||||||
let mut store = RedbMessagePackBackingStore::new(&path)?;
|
let mut store = RedbMessagePackBackingStore::new(&path)?;
|
||||||
store.push(&model)?;
|
store.push(&model)?;
|
||||||
|
|
@ -6342,7 +6395,7 @@ mod tests {
|
||||||
OwnedRedbMessagePackBackingStore::new(temp.path().join("compact-owned.cc"))?;
|
OwnedRedbMessagePackBackingStore::new(temp.path().join("compact-owned.cc"))?;
|
||||||
let old_head = test_envelope("retention", "current", b"one");
|
let old_head = test_envelope("retention", "current", b"one");
|
||||||
let retired_a = test_envelope("claim", "a", b"terminal");
|
let retired_a = test_envelope("claim", "a", b"terminal");
|
||||||
let retired_b = test_envelope("receipt", "a", b"terminal");
|
let retired_b = test_envelope("receipt", "b", b"terminal");
|
||||||
owner.push(&old_head)?;
|
owner.push(&old_head)?;
|
||||||
owner.push(&retired_a)?;
|
owner.push(&retired_a)?;
|
||||||
owner.push(&retired_b)?;
|
owner.push(&retired_b)?;
|
||||||
|
|
@ -9226,6 +9279,120 @@ mod tests {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn open_redb_cache(path: &Path, owned: Option<&OwnedRedbMessagePackBackingStore>) -> Result<CultCache> {
|
||||||
|
let mut cache = CultCache::new();
|
||||||
|
cache.register_registry(TestEntries)?;
|
||||||
|
match owned {
|
||||||
|
Some(handle) => cache.add_generic_backing_store(handle.clone())?,
|
||||||
|
None => cache.add_generic_backing_store(RedbMessagePackBackingStore::new(path)?)?,
|
||||||
|
}
|
||||||
|
cache.pull_all_backing_stores()?;
|
||||||
|
Ok(cache)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stale_cache_cannot_put_a_second_type_under_a_key_on_redb() -> Result<()> {
|
||||||
|
let temp = tempfile::tempdir()?;
|
||||||
|
let owned = OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?;
|
||||||
|
for (name, handle) in [("plain", None), ("owned", Some(&owned))] {
|
||||||
|
let path = temp.path().join("plain.db");
|
||||||
|
let mut stale = open_redb_cache(&path, handle)?;
|
||||||
|
let mut other = open_redb_cache(&path, handle)?;
|
||||||
|
other.put("k", &Note { title: "n".to_string(), body: "b".to_string() })?;
|
||||||
|
let refused = stale.put("k", &Settings { theme: "s".to_string(), retries: 1 }).unwrap_err();
|
||||||
|
let conflict = refused.downcast_ref::<SchemaConflictError>().expect(name);
|
||||||
|
assert_eq!(conflict.record_key, "k");
|
||||||
|
assert_eq!(conflict.schema_names, ["note", "settings"]);
|
||||||
|
let fresh = open_redb_cache(&path, handle)?;
|
||||||
|
assert_eq!(fresh.get_required::<Note>("k")?.title, "n", "{name}");
|
||||||
|
assert!(fresh.get::<Settings>("k")?.is_none(), "{name}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_stale_redb_batch_with_a_retype_writes_nothing() -> Result<()> {
|
||||||
|
let temp = tempfile::tempdir()?;
|
||||||
|
let owned = OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?;
|
||||||
|
for (name, handle) in [("plain", None), ("owned", Some(&owned))] {
|
||||||
|
let path = temp.path().join("plain.db");
|
||||||
|
let mut stale = open_redb_cache(&path, handle)?;
|
||||||
|
let mut other = open_redb_cache(&path, handle)?;
|
||||||
|
other.put("k", &Note { title: "n".to_string(), body: "b".to_string() })?;
|
||||||
|
let clean = stale.prepare_entry("clean", &Settings { theme: "s".to_string(), retries: 1 })?.0;
|
||||||
|
let retyped = stale.prepare_entry("k", &Settings { theme: "s".to_string(), retries: 1 })?.0;
|
||||||
|
let refused = stale.put_prepared_batch(vec![clean, retyped]).unwrap_err();
|
||||||
|
assert!(refused.downcast_ref::<SchemaConflictError>().is_some(), "{name}");
|
||||||
|
let fresh = open_redb_cache(&path, handle)?;
|
||||||
|
assert!(fresh.get::<Settings>("clean")?.is_none(), "{name}: the clean key is absent");
|
||||||
|
assert_eq!(fresh.get_required::<Note>("k")?.title, "n", "{name}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_redb_batch_with_two_schema_ids_at_one_key_is_refused() -> Result<()> {
|
||||||
|
let temp = tempfile::tempdir()?;
|
||||||
|
let stores: Vec<Box<dyn CacheBackingStore>> = vec![
|
||||||
|
Box::new(RedbMessagePackBackingStore::new(temp.path().join("plain.db"))?),
|
||||||
|
Box::new(OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?),
|
||||||
|
];
|
||||||
|
for mut store in stores {
|
||||||
|
let refused = store
|
||||||
|
.push_all(&[test_envelope("a", "k", b"1"), test_envelope("b", "k", b"2")], PushAllOptions::default())
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(refused.downcast_ref::<SchemaConflictError>().is_some());
|
||||||
|
assert!(store.pull_all()?.is_empty(), "neither row is written");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn redb_skip_scan_finds_a_row_of_any_type() -> Result<()> {
|
||||||
|
let temp = tempfile::tempdir()?;
|
||||||
|
let database = redb::Database::create(temp.path().join("scan.db"))?;
|
||||||
|
let write = database.begin_write()?;
|
||||||
|
{
|
||||||
|
let mut table = write.open_table(REDB_ENVELOPES)?;
|
||||||
|
for (kind, key) in [("a", "x"), ("a", "y"), ("ab", "x"), ("ab", "z"), ("b", "y"), ("zz", "x"), ("\u{ff}", "x")] {
|
||||||
|
let row = test_envelope(kind, key, b"p");
|
||||||
|
table.insert(redb_identity(&row)?.as_slice(), rmp_serde::to_vec(&row)?.as_slice())?;
|
||||||
|
}
|
||||||
|
let at = |key: &str| -> Result<Vec<String>> {
|
||||||
|
let mut types: Vec<String> = rows_at_key(&table, key)?.into_iter().map(|row| row.r#type).collect();
|
||||||
|
types.sort();
|
||||||
|
Ok(types)
|
||||||
|
};
|
||||||
|
assert_eq!(at("x")?, ["a", "ab", "zz", "\u{ff}"]);
|
||||||
|
assert_eq!(at("y")?, ["a", "b"]);
|
||||||
|
assert_eq!(at("z")?, ["ab"]);
|
||||||
|
assert!(at("missing")?.is_empty());
|
||||||
|
}
|
||||||
|
write.commit()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn redb_same_schema_id_rename_replaces() -> Result<()> {
|
||||||
|
let temp = tempfile::tempdir()?;
|
||||||
|
let stores: Vec<Box<dyn CacheBackingStore>> = vec![
|
||||||
|
Box::new(RedbMessagePackBackingStore::new(temp.path().join("plain.db"))?),
|
||||||
|
Box::new(OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?),
|
||||||
|
];
|
||||||
|
for mut store in stores {
|
||||||
|
let mut old = test_envelope("old", "k", b"1");
|
||||||
|
old.schema_id = Some("X".to_string());
|
||||||
|
let mut new = test_envelope("new", "k", b"2");
|
||||||
|
new.schema_id = Some("X".to_string());
|
||||||
|
store.push(&old)?;
|
||||||
|
store.push(&new)?;
|
||||||
|
let rows = store.pull_all()?;
|
||||||
|
assert_eq!(rows.len(), 1);
|
||||||
|
assert_eq!(rows[0].r#type, "new");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn every_store_merges_push_all_and_lands_the_last_of_a_repeated_key() -> Result<()> {
|
fn every_store_merges_push_all_and_lands_the_last_of_a_repeated_key() -> Result<()> {
|
||||||
let temp = tempfile::tempdir()?;
|
let temp = tempfile::tempdir()?;
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue