cultcache-rs: an injectable cache clock; stores restamp without reading a clock (#189)
This commit is contained in:
parent
3e550dffe1
commit
6841760947
3 changed files with 99 additions and 41 deletions
|
|
@ -12,6 +12,7 @@ only in git history.
|
|||
- `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`.
|
||||
- `CultCache::set_clock(impl Fn() -> DateTime<Utc> + Send + 'static)`: the one clock that stamps fresh writes (second precision; `Utc::now` by default). Pin it to write reproducible stores; a replacing write is still stamped later than the record it replaces. A pinned clock alone is not byte-identity wherever a writer mints random values of its own (the C# writer's unset element ids); this writer mints none.
|
||||
|
||||
### Fixed
|
||||
|
||||
|
|
@ -23,8 +24,9 @@ only in git history.
|
|||
- Rust-written catalog entries carry member rows, so a C# reader whose declaration differs now refuses the store; the new `SchemaCatalogEntry` field breaks struct-literal construction.
|
||||
- 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)`).
|
||||
- A store's restamp of a replacing write reads no clock: `max(staged, replaced + 1 microsecond)`, as TypeScript does (variants cultlib-gaps ruling `sibling-restamp-staged-derived`). Before, an unlater staged stamp was replaced by now if later than the replaced stamp. A replaced stamp that does not parse leaves the staged stamp as written. The C# reference stamps such a write with its cache clock's now; ordering (later than what it replaced) is the same.
|
||||
- `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.
|
||||
- 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), 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.
|
||||
- The single-file store re-checks for a link once the store lock is held (every write and the try-exchange), so a link put at the path while a writer waited on the lock is refused with `StoreLinkedError` and the lock released, as C# does, instead of being replaced. Pinned by a test that puts the link while a second holder owns the lock.
|
||||
- `CultCache::is_writable` does not look at store paths: a link at a store path is not predicted, and the write refuses it with `StoreLinkedError`. Pinned by a test through a cache attached to a linked store.
|
||||
|
||||
|
|
|
|||
|
|
@ -170,6 +170,7 @@ without pretending Rust has runtime reflection hiding under the floorboards.
|
|||
## Current Surface
|
||||
|
||||
- `CultCache::new`
|
||||
- `set_clock` (the clock that stamps fresh writes; pin it for reproducible stores; a writer that mints random values of its own, such as the C# writer's unset element ids, still breaks byte-identity)
|
||||
- `register_entry_type::<T>`
|
||||
- `add_generic_backing_store`
|
||||
- `add_backing_store`
|
||||
|
|
|
|||
|
|
@ -3436,6 +3436,8 @@ pub struct CultCache {
|
|||
foreign: Vec<(usize, CultCacheEnvelope)>,
|
||||
/// Whether the cache holds an image of its stores. While it is not `Pulled`, every write and removal is refused.
|
||||
load: LoadState,
|
||||
/// The one source of "now" for every stamp a write of this cache mints; `Utc::now` unless `set_clock` replaced it.
|
||||
clock: Box<dyn Fn() -> chrono::DateTime<chrono::Utc> + Send>,
|
||||
}
|
||||
|
||||
/// What the cache knows of its stores. `Unpulled` is the state of a cache that has never pulled, or that gained a store
|
||||
|
|
@ -3592,9 +3594,18 @@ impl CultCache {
|
|||
stores: Vec::new(),
|
||||
foreign: Vec::new(),
|
||||
load: LoadState::Unpulled,
|
||||
clock: Box::new(chrono::Utc::now),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the clock that stamps fresh writes (`Utc::now` by default; stamps keep second precision). Pin it to write
|
||||
/// reproducible stores. A replacing write is still stamped later than the record it replaces, per key, derived from the
|
||||
/// two stamps and no clock. A pinned clock alone does not make two stores byte-identical where a writer mints random
|
||||
/// values of its own (the C# writer's unset element ids); this writer mints none.
|
||||
pub fn set_clock(&mut self, clock: impl Fn() -> chrono::DateTime<chrono::Utc> + Send + 'static) {
|
||||
self.clock = Box::new(clock);
|
||||
}
|
||||
|
||||
pub fn register_entry_type<T: DatabaseEntry>(&mut self) -> Result<()> {
|
||||
if T::TYPE.trim().is_empty() {
|
||||
return Err(anyhow!(
|
||||
|
|
@ -4131,7 +4142,7 @@ impl CultCache {
|
|||
key: key.clone(),
|
||||
r#type: T::TYPE.to_string(),
|
||||
payload,
|
||||
stored_at: now_utc_second(),
|
||||
stored_at: (self.clock)().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
|
||||
schema_id: Some(T::TYPE.to_string()),
|
||||
};
|
||||
Ok((entry, parsed))
|
||||
|
|
@ -4724,35 +4735,33 @@ fn record_version(entry: &CultCacheEnvelope) -> String {
|
|||
Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect()
|
||||
}
|
||||
|
||||
/// A stamp strictly later than `previous` (to the microsecond): `now` truncated to the microsecond when that is later,
|
||||
/// otherwise `previous` truncated plus one microsecond. An absent or unparseable `previous` gives `now`. A successor past
|
||||
/// year 9999 does not exist as a stamp any runtime reads, so it is refused (C# `MintStoredAt` throws there).
|
||||
fn mint_stored_at(previous: Option<&str>, now: chrono::DateTime<chrono::Utc>) -> Result<String> {
|
||||
/// The stamp one microsecond after `replaced` (truncated to the microsecond), or `None` when `replaced` does not parse. A
|
||||
/// successor past year 9999 does not exist as a stamp any runtime reads, so it is refused (C# `MintStoredAt` throws there).
|
||||
fn successor_stamp(replaced: &str) -> Result<Option<String>> {
|
||||
use chrono::SubsecRound;
|
||||
let now = now.trunc_subsecs(6);
|
||||
let minted = match previous.and_then(|text| chrono::DateTime::parse_from_rfc3339(text).ok()) {
|
||||
Some(previous) => {
|
||||
let previous = previous.with_timezone(&chrono::Utc).trunc_subsecs(6);
|
||||
if now <= previous {
|
||||
previous
|
||||
.checked_add_signed(chrono::Duration::microseconds(1))
|
||||
.filter(|successor| chrono::Datelike::year(successor) <= 9999)
|
||||
.ok_or_else(|| anyhow!("stored_at {previous} has no later stamp: the successor is past year 9999"))?
|
||||
} else {
|
||||
now
|
||||
}
|
||||
}
|
||||
None => now,
|
||||
let Ok(replaced) = chrono::DateTime::parse_from_rfc3339(replaced) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(minted.to_rfc3339_opts(chrono::SecondsFormat::Micros, true))
|
||||
let replaced = replaced.with_timezone(&chrono::Utc).trunc_subsecs(6);
|
||||
let successor = replaced
|
||||
.checked_add_signed(chrono::Duration::microseconds(1))
|
||||
.filter(|successor| chrono::Datelike::year(successor) <= 9999)
|
||||
.ok_or_else(|| anyhow!("stored_at {replaced} has no later stamp: the successor is past year 9999"))?;
|
||||
Ok(Some(successor.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)))
|
||||
}
|
||||
|
||||
/// The stamp a replacing write carries: `staged` stands only when both stamps parse and it is strictly later than `replaced`.
|
||||
/// The stamp a replacing write carries, derived from the two stamps and no clock: `staged` stands only when both parse and it
|
||||
/// is strictly later than `replaced`; otherwise the replaced stamp plus one microsecond. A `replaced` that does not parse
|
||||
/// leaves nothing to be later than, so `staged` stands.
|
||||
fn stored_at_over(staged: &str, replaced: &str) -> Result<String> {
|
||||
match (chrono::DateTime::parse_from_rfc3339(staged), chrono::DateTime::parse_from_rfc3339(replaced)) {
|
||||
(Ok(staged_at), Ok(replaced_at)) if staged_at > replaced_at => Ok(staged.to_string()),
|
||||
_ => mint_stored_at(Some(replaced), chrono::Utc::now()),
|
||||
let later = matches!(
|
||||
(chrono::DateTime::parse_from_rfc3339(staged), chrono::DateTime::parse_from_rfc3339(replaced)),
|
||||
(Ok(staged_at), Ok(replaced_at)) if staged_at > replaced_at
|
||||
);
|
||||
if later {
|
||||
return Ok(staged.to_string());
|
||||
}
|
||||
Ok(successor_stamp(replaced)?.unwrap_or_else(|| staged.to_string()))
|
||||
}
|
||||
|
||||
/// `entry` stamped later than the record the store holds at its key, of any type; unchanged where nothing is held.
|
||||
|
|
@ -4831,10 +4840,6 @@ fn require_stored_at_stamp(entry: &CultCacheEnvelope) -> Result<()> {
|
|||
))
|
||||
}
|
||||
|
||||
fn now_utc_second() -> String {
|
||||
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
|
||||
}
|
||||
|
||||
/// The catalog names each schema id once. An entry the file already holds is arrived, and its type is its schema's name;
|
||||
/// one the caller supplies is registered. Records of one tier under one id are one type. Across tiers a write may not
|
||||
/// retype what the file holds, unless the registered type owns the id (a registered type's id is its entry type): that is
|
||||
|
|
@ -5895,6 +5900,60 @@ mod tests {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn pinned_cache(path: &std::path::Path, at: chrono::DateTime<chrono::Utc>) -> Result<CultCache> {
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<Settings>()?;
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path))?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
cache.set_clock(move || at);
|
||||
Ok(cache)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cache_with_no_set_clock_stamps_near_now() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<Settings>()?;
|
||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(temp.path().join("a.cc")))?;
|
||||
cache.pull_all_backing_stores()?;
|
||||
cache.put("app", &settings_one())?;
|
||||
let stamp = cache.get_required_envelope::<Settings>("app")?.stored_at;
|
||||
let stamped = chrono::DateTime::parse_from_rfc3339(&stamp).unwrap().with_timezone(&chrono::Utc);
|
||||
assert!((chrono::Utc::now() - stamped).num_seconds().abs() < 5, "{stamp}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_replays_with_a_pinned_clock_write_identical_bytes() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let at = chrono::DateTime::parse_from_rfc3339("2026-03-04T05:06:07Z").unwrap().with_timezone(&chrono::Utc);
|
||||
let mut files = Vec::new();
|
||||
for name in ["a.cc", "b.cc"] {
|
||||
let path = temp.path().join(name);
|
||||
let mut cache = pinned_cache(&path, at)?;
|
||||
cache.put("app", &settings_one())?;
|
||||
cache.put("app", &Settings { theme: "blue".to_string(), retries: 2 })?;
|
||||
cache.put("other", &settings_one())?;
|
||||
files.push(std::fs::read(&path)?);
|
||||
}
|
||||
assert_eq!(files[0], files[1]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pinned_clock_still_stamps_a_replacing_write_later() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let at = chrono::DateTime::parse_from_rfc3339("2026-03-04T05:06:07Z").unwrap().with_timezone(&chrono::Utc);
|
||||
let mut cache = pinned_cache(&temp.path().join("a.cc"), at)?;
|
||||
cache.put("app", &settings_one())?;
|
||||
let first = cache.get_required_envelope::<Settings>("app")?.stored_at;
|
||||
assert_eq!(first, "2026-03-04T05:06:07Z");
|
||||
cache.put("app", &Settings { theme: "blue".to_string(), retries: 2 })?;
|
||||
let second = cache.get_required_envelope::<Settings>("app")?.stored_at;
|
||||
assert_eq!(second, "2026-03-04T05:06:07.000001Z");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn settings_one() -> Settings {
|
||||
Settings { theme: "green".to_string(), retries: 1 }
|
||||
}
|
||||
|
|
@ -6538,13 +6597,9 @@ mod tests {
|
|||
}
|
||||
}
|
||||
assert_eq!(stored_at_over("2020-01-01T00:00:00Z", "2099-01-01T00:00:00Z").unwrap(), "2099-01-01T00:00:00.000001Z");
|
||||
// An unparseable stamp on either side is never kept: the minted stamp is the replaced's successor or now.
|
||||
let minted = stored_at_over("not a stamp", "2099-01-01T00:00:00Z").unwrap();
|
||||
assert_eq!(minted, "2099-01-01T00:00:00.000001Z");
|
||||
let minted = stored_at_over("2099-01-01T00:00:00Z", "not a stamp").unwrap();
|
||||
assert!(is_minted_text(&minted));
|
||||
assert!((chrono::Utc::now() - at(&minted).with_timezone(&chrono::Utc)).num_seconds().abs() < 60, "{minted}");
|
||||
assert!(is_minted_text(&mint_stored_at(None, chrono::Utc::now()).unwrap()));
|
||||
// An unparseable staged stamp is never kept: the replaced's successor. An unparseable replaced leaves nothing to be later than.
|
||||
assert_eq!(stored_at_over("not a stamp", "2099-01-01T00:00:00Z").unwrap(), "2099-01-01T00:00:00.000001Z");
|
||||
assert_eq!(stored_at_over("2099-01-01T00:00:00Z", "not a stamp").unwrap(), "2099-01-01T00:00:00Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -7530,7 +7585,7 @@ mod tests {
|
|||
key: "app".to_string(),
|
||||
r#type: "settings".to_string(),
|
||||
payload: vec![0xc1],
|
||||
stored_at: now_utc_second(),
|
||||
stored_at: "2026-01-01T00:00:00Z".to_string(),
|
||||
schema_id: Some("settings".to_string()),
|
||||
})?;
|
||||
|
||||
|
|
@ -7596,7 +7651,7 @@ mod tests {
|
|||
key: "app".to_string(),
|
||||
r#type: Settings::TYPE.to_string(),
|
||||
payload: vec![0xc1],
|
||||
stored_at: now_utc_second(),
|
||||
stored_at: "2026-01-01T00:00:00Z".to_string(),
|
||||
schema_id: Some("dynamic.settings.v1".to_string()),
|
||||
};
|
||||
|
||||
|
|
@ -7620,7 +7675,7 @@ mod tests {
|
|||
key: "note".to_string(),
|
||||
r#type: Note::TYPE.to_string(),
|
||||
payload: Vec::new(),
|
||||
stored_at: now_utc_second(),
|
||||
stored_at: "2026-01-01T00:00:00Z".to_string(),
|
||||
schema_id: Some("dynamic.settings.v1".to_string()),
|
||||
})
|
||||
.is_err()
|
||||
|
|
@ -7632,7 +7687,7 @@ mod tests {
|
|||
key: "foreign".to_string(),
|
||||
r#type: "unregistered".to_string(),
|
||||
payload: Vec::new(),
|
||||
stored_at: now_utc_second(),
|
||||
stored_at: "2026-01-01T00:00:00Z".to_string(),
|
||||
schema_id: None,
|
||||
})
|
||||
.is_err()
|
||||
|
|
@ -7652,7 +7707,7 @@ mod tests {
|
|||
key: "app".to_string(),
|
||||
r#type: Settings::TYPE.to_string(),
|
||||
payload: vec![0x91, 0x01, 0xc0],
|
||||
stored_at: now_utc_second(),
|
||||
stored_at: "2026-01-01T00:00:00Z".to_string(),
|
||||
schema_id: None,
|
||||
};
|
||||
let error = format!("{:#}", cache.put_raw_envelope(tailed.clone()).unwrap_err());
|
||||
|
|
|
|||
Loading…
Reference in a new issue