cultcache-rs: refuse a unique-index write into a moved store (cut-rs-stale-write-gate) (#182)
This commit is contained in:
parent
ba1f0a4cfd
commit
e503edf2b0
4 changed files with 725 additions and 33 deletions
|
|
@ -8,15 +8,18 @@ only in git history.
|
|||
|
||||
### Added
|
||||
|
||||
- `CacheBackingStore::push_all_unchanged(entries)` returning `CultPushUnchanged` (`Committed { stamps }` or `Changed { changed_keys }`), a provided method whose default refuses with an error naming the store kind and `push_all_unchanged`: a custom store keeps compiling and its writes of indexed types are refused until it implements it. The three bundled stores keep what each handle last read or wrote (a clone starts empty). Public `CultCacheWriteConflict { record_keys, changed_keys }`.
|
||||
- `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`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A cache whose store changed since it last read it no longer lands a write of a type with a unique index: `put`, `put_envelope`, `put_raw_envelope`, `put_prepared_batch` and `update` check, under the store's own exclusion, that every record is as the cache last read or wrote it, and otherwise write nothing, reload the changed records and return `CultCacheWriteConflict` (naming keys, never values; `update` counts it as a lost attempt and retries), as C# `RefuseWriteIntoMovedStore` does. Before, the judge saw only the cache's image, so a stale cache could write a value another writer already held at another key and every later pull refused the store. The gate also refuses when the other writer changed an unrelated key. Writes of types without an index are unchanged. If the reload fails the cache is refused (`CultCacheLoadRefused`) and the reload error is the conflict's source.
|
||||
- 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
|
||||
|
||||
- A redb store that already holds two types at one key (written by a build before the one-record-per-key rule) refuses a write of either held type at that key with `SchemaConflictError`, where it once succeeded; delete one of the two rows (`delete(type, key)` removes that type's row alone), then write.
|
||||
- `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)`).
|
||||
- `is_stored_at_stamp(&str)` (new, public) is the one shape a peer's `storedAt` must parse as, pinned by `tests/vectors/stored-at-stamp` (RFC 3339 `YYYY-MM-DDThh:mm:ss`, a 1 to 9 digit fraction, `Z` or `+hh:mm`/`-hh:mm`; uppercase `T`/`Z`, a real date, seconds 00-59, years 0001-9999), hand-checked because `chrono`'s RFC 3339 reader takes other shapes. `put_raw_envelope` and `put_prepared_batch` refuse a `stored_at` that is not a stamp (before: only a blank one) and mint nothing (variants:ruling:raw-put-without-stamp-refused).
|
||||
- The single-file store's `push`, `push_all` and `commit_if` stamp a replacing write strictly later than the record it replaces at the same key (a staged stamp stands only when it parses and is strictly later; otherwise the stamp is minted as the replaced stamp plus one microsecond, or now if later), with no identical-content exception, as C# does. A stamp with no successor (the replaced stamp is at year 9999's last microsecond) refuses the write and writes nothing, as C# `MintStoredAt` does. `commit_if` replaces only the record of the entry's own type under the key, so a retype is refused as `push` refuses it. The cache holds the stamp the store wrote. The redb stores and the store-level exact-envelope writes (`compare_and_swap_entry` and its family) still write the caller's envelope unchanged.
|
||||
|
|
|
|||
|
|
@ -444,6 +444,11 @@ A store whose elements hold an id is marked `cultcache.store.v3` by the C# runti
|
|||
- `cache.get_by_index::<T>("callsign", "Lucent-7")`: `#[cultcache(index)]` is unique. Within one type no two
|
||||
records hold one non-blank value of the alias; a put, batch or load that would make two is refused, naming both
|
||||
keys and the alias, and writes nothing. A grouping (faction, kind, status) is not an index: filter `get_all`.
|
||||
A cache whose store changed since it last read it (another writer added, replaced or removed any record) cannot
|
||||
check uniqueness against what it has not seen: its write of an indexed type returns `CultCacheWriteConflict`
|
||||
(`error.downcast_ref`), writes nothing and reloads the changed records; retry the write against them. `update`
|
||||
retries on its own. Writes of types without an index merge as before. A custom `CacheBackingStore` needs
|
||||
`push_all_unchanged` for indexed writes, else they are refused.
|
||||
- generated extractors instead of reflection strings
|
||||
|
||||
4. **Schema/version metadata**
|
||||
|
|
|
|||
|
|
@ -1307,6 +1307,74 @@ pub enum CultCommitIf {
|
|||
Mismatch,
|
||||
}
|
||||
|
||||
/// The verdict of [`CacheBackingStore::push_all_unchanged`]: the write landed and carries one stamp per entry (as `push_all`
|
||||
/// returns), or the store held records this handle had not read as they now are and nothing was written. `changed_keys` are
|
||||
/// the keys whose record differs from what the handle last read (a record another writer added, replaced or removed), in UTF-16
|
||||
/// order.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum CultPushUnchanged {
|
||||
Committed { stamps: Vec<String> },
|
||||
Changed { changed_keys: Vec<String> },
|
||||
}
|
||||
|
||||
/// What one store handle last read or wrote: key -> content version. It decides only whether a gated write may land, never a
|
||||
/// record's content. A clone starts empty (a clone is another reader), every handle compares equal, and it prints as a count.
|
||||
#[derive(Default)]
|
||||
struct LastRead(std::sync::Mutex<BTreeMap<String, String>>);
|
||||
|
||||
impl LastRead {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, String>> {
|
||||
self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Replaces the whole map with the versions of `entries`: a pull read all of them.
|
||||
fn set_all(&self, entries: &[CultCacheEnvelope]) {
|
||||
*self.lock() = entries.iter().map(|entry| (entry.key.clone(), record_version(entry))).collect();
|
||||
}
|
||||
|
||||
fn record(&self, entry: &CultCacheEnvelope) {
|
||||
self.lock().insert(entry.key.clone(), record_version(entry));
|
||||
}
|
||||
|
||||
fn forget(&self, key: &str) {
|
||||
self.lock().remove(key);
|
||||
}
|
||||
|
||||
/// The keys at which `held` (every record the store holds now) differs from what was last read, in UTF-16 order.
|
||||
fn changed_keys(&self, held: &[CultCacheEnvelope]) -> Vec<String> {
|
||||
let read = self.lock();
|
||||
let now: BTreeMap<&str, String> = held.iter().map(|entry| (entry.key.as_str(), record_version(entry))).collect();
|
||||
let mut changed: Vec<String> = now
|
||||
.iter()
|
||||
.filter(|(key, version)| read.get(**key) != Some(*version))
|
||||
.map(|(key, _)| (*key).to_string())
|
||||
.chain(read.keys().filter(|key| !now.contains_key(key.as_str())).cloned())
|
||||
.collect();
|
||||
changed.sort_by(|left, right| utf16_cmp(left, right));
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for LastRead {
|
||||
fn clone(&self) -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for LastRead {
|
||||
fn eq(&self, _: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for LastRead {}
|
||||
|
||||
impl std::fmt::Debug for LastRead {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(formatter, "LastRead({})", self.lock().len())
|
||||
}
|
||||
}
|
||||
|
||||
/// How [`CultCache::update`] ended. `Declined` wrote nothing because `apply` returned `None`; `LostRace` wrote nothing because
|
||||
/// every attempt found the record changed under it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
|
|
@ -1397,16 +1465,28 @@ pub trait CacheBackingStore: Send {
|
|||
std::any::type_name::<Self>()
|
||||
))
|
||||
}
|
||||
|
||||
/// [`CacheBackingStore::push_all`] that writes only if every record the store holds is as this handle last read or wrote it,
|
||||
/// compared under the store's own exclusion. If any differs (a record another writer added, replaced or removed) nothing is
|
||||
/// written and the keys that moved are returned. A cache needs this for a write of a type with a unique index, whose rule
|
||||
/// resolves against other records; a store without it refuses such a write.
|
||||
fn push_all_unchanged(&mut self, _entries: &[CultCacheEnvelope]) -> Result<CultPushUnchanged> {
|
||||
Err(anyhow!(
|
||||
"{} has no push_all_unchanged: a write of a type with a unique index needs push_all_unchanged",
|
||||
std::any::type_name::<Self>()
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SingleFileMessagePackBackingStore {
|
||||
path: PathBuf,
|
||||
last_read: LastRead,
|
||||
}
|
||||
|
||||
impl SingleFileMessagePackBackingStore {
|
||||
pub fn new(path: impl Into<PathBuf>) -> Self {
|
||||
Self { path: path.into() }
|
||||
Self { path: path.into(), last_read: LastRead::default() }
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &Path {
|
||||
|
|
@ -2076,9 +2156,14 @@ fn unique_batch_ids(
|
|||
impl CacheBackingStore for SingleFileMessagePackBackingStore {
|
||||
fn pull_all(&self) -> Result<Vec<CultCacheEnvelope>> {
|
||||
if is_absent(&self.path)? && is_absent(&self.lock_path())? {
|
||||
self.last_read.set_all(&[]);
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
self.with_shared_lock(|| self.read_all_unlocked())
|
||||
self.with_shared_lock(|| {
|
||||
let entries = self.read_all_unlocked()?;
|
||||
self.last_read.set_all(&entries);
|
||||
Ok(entries)
|
||||
})
|
||||
}
|
||||
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String> {
|
||||
|
|
@ -2090,6 +2175,7 @@ impl CacheBackingStore for SingleFileMessagePackBackingStore {
|
|||
entries.push(entry.clone());
|
||||
entries.sort_by_key(entry_id);
|
||||
self.write_all_unlocked(&entries)?;
|
||||
self.last_read.record(&entry);
|
||||
Ok(entry.stored_at)
|
||||
})
|
||||
}
|
||||
|
|
@ -2120,6 +2206,7 @@ impl CacheBackingStore for SingleFileMessagePackBackingStore {
|
|||
entries.push(entry.clone());
|
||||
entries.sort_by_key(entry_id);
|
||||
self.write_all_unlocked(&entries)?;
|
||||
self.last_read.record(&entry);
|
||||
Ok(CultCommitIf::Committed { stored_at: entry.stored_at })
|
||||
})
|
||||
}
|
||||
|
|
@ -2128,7 +2215,9 @@ impl CacheBackingStore for SingleFileMessagePackBackingStore {
|
|||
self.with_exclusive_lock(|| {
|
||||
let mut entries = self.read_all_unlocked()?;
|
||||
entries.retain(|candidate| entry_id(candidate) != entry_id(entry));
|
||||
self.write_all_unlocked(&entries)
|
||||
self.write_all_unlocked(&entries)?;
|
||||
self.last_read.forget(&entry.key);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -2140,26 +2229,46 @@ impl CacheBackingStore for SingleFileMessagePackBackingStore {
|
|||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
// Of entries sharing a key and a schema id the last one given is the record, whatever their type names (a type
|
||||
// renamed under a stable id); it replaces the held record under that key and schema id. A second schema id
|
||||
// under a key reaches the commit guard, which judges the merged store.
|
||||
let mut merged = self.read_all_unlocked()?;
|
||||
let mut by_id = BTreeMap::<(String, String), CultCacheEnvelope>::new();
|
||||
for entry in entries {
|
||||
by_id.insert((schema_identity(entry).to_string(), entry.key.clone()), restamped_over(entry, &merged)?);
|
||||
}
|
||||
let replaced: BTreeSet<_> = by_id.values().map(entry_id).collect();
|
||||
merged.retain(|held| !replaced.contains(&entry_id(held)));
|
||||
let stamps = entries
|
||||
.iter()
|
||||
.map(|entry| by_id[&(schema_identity(entry).to_string(), entry.key.clone())].stored_at.clone())
|
||||
.collect();
|
||||
merged.extend(by_id.into_values());
|
||||
merged.sort_by_key(entry_id);
|
||||
self.write_all_unlocked(&merged)?;
|
||||
Ok(stamps)
|
||||
self.merge_unlocked(entries)
|
||||
})
|
||||
}
|
||||
|
||||
fn push_all_unchanged(&mut self, entries: &[CultCacheEnvelope]) -> Result<CultPushUnchanged> {
|
||||
self.with_exclusive_lock(|| {
|
||||
let changed_keys = self.last_read.changed_keys(&self.read_all_unlocked()?);
|
||||
if !changed_keys.is_empty() {
|
||||
return Ok(CultPushUnchanged::Changed { changed_keys });
|
||||
}
|
||||
Ok(CultPushUnchanged::Committed { stamps: self.merge_unlocked(entries)? })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl SingleFileMessagePackBackingStore {
|
||||
/// `push_all`'s write, under the exclusive lock the caller holds.
|
||||
fn merge_unlocked(&self, entries: &[CultCacheEnvelope]) -> Result<Vec<String>> {
|
||||
// Of entries sharing a key and a schema id the last one given is the record, whatever their type names (a type
|
||||
// renamed under a stable id); it replaces the held record under that key and schema id. A second schema id
|
||||
// under a key reaches the commit guard, which judges the merged store.
|
||||
let mut merged = self.read_all_unlocked()?;
|
||||
let mut by_id = BTreeMap::<(String, String), CultCacheEnvelope>::new();
|
||||
for entry in entries {
|
||||
by_id.insert((schema_identity(entry).to_string(), entry.key.clone()), restamped_over(entry, &merged)?);
|
||||
}
|
||||
let replaced: BTreeSet<_> = by_id.values().map(entry_id).collect();
|
||||
merged.retain(|held| !replaced.contains(&entry_id(held)));
|
||||
let stamps = entries
|
||||
.iter()
|
||||
.map(|entry| by_id[&(schema_identity(entry).to_string(), entry.key.clone())].stored_at.clone())
|
||||
.collect();
|
||||
merged.extend(by_id.values().cloned());
|
||||
merged.sort_by_key(entry_id);
|
||||
self.write_all_unlocked(&merged)?;
|
||||
for entry in by_id.values() {
|
||||
self.last_read.record(entry);
|
||||
}
|
||||
Ok(stamps)
|
||||
}
|
||||
}
|
||||
|
||||
const REDB_ENVELOPES: TableDefinition<&[u8], &[u8]> = TableDefinition::new("cultcache_envelopes");
|
||||
|
|
@ -2170,6 +2279,7 @@ const REDB_ENVELOPES: TableDefinition<&[u8], &[u8]> = TableDefinition::new("cult
|
|||
#[derive(Clone)]
|
||||
pub struct RedbMessagePackBackingStore {
|
||||
path: PathBuf,
|
||||
last_read: LastRead,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RedbMessagePackBackingStore {
|
||||
|
|
@ -2191,7 +2301,7 @@ impl RedbMessagePackBackingStore {
|
|||
fs::create_dir_all(parent)
|
||||
.with_context(|| format!("failed to create {}", parent.display()))?;
|
||||
}
|
||||
let store = Self { path };
|
||||
let store = Self { path, last_read: LastRead::default() };
|
||||
store.with_database(|database| {
|
||||
let write = database.begin_write()?;
|
||||
{
|
||||
|
|
@ -2542,6 +2652,7 @@ struct OwnedRedbInner {
|
|||
pub struct OwnedRedbMessagePackBackingStore {
|
||||
path: PathBuf,
|
||||
inner: Arc<OwnedRedbInner>,
|
||||
last_read: LastRead,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for OwnedRedbMessagePackBackingStore {
|
||||
|
|
@ -2612,6 +2723,7 @@ impl OwnedRedbMessagePackBackingStore {
|
|||
_owner_lock: owner_lock,
|
||||
file_identity: held_identity,
|
||||
}),
|
||||
last_read: LastRead::default(),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -2916,7 +3028,9 @@ impl CacheBackingStore for OwnedRedbMessagePackBackingStore {
|
|||
fn pull_all(&self) -> Result<Vec<CultCacheEnvelope>> {
|
||||
let read = self.inner.database.begin_read()?;
|
||||
let table = read.open_table(REDB_ENVELOPES)?;
|
||||
read_all_redb(&table)
|
||||
let entries = read_all_redb(&table)?;
|
||||
self.last_read.set_all(&entries);
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String> {
|
||||
|
|
@ -2926,6 +3040,7 @@ impl CacheBackingStore for OwnedRedbMessagePackBackingStore {
|
|||
insert_redb_entry(&mut table, entry)?;
|
||||
}
|
||||
write.commit()?;
|
||||
self.last_read.record(entry);
|
||||
Ok(entry.stored_at.clone())
|
||||
}
|
||||
|
||||
|
|
@ -2937,6 +3052,7 @@ impl CacheBackingStore for OwnedRedbMessagePackBackingStore {
|
|||
table.remove(key.as_slice())?;
|
||||
}
|
||||
write.commit()?;
|
||||
self.last_read.forget(&entry.key);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -2950,8 +3066,37 @@ impl CacheBackingStore for OwnedRedbMessagePackBackingStore {
|
|||
}
|
||||
}
|
||||
write.commit()?;
|
||||
entries.iter().for_each(|entry| self.last_read.record(entry));
|
||||
Ok(entries.iter().map(|entry| entry.stored_at.clone()).collect())
|
||||
}
|
||||
|
||||
fn push_all_unchanged(&mut self, entries: &[CultCacheEnvelope]) -> Result<CultPushUnchanged> {
|
||||
push_all_unchanged_redb(&self.inner.database, &self.last_read, entries)
|
||||
}
|
||||
}
|
||||
|
||||
/// The gated batch write of both redb stores: the write transaction is the exclusion, the gate reads every row inside it, and a
|
||||
/// moved store aborts it.
|
||||
fn push_all_unchanged_redb(database: &Database, last_read: &LastRead, entries: &[CultCacheEnvelope]) -> Result<CultPushUnchanged> {
|
||||
unique_batch_ids(entries, "push all")?;
|
||||
let write = database.begin_write()?;
|
||||
let changed_keys = {
|
||||
let mut table = write.open_table(REDB_ENVELOPES)?;
|
||||
let changed_keys = last_read.changed_keys(&read_all_redb(&table)?);
|
||||
if changed_keys.is_empty() {
|
||||
for entry in entries {
|
||||
insert_redb_entry(&mut table, entry)?;
|
||||
}
|
||||
}
|
||||
changed_keys
|
||||
};
|
||||
if !changed_keys.is_empty() {
|
||||
write.abort()?;
|
||||
return Ok(CultPushUnchanged::Changed { changed_keys });
|
||||
}
|
||||
write.commit()?;
|
||||
entries.iter().for_each(|entry| last_read.record(entry));
|
||||
Ok(CultPushUnchanged::Committed { stamps: entries.iter().map(|entry| entry.stored_at.clone()).collect() })
|
||||
}
|
||||
|
||||
fn redb_lock_path(path: &Path) -> PathBuf {
|
||||
|
|
@ -3091,7 +3236,9 @@ impl CacheBackingStore for RedbMessagePackBackingStore {
|
|||
self.with_database(|database| {
|
||||
let read = database.begin_read()?;
|
||||
let table = read.open_table(REDB_ENVELOPES)?;
|
||||
read_all_redb(&table)
|
||||
let entries = read_all_redb(&table)?;
|
||||
self.last_read.set_all(&entries);
|
||||
Ok(entries)
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -3103,6 +3250,7 @@ impl CacheBackingStore for RedbMessagePackBackingStore {
|
|||
insert_redb_entry(&mut table, entry)?;
|
||||
}
|
||||
write.commit()?;
|
||||
self.last_read.record(entry);
|
||||
Ok(entry.stored_at.clone())
|
||||
})
|
||||
}
|
||||
|
|
@ -3116,6 +3264,7 @@ impl CacheBackingStore for RedbMessagePackBackingStore {
|
|||
table.remove(key.as_slice())?;
|
||||
}
|
||||
write.commit()?;
|
||||
self.last_read.forget(&entry.key);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
|
@ -3131,9 +3280,14 @@ impl CacheBackingStore for RedbMessagePackBackingStore {
|
|||
}
|
||||
}
|
||||
write.commit()?;
|
||||
entries.iter().for_each(|entry| self.last_read.record(entry));
|
||||
Ok(entries.iter().map(|entry| entry.stored_at.clone()).collect())
|
||||
})
|
||||
}
|
||||
|
||||
fn push_all_unchanged(&mut self, entries: &[CultCacheEnvelope]) -> Result<CultPushUnchanged> {
|
||||
self.with_database(|database| push_all_unchanged_redb(database, &self.last_read, entries))
|
||||
}
|
||||
}
|
||||
|
||||
struct CultCacheStoreRegistration {
|
||||
|
|
@ -3192,6 +3346,67 @@ impl std::fmt::Display for CultCacheLoadRefused {
|
|||
|
||||
impl std::error::Error for CultCacheLoadRefused {}
|
||||
|
||||
/// A write of a type with a unique index refused because its store changed since this cache last read it. Uniqueness resolves
|
||||
/// against other records, which the cache's image may lack, so nothing was written; the cache reloaded the changed records (its
|
||||
/// image now holds them) and the write can be retried against what the store holds now. If the reload failed, the cache is
|
||||
/// refused as any failed pull leaves it, and the reload error is this error's source. Names keys, never values.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CultCacheWriteConflict {
|
||||
/// The keys this write would have written, in UTF-16 order.
|
||||
pub record_keys: Vec<String>,
|
||||
/// The keys whose records differ from what the cache last read, in UTF-16 order.
|
||||
pub changed_keys: Vec<String>,
|
||||
reload_failed: bool,
|
||||
}
|
||||
|
||||
impl CultCacheWriteConflict {
|
||||
/// Whether reloading the changed records failed. When it did, the cache is refused (every write returns
|
||||
/// `CultCacheLoadRefused` until a pull succeeds) and the reload error is this error's source; otherwise the cache already
|
||||
/// holds the changed records and the write can be retried.
|
||||
pub fn reload_failed(&self) -> bool {
|
||||
self.reload_failed
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CultCacheWriteConflict {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let quoted = |keys: &[String]| keys.iter().map(|key| format!("'{key}'")).collect::<Vec<_>>().join(", ");
|
||||
write!(
|
||||
formatter,
|
||||
"The backing store changed since this cache last read it, and it holds a record with a unique index, which resolve against other records; nothing was written. Records this write would have written: {}; records that changed: {}. {}",
|
||||
quoted(&self.record_keys),
|
||||
quoted(&self.changed_keys),
|
||||
if self.reload_failed {
|
||||
"Reloading them failed, so the cache is refused."
|
||||
} else {
|
||||
"The cache reloaded them; retry the write against what the store holds now."
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for CultCacheWriteConflict {}
|
||||
|
||||
/// How a landing reaches its home store.
|
||||
enum LandAs {
|
||||
/// One record, replacing what is there (`push`).
|
||||
Record,
|
||||
/// One record over the record at the given version (`commit_if`; `Some(None)`: over nothing).
|
||||
Over(Option<String>),
|
||||
/// Many records, each replacing its own identity and nothing else (`push_all`).
|
||||
Batch,
|
||||
}
|
||||
|
||||
/// What a landing found at its home store.
|
||||
enum Landed {
|
||||
/// Written; one stamp per record landed.
|
||||
Stamps(Vec<String>),
|
||||
/// `LandAs::Over` found another version there; nothing was written.
|
||||
Mismatch,
|
||||
/// A gated landing found the store moved; nothing was written and the cache reloaded.
|
||||
Moved(CultCacheWriteConflict),
|
||||
}
|
||||
|
||||
/// A record a store holds that no registered type claims: carried, never served.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ForeignRecord {
|
||||
|
|
@ -3842,7 +4057,11 @@ impl CultCache {
|
|||
.collect::<BTreeMap<_, _>>()
|
||||
.into_values()
|
||||
.collect();
|
||||
let stamps = self.stores[store_index].store.push_all(&landing, PushAllOptions::default())?;
|
||||
let stamps = match self.land(store_index, &landing, LandAs::Batch)? {
|
||||
Landed::Stamps(stamps) => stamps,
|
||||
Landed::Moved(conflict) => return Err(conflict.into()),
|
||||
Landed::Mismatch => unreachable!("a batch is not written over a version"),
|
||||
};
|
||||
if stamps.len() == landing.len() {
|
||||
for (entry, stamp) in landing.iter().zip(stamps) {
|
||||
if chrono::DateTime::parse_from_rfc3339(&stamp).is_ok()
|
||||
|
|
@ -3894,6 +4113,38 @@ impl CultCache {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// The one door from the cache to a home store. A landing with an entry of a type that has a projector (a unique index) is
|
||||
/// gated: its store must still hold what this cache last read, compared under the store's own exclusion by
|
||||
/// `push_all_unchanged`, because the uniqueness judge only knows the cache's image. A store that moved is not written; the
|
||||
/// cache reloads and the conflict comes back as `Moved` (a failed reload is the error, the conflict its context). Every
|
||||
/// other landing reaches the store by its own door.
|
||||
fn land(&mut self, home: usize, landing: &[CultCacheEnvelope], how: LandAs) -> Result<Landed> {
|
||||
if landing.iter().any(|entry| self.projectors.contains_key(&entry.r#type)) {
|
||||
return match self.stores[home].store.push_all_unchanged(landing)? {
|
||||
CultPushUnchanged::Committed { stamps } => Ok(Landed::Stamps(stamps)),
|
||||
CultPushUnchanged::Changed { changed_keys } => {
|
||||
let mut record_keys: Vec<String> = landing.iter().map(|entry| entry.key.clone()).collect();
|
||||
record_keys.sort_by(|left, right| utf16_cmp(left, right));
|
||||
record_keys.dedup();
|
||||
let conflict = CultCacheWriteConflict { record_keys, changed_keys, reload_failed: false };
|
||||
match self.pull_all_backing_stores() {
|
||||
Ok(()) => Ok(Landed::Moved(conflict)),
|
||||
Err(error) => Err(error.context(CultCacheWriteConflict { reload_failed: true, ..conflict })),
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
let store = &mut self.stores[home].store;
|
||||
match how {
|
||||
LandAs::Record => Ok(Landed::Stamps(vec![store.push(&landing[0])?])),
|
||||
LandAs::Over(expected) => Ok(match store.commit_if(&landing[0], expected.as_deref())? {
|
||||
CultCommitIf::Committed { stored_at } => Landed::Stamps(vec![stored_at]),
|
||||
CultCommitIf::Mismatch => Landed::Mismatch,
|
||||
}),
|
||||
LandAs::Batch => Ok(Landed::Stamps(store.push_all(landing, PushAllOptions::default())?)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one landing of a single record, for `put`, `put_envelope`, `put_raw_envelope` and `update`: the global, retype and
|
||||
/// unique judges, then the home store's write, then the install of the stamp the store reports (kept only when it parses
|
||||
/// as RFC 3339, else the entry's own). `expected` is `None` for a blind write; `Some(version)` writes only over the record at
|
||||
|
|
@ -3903,15 +4154,22 @@ impl CultCache {
|
|||
self.refuse_retype(&self.entries, &self.foreign, &entry)?;
|
||||
let change = self.judge_unique(&[&entry])?;
|
||||
if let Some(home) = self.home_index(&entry.r#type)? {
|
||||
let stored_at = match expected {
|
||||
None => self.stores[home].store.push(&entry)?,
|
||||
Some(version) => match self.stores[home].store.commit_if(&entry, version.as_deref())? {
|
||||
CultCommitIf::Committed { stored_at } => stored_at,
|
||||
CultCommitIf::Mismatch => return Ok(false),
|
||||
},
|
||||
let how = match expected {
|
||||
None => LandAs::Record,
|
||||
Some(version) => LandAs::Over(version),
|
||||
};
|
||||
if chrono::DateTime::parse_from_rfc3339(&stored_at).is_ok() {
|
||||
entry.stored_at = stored_at;
|
||||
let blind = matches!(how, LandAs::Record);
|
||||
match self.land(home, std::slice::from_ref(&entry), how)? {
|
||||
Landed::Stamps(stamps) => {
|
||||
if let Some(stored_at) = stamps.into_iter().next()
|
||||
&& chrono::DateTime::parse_from_rfc3339(&stored_at).is_ok()
|
||||
{
|
||||
entry.stored_at = stored_at;
|
||||
}
|
||||
}
|
||||
Landed::Mismatch => return Ok(false),
|
||||
Landed::Moved(conflict) if blind => return Err(conflict.into()),
|
||||
Landed::Moved(_) => return Ok(false),
|
||||
}
|
||||
}
|
||||
self.entries.insert(entry_id(&entry), entry);
|
||||
|
|
@ -9347,6 +9605,145 @@ mod tests {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
|
||||
#[cultcache(type = "indexed", schema = "tests.indexed")]
|
||||
struct Indexed {
|
||||
#[cultcache(key = 0, index = "Sku")]
|
||||
sku: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_without_the_door_refuses_indexed_writes() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_registry(TestEntries)?;
|
||||
cache.register_entry_type::<Indexed>()?;
|
||||
cache.add_generic_backing_store(RefusingBatchStore {
|
||||
inner: SingleFileMessagePackBackingStore::new(temp.path().join("refusing.cc")),
|
||||
refuse_batch: Arc::new(AtomicBool::new(false)),
|
||||
})?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
let refused = cache.put("k", &Indexed { sku: "S".to_string() }).unwrap_err();
|
||||
assert!(format!("{refused:#}").contains("push_all_unchanged"), "{refused:#}");
|
||||
assert!(cache.get::<Indexed>("k")?.is_none());
|
||||
cache.put("plain", &Note { title: "t".to_string(), body: "b".to_string() })?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn raw_rows(database: &Database, rows: &[&CultCacheEnvelope]) -> Result<()> {
|
||||
let write = database.begin_write()?;
|
||||
{
|
||||
let mut table = write.open_table(REDB_ENVELOPES)?;
|
||||
for row in rows {
|
||||
table.insert(redb_identity(row)?.as_slice(), rmp_serde::to_vec(row)?.as_slice())?;
|
||||
}
|
||||
}
|
||||
write.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Both redb stores, each holding `rows` as an older build could have written them (two types at one key).
|
||||
fn redb_stores_holding(temp: &Path, rows: &[&CultCacheEnvelope]) -> Result<Vec<Box<dyn CacheBackingStore>>> {
|
||||
let plain = RedbMessagePackBackingStore::new(temp.join("plain.db"))?;
|
||||
plain.with_database(|database| raw_rows(database, rows))?;
|
||||
let owned = OwnedRedbMessagePackBackingStore::new(temp.join("owned.db"))?;
|
||||
raw_rows(&owned.inner.database, rows)?;
|
||||
Ok(vec![Box::new(plain), Box::new(owned)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_of_the_same_type_under_another_schema_id_is_overwritten_not_refused() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let mut old = test_envelope("a", "k", b"old");
|
||||
old.schema_id = Some("S1".to_string());
|
||||
for mut store in redb_stores_holding(temp.path(), &[&old])? {
|
||||
let mut restamped = test_envelope("a", "k", b"new");
|
||||
restamped.schema_id = Some("S2".to_string());
|
||||
store.push(&restamped)?;
|
||||
assert_eq!(store.pull_all()?, vec![restamped.clone()]);
|
||||
store.push_all(std::slice::from_ref(&old), PushAllOptions::default())?;
|
||||
assert_eq!(store.pull_all()?, vec![old.clone()]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_holding_two_types_at_a_key_refuses_both_writes_until_one_is_deleted() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let (a, b) = (test_envelope("a", "k", b"1"), test_envelope("b", "k", b"2"));
|
||||
for mut store in redb_stores_holding(temp.path(), &[&a, &b])? {
|
||||
// Neither held type can be rewritten while the other is held there.
|
||||
for rewrite in [test_envelope("a", "k", b"3"), test_envelope("b", "k", b"3")] {
|
||||
let refused = store.push(&rewrite).unwrap_err();
|
||||
assert!(refused.downcast_ref::<SchemaConflictError>().is_some(), "{refused:#}");
|
||||
}
|
||||
assert_eq!(store.pull_all()?.len(), 2, "nothing was written");
|
||||
// delete(type, key) removes that type's row alone: the repair path.
|
||||
store.delete(&b)?;
|
||||
assert_eq!(store.pull_all()?, vec![a.clone()]);
|
||||
let rewrite = test_envelope("a", "k", b"3");
|
||||
store.push(&rewrite)?;
|
||||
assert_eq!(store.pull_all()?, vec![rewrite]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cache_refuses_to_pull_an_owned_redb_store_holding_two_types_at_a_key() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let owned = OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?;
|
||||
let settings = test_envelope("settings", "shared", b"1");
|
||||
let mut stamped = test_envelope("note", "shared", b"2");
|
||||
stamped.schema_id = Some("settings".to_string());
|
||||
raw_rows(&owned.inner.database, &[&settings, &stamped])?;
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_registry(TestEntries)?;
|
||||
cache.add_generic_backing_store(owned)?;
|
||||
let error = cache.pull_all_backing_stores().unwrap_err();
|
||||
assert_eq!(retype_refusal(&error).record_key, "shared");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Two writers race two types onto one key of one file: the store's own exclusion lets exactly one in.
|
||||
#[test]
|
||||
fn two_writers_racing_two_types_onto_one_key_leave_one_winner() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let owned = OwnedRedbMessagePackBackingStore::new(temp.path().join("owned.db"))?;
|
||||
type Opener = Box<dyn Fn() -> Box<dyn CacheBackingStore + Send>>;
|
||||
let stores: Vec<(&str, Opener)> = vec![
|
||||
("single", Box::new({
|
||||
let path = temp.path().join("single.cc");
|
||||
move || -> Box<dyn CacheBackingStore + Send> { Box::new(SingleFileMessagePackBackingStore::new(&path)) }
|
||||
})),
|
||||
("redb", Box::new({
|
||||
let path = temp.path().join("plain.db");
|
||||
move || -> Box<dyn CacheBackingStore + Send> { Box::new(RedbMessagePackBackingStore::new(&path).unwrap()) }
|
||||
})),
|
||||
("owned", Box::new(move || -> Box<dyn CacheBackingStore + Send> { Box::new(owned.clone()) })),
|
||||
];
|
||||
for (name, open) in &stores {
|
||||
for round in 0..30 {
|
||||
let key = format!("k{round}");
|
||||
let gate = Arc::new(std::sync::Barrier::new(2));
|
||||
let racers: Vec<_> = ["a", "b"]
|
||||
.into_iter()
|
||||
.map(|kind| {
|
||||
let (mut store, gate, key) = (open(), gate.clone(), key.clone());
|
||||
std::thread::spawn(move || {
|
||||
gate.wait();
|
||||
store.push(&test_envelope(kind, &key, kind.as_bytes())).is_ok()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let wins = racers.into_iter().map(|racer| racer.join().unwrap()).filter(|won| *won).count();
|
||||
assert_eq!(wins, 1, "{name} round {round}");
|
||||
let held = open().pull_all()?.into_iter().filter(|row| row.key == key).count();
|
||||
assert_eq!(held, 1, "{name} round {round}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redb_skip_scan_finds_a_row_of_any_type() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@
|
|||
use std::path::{Path, PathBuf};
|
||||
|
||||
use cultcache_rs::{
|
||||
CultCache, CultCacheEnvelope, CultCacheLoadRefused, CultCacheSoaTable, DatabaseEntry, SingleFileMessagePackBackingStore,
|
||||
CultCache, CultCacheEnvelope, CultCacheLoadRefused, CultCacheSoaTable, CultCacheWriteConflict, CultUpdateOutcome,
|
||||
DatabaseEntry, OwnedRedbMessagePackBackingStore, RedbMessagePackBackingStore, SingleFileMessagePackBackingStore,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
|
|
@ -354,6 +355,217 @@ fn every_write_path_refuses_and_changes_nothing() {
|
|||
assert!(reopened.put("m:x", &multi(Some("zz"), Some("yy"))).is_ok());
|
||||
}
|
||||
|
||||
/// Which store a stale-writer scenario runs on. `Owned` hands every cache a clone of one pinned handle (each clone is another
|
||||
/// reader).
|
||||
enum Kind {
|
||||
Single,
|
||||
Redb,
|
||||
Owned(OwnedRedbMessagePackBackingStore),
|
||||
}
|
||||
|
||||
fn kinds(dir: &Path) -> Vec<(&'static str, Kind)> {
|
||||
vec![
|
||||
("single", Kind::Single),
|
||||
("redb", Kind::Redb),
|
||||
("owned", Kind::Owned(OwnedRedbMessagePackBackingStore::new(dir.join("owned.db")).unwrap())),
|
||||
]
|
||||
}
|
||||
|
||||
/// A cache over the kind's store that has pulled it, so its image is what the store holds now.
|
||||
fn reader(kind: &Kind, dir: &Path) -> CultCache {
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<Unique>().unwrap();
|
||||
cache.register_entry_type::<Plain>().unwrap();
|
||||
match kind {
|
||||
Kind::Single => cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(dir.join("s.cc"))),
|
||||
Kind::Redb => cache.add_generic_backing_store(RedbMessagePackBackingStore::new(dir.join("r.db")).unwrap()),
|
||||
Kind::Owned(owned) => cache.add_generic_backing_store(owned.clone()),
|
||||
}
|
||||
.unwrap();
|
||||
cache.pull_all_backing_stores().unwrap();
|
||||
cache
|
||||
}
|
||||
|
||||
const CANARY: &str = "canary-value-no-refusal-may-echo";
|
||||
|
||||
fn conflict_of(error: &anyhow::Error) -> &CultCacheWriteConflict {
|
||||
error.downcast_ref::<CultCacheWriteConflict>().unwrap_or_else(|| panic!("not a write conflict: {error:#}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_onto_a_moved_store_is_a_conflict_and_the_retry_is_refused() {
|
||||
for kind in ["single", "redb", "owned"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1;
|
||||
let mut seed = reader(&kind, dir.path());
|
||||
seed.put("a", &unique("base")).unwrap();
|
||||
let mut second = reader(&kind, dir.path());
|
||||
reader(&kind, dir.path()).put("b", &unique(CANARY)).unwrap();
|
||||
|
||||
let error = second.put("c", &unique(CANARY)).unwrap_err();
|
||||
let conflict = conflict_of(&error);
|
||||
assert_eq!(conflict.record_keys, ["c"]);
|
||||
assert_eq!(conflict.changed_keys, ["b"]);
|
||||
assert!(!conflict.reload_failed());
|
||||
let text = error.to_string();
|
||||
assert_eq!(
|
||||
text,
|
||||
"The backing store changed since this cache last read it, and it holds a record with a unique index, which resolve against other records; nothing was written. Records this write would have written: 'c'; records that changed: 'b'. The cache reloaded them; retry the write against what the store holds now."
|
||||
);
|
||||
assert!(text.contains("unique index") && text.contains("'b'") && text.contains("'c'"), "{text}");
|
||||
assert!(!text.contains(CANARY), "the conflict names keys, never values");
|
||||
assert!(second.get::<Unique>("b").unwrap().is_some(), "the moved record is loaded");
|
||||
|
||||
let retry = error_text(second.put("c", &unique(CANARY)));
|
||||
assert!(retry.contains('b') && retry.contains('c') && !retry.contains(CANARY), "{retry}");
|
||||
let fresh = reader(&kind, dir.path());
|
||||
assert!(fresh.get::<Unique>("b").unwrap().is_some());
|
||||
assert!(fresh.get::<Unique>("c").unwrap().is_none(), "the store never holds the pair");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_store_refuses_even_without_a_collision() {
|
||||
for kind in ["single", "redb", "owned"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1;
|
||||
let mut seed = reader(&kind, dir.path());
|
||||
seed.put("a", &unique("base")).unwrap();
|
||||
let mut second = reader(&kind, dir.path());
|
||||
reader(&kind, dir.path()).put("z", &Plain { value: "elsewhere".into() }).unwrap();
|
||||
|
||||
let error = second.put("c", &unique("fresh")).unwrap_err();
|
||||
assert_eq!(conflict_of(&error).changed_keys, ["z"]);
|
||||
assert!(second.get::<Plain>("z").unwrap().is_some());
|
||||
second.put("c", &unique("fresh")).unwrap();
|
||||
assert!(reader(&kind, dir.path()).get::<Unique>("c").unwrap().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_gated_door_takes_the_gate() {
|
||||
for kind in ["single", "redb", "owned"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1;
|
||||
let mut second = reader(&kind, dir.path());
|
||||
let mut other = reader(&kind, dir.path());
|
||||
let mut moves = 0;
|
||||
let mut move_store = |other: &mut CultCache| {
|
||||
moves += 1;
|
||||
other.put(&format!("moved{moves}"), &Plain { value: "m".into() }).unwrap();
|
||||
};
|
||||
|
||||
move_store(&mut other);
|
||||
conflict_of(&second.put("d1", &unique("S1")).unwrap_err());
|
||||
second.put("d1", &unique("S1")).unwrap();
|
||||
|
||||
move_store(&mut other);
|
||||
let envelope = second.prepare_entry("d2", &unique("S2")).unwrap().0;
|
||||
conflict_of(&second.put_envelope::<Unique>(envelope.clone()).unwrap_err());
|
||||
second.put_envelope::<Unique>(envelope).unwrap();
|
||||
|
||||
move_store(&mut other);
|
||||
let envelope = second.prepare_entry("d3", &unique("S3")).unwrap().0;
|
||||
conflict_of(&second.put_raw_envelope(envelope.clone()).unwrap_err());
|
||||
second.put_raw_envelope(envelope).unwrap();
|
||||
|
||||
move_store(&mut other);
|
||||
let rows = staged(&second, &[("d4", unique("S4"))]);
|
||||
conflict_of(&second.put_prepared_batch(rows.clone()).unwrap_err());
|
||||
second.put_prepared_batch(rows).unwrap();
|
||||
|
||||
// A batch with one indexed entry among plain ones is gated whole.
|
||||
move_store(&mut other);
|
||||
let plain = second.prepare_entry("batch-plain", &Plain { value: "p".into() }).unwrap().0;
|
||||
let indexed = second.prepare_entry("batch-indexed", &unique("S5")).unwrap().0;
|
||||
conflict_of(&second.put_prepared_batch(vec![plain.clone(), indexed.clone()]).unwrap_err());
|
||||
assert!(reader(&kind, dir.path()).get::<Plain>("batch-plain").unwrap().is_none(), "nothing of the batch landed");
|
||||
second.put_prepared_batch(vec![plain, indexed]).unwrap();
|
||||
assert!(reader(&kind, dir.path()).get::<Plain>("batch-plain").unwrap().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ungated_write_onto_a_moved_store_still_merges() {
|
||||
for kind in ["single", "redb", "owned"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1;
|
||||
let mut second = reader(&kind, dir.path());
|
||||
reader(&kind, dir.path()).put("one", &Plain { value: "1".into() }).unwrap();
|
||||
second.put("two", &Plain { value: "2".into() }).unwrap();
|
||||
let fresh = reader(&kind, dir.path());
|
||||
assert!(fresh.get::<Plain>("one").unwrap().is_some() && fresh.get::<Plain>("two").unwrap().is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_retries_after_a_moved_store() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("update.cc");
|
||||
for (attempts, expected, applied) in [(5, CultUpdateOutcome::Updated, 2), (1, CultUpdateOutcome::LostRace, 1)] {
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let mut second = cache_at(&path);
|
||||
cache_at(&path).put("b", &unique("elsewhere")).unwrap();
|
||||
let mut calls = 0;
|
||||
let result = second
|
||||
.update_with_attempts::<Unique, _>("c", attempts, |_| {
|
||||
calls += 1;
|
||||
Some(unique("fresh"))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!((result.outcome, calls), (expected, applied), "max attempts {attempts}");
|
||||
assert_eq!(cache_at(&path).get::<Unique>("c").unwrap().is_some(), expected == CultUpdateOutcome::Updated);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_reload_leaves_the_cache_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("reload.cc");
|
||||
let mut second = cache_at(&path);
|
||||
// The other writer holds one value twice through the index-free twin type, so the store no longer loads.
|
||||
let mut twin = twin_cache_at(&path);
|
||||
twin.put("item:b", &Twin { sku: "S".into(), category: "c".into() }).unwrap();
|
||||
twin.put("item:a", &Twin { sku: "S".into(), category: "c".into() }).unwrap();
|
||||
|
||||
let error = second.put("c", &unique("fresh")).unwrap_err();
|
||||
assert!(conflict_of(&error).reload_failed());
|
||||
assert!(error.to_string().contains("Reloading them failed"));
|
||||
assert!(format!("{error:#}").contains("both hold unique index"), "the reload error is the source: {error:#}");
|
||||
let next = second.put("d", &unique("other")).unwrap_err();
|
||||
assert!(next.downcast_ref::<CultCacheLoadRefused>().is_some(), "{next:#}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_read_follows_this_handles_own_writes() {
|
||||
for kind in ["single", "redb", "owned"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1;
|
||||
let mut cache = reader(&kind, dir.path());
|
||||
cache.put("a", &unique("A")).unwrap();
|
||||
cache.put("p", &Plain { value: "1".into() }).unwrap();
|
||||
cache.put("b", &unique("B")).unwrap();
|
||||
let mut rows = staged(&cache, &[("p", Plain { value: "2".into() })]);
|
||||
rows.extend(staged(&cache, &[("c", unique("C"))]));
|
||||
cache.put_prepared_batch(rows).unwrap();
|
||||
assert!(cache.delete::<Plain>("p").unwrap());
|
||||
// An ungated batch is a landing the store records too.
|
||||
cache.put_prepared_batch(staged(&cache, &[("q", Plain { value: "q".into() })])).unwrap();
|
||||
cache.put("d", &unique("D")).unwrap();
|
||||
cache.put("a", &unique("A2")).unwrap();
|
||||
assert!(cache.delete::<Unique>("c").unwrap());
|
||||
cache.put("e", &unique("C")).unwrap();
|
||||
assert_eq!(reader(&kind, dir.path()).get_all_with_keys::<Unique>().unwrap().len(), 4);
|
||||
}
|
||||
// update on the single-file store keeps it current too.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut cache = cache_at(&dir.path().join("own-update.cc"));
|
||||
cache.put("a", &unique("A")).unwrap();
|
||||
cache.update::<Unique, _>("a", |_| Some(unique("A2"))).unwrap();
|
||||
cache.update::<Unique, _>("b", |_| Some(unique("B"))).unwrap();
|
||||
cache.put("c", &unique("C")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_is_judged_whole() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
@ -821,3 +1033,78 @@ fn registering_without_the_index_releases_the_holders() {
|
|||
cache.put("b", &Twin { sku: "S".into(), category: "x".into() }).unwrap();
|
||||
assert!(cache.register_entry_type::<Unique>().is_err(), "the duplicate now written is a held violation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_another_writer_removed_or_added_moves_the_store_and_the_keys_come_back_in_utf16_order() {
|
||||
for kind in ["single", "redb", "owned"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1;
|
||||
let mut seed = reader(&kind, dir.path());
|
||||
seed.put("a", &Plain { value: "gone soon".into() }).unwrap();
|
||||
let mut second = reader(&kind, dir.path());
|
||||
let mut other = reader(&kind, dir.path());
|
||||
|
||||
// A removal alone moves the store.
|
||||
assert!(other.delete::<Plain>("a").unwrap());
|
||||
assert_eq!(conflict_of(&second.put("c", &unique("fresh")).unwrap_err()).changed_keys, ["a"]);
|
||||
assert!(second.get::<Plain>("a").unwrap().is_none(), "the removal is loaded");
|
||||
|
||||
// Keys sort by UTF-16 code unit: b, then the astral U+10400 (D801 DC00), then U+FF21.
|
||||
for key in ["\u{ff21}", "\u{10400}", "b"] {
|
||||
other.put(key, &Plain { value: "x".into() }).unwrap();
|
||||
}
|
||||
assert_eq!(conflict_of(&second.put("c", &unique("fresh")).unwrap_err()).changed_keys, ["b", "\u{10400}", "\u{ff21}"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mover_that_took_the_same_key_with_another_type_is_a_conflict_not_a_retype_refusal() {
|
||||
for kind in ["single", "redb", "owned"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1;
|
||||
let mut second = reader(&kind, dir.path());
|
||||
reader(&kind, dir.path()).put("k", &Plain { value: "first".into() }).unwrap();
|
||||
|
||||
let error = second.put("k", &unique("S")).unwrap_err();
|
||||
assert_eq!(conflict_of(&error).changed_keys, ["k"]);
|
||||
assert!(second.get::<Plain>("k").unwrap().is_some(), "the cache reloaded the mover's record");
|
||||
let retry = second.put("k", &unique("S")).unwrap_err();
|
||||
assert!(retry.downcast_ref::<CultCacheWriteConflict>().is_none(), "the retry meets the retype rule: {retry:#}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two caches that both hold the current image race one value onto two keys through the gate: the store's exclusion lets
|
||||
/// exactly one in, and the other is a conflict that reloaded.
|
||||
#[test]
|
||||
fn two_caches_racing_one_value_through_the_gate_leave_one_holder() {
|
||||
for kind in ["single", "redb", "owned"] {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let kind = kinds(dir.path()).into_iter().find(|(name, _)| *name == kind).unwrap().1;
|
||||
let mut left = reader(&kind, dir.path());
|
||||
let mut right = reader(&kind, dir.path());
|
||||
for round in 0..25 {
|
||||
let value = format!("V{round}");
|
||||
let gate = std::sync::Barrier::new(2);
|
||||
let (won_left, won_right) = std::thread::scope(|scope| {
|
||||
let (gate, value) = (&gate, &value);
|
||||
let attempt = move |cache: &mut CultCache, key: String| {
|
||||
gate.wait();
|
||||
match cache.put(&key, &unique(value)) {
|
||||
Ok(_) => true,
|
||||
Err(error) => {
|
||||
conflict_of(&error);
|
||||
false
|
||||
}
|
||||
}
|
||||
};
|
||||
let (left, right) = (&mut left, &mut right);
|
||||
let l = scope.spawn(move || attempt(left, format!("l{round}")));
|
||||
let r = scope.spawn(move || attempt(right, format!("r{round}")));
|
||||
(l.join().unwrap(), r.join().unwrap())
|
||||
});
|
||||
assert!(won_left ^ won_right, "{round}: exactly one writer lands (left {won_left}, right {won_right})");
|
||||
let held = reader(&kind, dir.path()).get_all_with_keys::<Unique>().unwrap();
|
||||
assert_eq!(held.iter().filter(|(_, row)| row.sku == value).count(), 1, "round {round}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue