cultcache-rs: re-registration re-derives holders over held records (or refuses); one index declaration (UNIQUE_INDEXES members) replaces cult_indexes; delete projects before the store delete; pins for re-pull and re-registration
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b52786ba69
commit
4f730119ee
3 changed files with 113 additions and 42 deletions
|
|
@ -70,26 +70,15 @@ fn database_entry_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStr
|
|||
}
|
||||
});
|
||||
let index_members: Vec<_> = slots.iter().filter_map(|slot| slot.index.as_ref().map(|alias| (alias, &slot.ident))).collect();
|
||||
let index_aliases: Vec<_> = index_members.iter().map(|(alias, _)| *alias).collect();
|
||||
let index_pushes = index_members.iter().map(|(alias, member)| {
|
||||
let index_rows = index_members.iter().map(|(alias, member)| {
|
||||
quote! {
|
||||
if let ::std::option::Option::Some(value) = ::cultcache_rs::CultLookupValue::lookup_value(&self.#member) {
|
||||
held.push((#alias, value));
|
||||
}
|
||||
(#alias, (|record: &Self| ::cultcache_rs::CultLookupValue::lookup_value(&record.#member))
|
||||
as fn(&Self) -> ::std::option::Option<::std::string::String>)
|
||||
}
|
||||
});
|
||||
let index_pushes: Vec<_> = index_pushes.collect();
|
||||
let unique_indexes = (!index_aliases.is_empty()).then(|| {
|
||||
quote! { const UNIQUE_INDEXES: &'static [&'static str] = &[#(#index_aliases),*]; }
|
||||
});
|
||||
let indexes_fn = (!index_pushes.is_empty()).then(|| {
|
||||
quote! {
|
||||
fn cult_indexes(&self) -> ::std::vec::Vec<(&'static str, ::std::string::String)> {
|
||||
let mut held = ::std::vec::Vec::new();
|
||||
#(#index_pushes)*
|
||||
held
|
||||
}
|
||||
}
|
||||
let index_rows: Vec<_> = index_rows.collect();
|
||||
let unique_indexes = (!index_rows.is_empty()).then(|| {
|
||||
quote! { const UNIQUE_INDEXES: &'static [::cultcache_rs::CultIndexMember<Self>] = &[#(#index_rows),*]; }
|
||||
});
|
||||
|
||||
Ok(quote! {
|
||||
|
|
@ -99,7 +88,6 @@ fn database_entry_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStr
|
|||
const GLOBAL: bool = #global;
|
||||
#unique_indexes
|
||||
#name_fn
|
||||
#indexes_fn
|
||||
}
|
||||
|
||||
#codec
|
||||
|
|
@ -947,15 +935,15 @@ mod tests {
|
|||
);
|
||||
assert!(tokens.contains("constGLOBAL:bool=true"), "{tokens}");
|
||||
assert!(tokens.contains("fncult_name"), "{tokens}");
|
||||
assert!(tokens.contains("(\"code\",value)"), "{tokens}");
|
||||
assert!(tokens.contains("(\"sku\",value)"), "{tokens}");
|
||||
assert!(tokens.contains("(\"code\","), "{tokens}");
|
||||
assert!(tokens.contains("(\"sku\","), "{tokens}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_without_lookups_generates_none_of_them() {
|
||||
let tokens = entry_tokens(r#"#[cultcache(type = "t")] struct S { #[cultcache(key = 0)] a: String }"#);
|
||||
assert!(tokens.contains("constGLOBAL:bool=false"), "{tokens}");
|
||||
assert!(!tokens.contains("fncult_name") && !tokens.contains("fncult_indexes"), "{tokens}");
|
||||
assert!(!tokens.contains("fncult_name") && !tokens.contains("UNIQUE_INDEXES"), "{tokens}");
|
||||
}
|
||||
|
||||
// ResolveIndexAlias: a blank alias is the member's name.
|
||||
|
|
@ -964,7 +952,7 @@ mod tests {
|
|||
let tokens = entry_tokens(
|
||||
r#"#[cultcache(type = "t")] struct S { #[cultcache(key = 0, index = " ")] code: String }"#,
|
||||
);
|
||||
assert!(tokens.contains("(\"code\",value)"), "{tokens}");
|
||||
assert!(tokens.contains("(\"code\","), "{tokens}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -168,15 +168,14 @@ pub trait DatabaseEntry: Serialize + DeserializeOwned + Clone + Send + 'static {
|
|||
fn cult_name(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
/// The `#[cultcache(index)]` aliases. Each is unique: within one type no two records hold one non-blank value of it.
|
||||
const UNIQUE_INDEXES: &'static [&'static str] = &[];
|
||||
/// Each `#[cultcache(index)]` member as (alias, value): a unique lookup, so a non-blank value names one record of
|
||||
/// the type, which `get_by_index` finds it by.
|
||||
fn cult_indexes(&self) -> Vec<(&'static str, String)> {
|
||||
Vec::new()
|
||||
}
|
||||
/// The `#[cultcache(index)]` members, the one declaration: each is an alias with the reader of its value. Each is
|
||||
/// unique: within one type no two records hold one non-blank value of it, and `get_by_index` finds the record by it.
|
||||
const UNIQUE_INDEXES: &'static [CultIndexMember<Self>] = &[];
|
||||
}
|
||||
|
||||
/// An index alias and how to read its value from a record; `None` is no value.
|
||||
pub type CultIndexMember<T> = (&'static str, fn(&T) -> Option<String>);
|
||||
|
||||
/// What a `#[cultcache(name)]` or `#[cultcache(index)]` member says it is called: its text, or `None` for a member
|
||||
/// that holds no value (an `Option` that is `None`). The cache treats an empty name and a blank index value as none.
|
||||
pub trait CultLookupValue {
|
||||
|
|
@ -2743,9 +2742,12 @@ type IndexSlot = (String, String, String);
|
|||
type IndexHolders = BTreeMap<IndexSlot, String>;
|
||||
|
||||
fn project_indexes<T: DatabaseEntry>(payload: &[u8]) -> Result<Vec<(&'static str, String)>> {
|
||||
let mut held = decode_payload::<T>(payload)?.cult_indexes();
|
||||
held.retain(|(_, value)| !value.trim().is_empty());
|
||||
Ok(held)
|
||||
let document = decode_payload::<T>(payload)?;
|
||||
Ok(T::UNIQUE_INDEXES
|
||||
.iter()
|
||||
.filter_map(|(alias, read)| read(&document).map(|value| (*alias, value)))
|
||||
.filter(|(_, value)| !value.trim().is_empty())
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// What an admission does to the holder map: slots it releases (still held by the key that held them) and slots it takes.
|
||||
|
|
@ -2802,17 +2804,33 @@ impl CultCache {
|
|||
existing_type
|
||||
));
|
||||
}
|
||||
// The projector decides what the held records hold, so a changed declaration re-derives the holder table over
|
||||
// them; a held violation (or a record the new type cannot decode) refuses the registration and changes nothing.
|
||||
let previous = self.projectors.get(T::TYPE).copied();
|
||||
if T::UNIQUE_INDEXES.is_empty() {
|
||||
self.projectors.remove(T::TYPE);
|
||||
} else {
|
||||
self.projectors.insert(T::TYPE.to_string(), project_indexes::<T>);
|
||||
}
|
||||
let held_type = self.entries.range((T::TYPE.to_string(), String::new())..).next().is_some_and(|((held, _), _)| held == T::TYPE);
|
||||
if held_type {
|
||||
match self.judge_image(&self.entries) {
|
||||
Ok(holders) => self.index_holders = holders,
|
||||
Err(refusal) => {
|
||||
match previous {
|
||||
Some(project) => self.projectors.insert(T::TYPE.to_string(), project),
|
||||
None => self.projectors.remove(T::TYPE),
|
||||
};
|
||||
return Err(refusal);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.definitions.insert(T::TYPE.to_string(), T::SCHEMA_NAME);
|
||||
if T::GLOBAL {
|
||||
self.globals.insert(T::TYPE.to_string());
|
||||
} else {
|
||||
self.globals.remove(T::TYPE);
|
||||
}
|
||||
if T::UNIQUE_INDEXES.is_empty() {
|
||||
self.projectors.remove(T::TYPE);
|
||||
} else {
|
||||
self.projectors.insert(T::TYPE.to_string(), project_indexes::<T>);
|
||||
}
|
||||
self.schema_name_definitions
|
||||
.insert(T::SCHEMA_NAME.to_string(), T::TYPE.to_string());
|
||||
Ok(())
|
||||
|
|
@ -3030,7 +3048,7 @@ impl CultCache {
|
|||
/// blank value is not indexed, so it finds nothing; neither does an alias `T` does not declare.
|
||||
pub fn get_by_index<T: DatabaseEntry>(&self, alias: &str, value: &str) -> Result<Option<T>> {
|
||||
self.require_entry_type::<T>()?;
|
||||
if value.trim().is_empty() || !T::UNIQUE_INDEXES.contains(&alias) {
|
||||
if value.trim().is_empty() || !T::UNIQUE_INDEXES.iter().any(|(declared, _)| *declared == alias) {
|
||||
return Ok(None);
|
||||
}
|
||||
let slot = (T::TYPE.to_string(), alias.to_string(), value.to_string());
|
||||
|
|
@ -3306,10 +3324,10 @@ impl CultCache {
|
|||
let Some(entry) = self.entries.get(&id).cloned() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let released = self.projected_slots(&entry)?;
|
||||
if let Some(home) = self.home_index(T::TYPE)? {
|
||||
self.stores[home].store.delete(&entry)?;
|
||||
}
|
||||
let released = self.projected_slots(&entry)?;
|
||||
self.entries.remove(&id);
|
||||
IndexChange { released, taken: Vec::new() }.apply(&mut self.index_holders);
|
||||
Ok(true)
|
||||
|
|
|
|||
|
|
@ -129,9 +129,12 @@ fn skus(cache: &CultCache) -> Vec<(String, String)> {
|
|||
|
||||
#[test]
|
||||
fn the_derive_emits_the_unique_aliases() {
|
||||
assert_eq!(Unique::UNIQUE_INDEXES, &["Sku"]);
|
||||
assert_eq!(Multi::UNIQUE_INDEXES, &["B", "A"]);
|
||||
assert!(Plain::UNIQUE_INDEXES.is_empty());
|
||||
fn aliases<T: DatabaseEntry>() -> Vec<&'static str> {
|
||||
T::UNIQUE_INDEXES.iter().map(|(alias, _)| *alias).collect()
|
||||
}
|
||||
assert_eq!(aliases::<Unique>(), ["Sku"]);
|
||||
assert_eq!(aliases::<Multi>(), ["B", "A"]);
|
||||
assert!(aliases::<Plain>().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -557,3 +560,65 @@ fn vectors_stores_hold_their_verdicts() {
|
|||
assert_eq!(std::fs::read(&path).unwrap(), before, "{file} is byte-identical");
|
||||
}
|
||||
}
|
||||
|
||||
// A pull replaces the holder table with the stored image's: a value another writer changed is released, not kept.
|
||||
#[test]
|
||||
fn a_second_pull_replaces_the_holders_with_the_stored_image() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("pull.cc");
|
||||
let mut cache = cache_at(&path);
|
||||
cache.put("a", &unique("S")).unwrap();
|
||||
|
||||
cache_at(&path).put("a", &unique("T")).unwrap();
|
||||
cache.pull_all_backing_stores().unwrap();
|
||||
|
||||
assert_eq!(cache.get_by_index::<Unique>("Sku", "S").unwrap(), None, "the replaced value is no longer held");
|
||||
assert_eq!(cache.get_by_index::<Unique>("Sku", "T").unwrap(), cache.get::<Unique>("a").unwrap());
|
||||
cache.put("b", &unique("S")).unwrap();
|
||||
assert!(cache.put("c", &unique("T")).is_err());
|
||||
}
|
||||
|
||||
// The projector decides what held records hold: declaring an index for a type that already has records derives
|
||||
// their holders, or refuses the registration when they collide.
|
||||
#[test]
|
||||
fn registering_an_index_over_held_records_derives_their_holders() {
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<Twin>().unwrap();
|
||||
cache.put("a", &Twin { sku: "S".into(), category: "x".into() }).unwrap();
|
||||
cache.put("b", &Twin { sku: "T".into(), category: "x".into() }).unwrap();
|
||||
|
||||
cache.register_entry_type::<Unique>().unwrap();
|
||||
|
||||
assert_eq!(cache.get_by_index::<Unique>("Sku", "S").unwrap(), cache.get::<Unique>("a").unwrap());
|
||||
assert!(cache.get_by_index::<Unique>("Sku", "S").unwrap().is_some());
|
||||
assert!(cache.put("c", &unique("S")).is_err(), "a held value is refused");
|
||||
cache.put("c", &unique("U")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registering_an_index_over_colliding_held_records_is_refused_and_changes_nothing() {
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<Twin>().unwrap();
|
||||
cache.put("a", &Twin { sku: "S".into(), category: "x".into() }).unwrap();
|
||||
cache.put("b", &Twin { sku: "S".into(), category: "y".into() }).unwrap();
|
||||
|
||||
let text = error_text(cache.register_entry_type::<Unique>());
|
||||
assert_eq!(text, refusal("a", "b", "tests.unique_item", "Sku"));
|
||||
|
||||
// Still the unindexed declaration: duplicates keep landing, nothing is looked up.
|
||||
cache.put("c", &Twin { sku: "S".into(), category: "z".into() }).unwrap();
|
||||
assert_eq!(cache.get_all_with_keys::<Twin>().unwrap().len(), 3);
|
||||
assert_eq!(cache.get_by_index::<Unique>("Sku", "S").unwrap(), None);
|
||||
}
|
||||
|
||||
// Dropping the declaration releases the holders.
|
||||
#[test]
|
||||
fn registering_without_the_index_releases_the_holders() {
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<Unique>().unwrap();
|
||||
cache.put("a", &unique("S")).unwrap();
|
||||
cache.register_entry_type::<Twin>().unwrap();
|
||||
assert_eq!(cache.get_by_index::<Unique>("Sku", "S").unwrap(), None, "no declaration, no 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");
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue