cultcache-rs: write a catalog member row for every member (CultTypeName, SchemaCatalogMember, describe)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-27 22:47:39 +01:00
commit 6b2bec6172
3 changed files with 440 additions and 54 deletions

View file

@ -23,6 +23,7 @@ fn database_entry_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStr
let mut entry_type: Option<LitStr> = None;
let mut schema_name: Option<LitStr> = None;
let mut global = false;
let mut type_name: Option<LitStr> = None;
for attribute in input
.attrs
@ -38,6 +39,9 @@ fn database_entry_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStr
once(&schema_name, &meta, "schema")?;
schema_name = Some(meta.value()?.parse()?);
Ok(())
} else if meta.path.is_ident("type_name") {
type_name = Some(parse_type_name(&meta, &type_name)?);
Ok(())
} else if meta.path.is_ident("global") {
if global {
return Err(meta.error("repeated `global`: #[cultcache(global)] is given once"));
@ -61,6 +65,8 @@ fn database_entry_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStr
let slots = named_slots(input.data, &ident, "DatabaseEntry")?;
let codec = slot_codec(&ident, &slots);
let type_name_impl = type_name_impl(&ident, type_name.as_ref());
let member_rows = slots.iter().map(member_row);
let name_member = slots.iter().find(|slot| slot.name).map(|slot| &slot.ident);
let name_fn = name_member.map(|member| {
quote! {
@ -88,8 +94,14 @@ fn database_entry_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStr
const GLOBAL: bool = #global;
#unique_indexes
#name_fn
fn schema_members() -> ::std::vec::Vec<::cultcache_rs::SchemaCatalogMember> {
::std::vec![#(#member_rows),*]
}
}
#type_name_impl
#codec
})
}
@ -111,8 +123,11 @@ fn cult_slots_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream>
if !input.generics.params.is_empty() {
return Err(syn::Error::new_spanned(ident, "CultSlots derive does not support generics"));
}
let type_name = type_level_type_name(&input.attrs)?;
let slots = named_slots(input.data, &ident, "CultSlots")?;
Ok(slot_codec(&ident, &slots))
let type_name_impl = type_name_impl(&ident, type_name.as_ref());
let codec = slot_codec(&ident, &slots);
Ok(quote! { #type_name_impl #codec })
}
/// An enum written as `[key, armSlots]`. Every variant carries `#[cultcache(key = N)]`
@ -164,6 +179,7 @@ fn named_slots(data: Data, ident: &syn::Ident, owner: &str) -> syn::Result<Vec<C
let mut bytes = false;
let mut name = false;
let mut index: Option<String> = None;
let mut type_name: Option<LitStr> = None;
for attribute in field
.attrs
.iter()
@ -194,6 +210,9 @@ fn named_slots(data: Data, ident: &syn::Ident, owner: &str) -> syn::Result<Vec<C
}
name = true;
Ok(())
} else if owner == "DatabaseEntry" && meta.path.is_ident("type_name") {
type_name = Some(parse_type_name(&meta, &type_name)?);
Ok(())
} else if owner == "DatabaseEntry" && meta.path.is_ident("index") {
once(&index, &meta, "index")?;
// A bare `index`, or an alias that is blank, names the field itself.
@ -229,6 +248,7 @@ fn named_slots(data: Data, ident: &syn::Ident, owner: &str) -> syn::Result<Vec<C
bytes,
name,
index,
type_name: type_name.map(|literal| literal.value()),
});
}
if let Some(second) = slots.iter().filter(|slot| slot.name).nth(1) {
@ -413,6 +433,96 @@ fn slot_codec(ident: &syn::Ident, slots: &[CultCacheSlot]) -> proc_macro2::Token
}
/// An attribute names each thing once; a second `key = N` would silently win otherwise.
/// `type_name = "..."`, once and not blank: the C# type name a catalog row carries.
fn parse_type_name<T>(meta: &syn::meta::ParseNestedMeta, seen: &Option<T>) -> syn::Result<LitStr> {
once(seen, meta, "type_name")?;
let literal: LitStr = meta.value()?.parse()?;
if literal.value().trim().is_empty() {
return Err(syn::Error::new_spanned(&literal, "#[cultcache(type_name = ...)] is not blank: it names a C# type"));
}
Ok(literal)
}
/// The type-level attributes of a CultSlots struct or CultUnion enum: `type_name` only.
fn type_level_type_name(attrs: &[syn::Attribute]) -> syn::Result<Option<LitStr>> {
let mut type_name: Option<LitStr> = None;
for attribute in attrs.iter().filter(|attr| attr.path().is_ident("cultcache")) {
attribute.parse_nested_meta(|meta| {
if meta.path.is_ident("type_name") {
type_name = Some(parse_type_name(&meta, &type_name)?);
Ok(())
} else {
Err(meta.error("unsupported cultcache attribute"))
}
})?;
}
Ok(type_name)
}
/// `impl CultTypeName` for a type that was given `type_name`; nothing otherwise.
fn type_name_impl(ident: &syn::Ident, type_name: Option<&LitStr>) -> proc_macro2::TokenStream {
match type_name {
Some(name) => quote! {
impl ::cultcache_rs::CultTypeName for #ident {
fn cult_type_name() -> ::std::string::String {
::std::string::String::from(#name)
}
}
},
None => proc_macro2::TokenStream::new(),
}
}
/// The member name C# declares for a Rust field: the ident without `r#`, each `_` part's first letter upper-cased.
fn member_name(ident: &syn::Ident) -> String {
let raw = ident.to_string();
let raw = raw.strip_prefix("r#").unwrap_or(&raw);
raw.split('_')
.map(|part| {
let mut chars = part.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect::<String>(),
None => String::new(),
}
})
.collect()
}
/// One catalog row for a slot: the explicit `type_name`, `System.Byte[]` for `bytes`, else what the field type names.
fn member_row(slot: &CultCacheSlot) -> proc_macro2::TokenStream {
let key = slot.key as u32;
let name = member_name(&slot.ident);
let ty = &slot.ty;
let type_name = if let Some(explicit) = &slot.type_name {
quote! { ::std::string::String::from(#explicit) }
} else if slot.bytes {
quote! { ::std::string::String::from("System.Byte[]") }
} else {
quote! {{
use ::cultcache_rs::__NamedType as _;
use ::cultcache_rs::__UnnamedType as _;
(&&::cultcache_rs::__TypeNameProbe::<#ty>::new()).__cult_type_name()
}}
};
let is_name = slot.name;
let alias = match &slot.index {
Some(alias) => quote! { ::std::option::Option::Some(::std::string::String::from(#alias)) },
None => quote! { ::std::option::Option::None },
};
quote! {
::cultcache_rs::SchemaCatalogMember {
slot: #key,
member_name: ::std::string::String::from(#name),
type_name: #type_name,
is_reference: false,
is_many: false,
target_schema_name: ::std::option::Option::None,
is_name: #is_name,
index_alias: #alias,
}
}
}
fn once<T>(seen: &Option<T>, meta: &syn::meta::ParseNestedMeta, name: &str) -> syn::Result<()> {
if seen.is_some() {
return Err(meta.error(format!("repeated `{name}`: #[cultcache({name} = ...)] is given once")));
@ -448,6 +558,8 @@ struct CultCacheSlot {
/// `#[cultcache(index)]` or `#[cultcache(index = "alias")]`: a unique lookup. Within one type no two records hold one
/// non-blank value of the alias; `get_by_index` finds the record by it.
index: Option<String>,
/// `#[cultcache(type_name = "...")]`: the C# type name this member's catalog row carries.
type_name: Option<String>,
}
fn union_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
@ -458,6 +570,8 @@ fn union_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
"CultUnion derive does not support generics",
));
}
let type_name = type_level_type_name(&input.attrs)?;
let type_name_impl = type_name_impl(&ident, type_name.as_ref());
let Data::Enum(data) = input.data else {
return Err(syn::Error::new_spanned(ident, "CultUnion derive requires an enum"));
};
@ -598,6 +712,8 @@ fn union_codec(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
});
Ok(quote! {
#type_name_impl
const _: () = ::core::assert!(
::core::mem::size_of::<#ident>() <= ::cultcache_rs::MAX_RECORD_INLINE_BYTES,
"a CultCache record is at most cultcache_rs::MAX_RECORD_INLINE_BYTES bytes inline; box its largest slot"
@ -1011,4 +1127,54 @@ mod tests {
assert!(message.contains("unsupported field cultcache attribute"), "{message}");
}
#[test]
fn type_name_is_given_once_and_not_blank() {
for source in [
r#"#[cultcache(type = "t", type_name = "")] struct S { #[cultcache(key = 0)] a: String }"#,
r#"#[cultcache(type = "t", type_name = " ")] struct S { #[cultcache(key = 0)] a: String }"#,
r#"#[cultcache(type = "t")] struct S { #[cultcache(key = 0, type_name = "")] a: String }"#,
] {
let message = entry_error(source);
assert!(message.contains("not blank"), "{source}: {message}");
}
let message = entry_error(r#"#[cultcache(type = "t", type_name = "A", type_name = "B")] struct S { #[cultcache(key = 0)] a: String }"#);
assert!(message.contains("repeated `type_name`"), "{message}");
let message = entry_error(r#"#[cultcache(type = "t")] struct S { #[cultcache(key = 0, type_name = "A", type_name = "B")] a: String }"#);
assert!(message.contains("repeated `type_name`"), "{message}");
}
#[test]
fn a_field_type_name_is_refused_on_a_slots_record() {
let message = slots_error(r#"struct S { #[cultcache(key = 0, type_name = "System.Guid")] a: String }"#);
assert!(message.contains("unsupported field cultcache attribute"), "{message}");
}
#[test]
fn a_type_level_type_name_emits_the_impl_on_every_derive() {
let input: DeriveInput = syn::parse_str(r#"#[cultcache(type_name = "Ns.S")] struct S { #[cultcache(key = 0)] a: String }"#).unwrap();
let tokens = cult_slots_codec(input).unwrap().to_string().replace(' ', "");
assert!(tokens.contains("CultTypeNameforS") && tokens.contains("\"Ns.S\""), "{tokens}");
let input: DeriveInput = syn::parse_str(r#"#[cultcache(type_name = "Ns.U")] enum U { #[cultcache(key = 0)] A }"#).unwrap();
let tokens = union_codec(input).unwrap().to_string().replace(' ', "");
assert!(tokens.contains("CultTypeNameforU") && tokens.contains("\"Ns.U\""), "{tokens}");
let tokens = entry_tokens(r#"#[cultcache(type = "t")] struct S { #[cultcache(key = 0)] a: String }"#);
assert!(!tokens.contains("CultTypeNamefor"), "{tokens}");
}
#[test]
fn member_rows_are_pascal_cased_and_follow_the_attributes() {
let tokens = entry_tokens(
r#"#[cultcache(type = "t")] struct S {
#[cultcache(key = 0, name)] r#type_label: String,
#[cultcache(key = 2, bytes)] raw_bytes: Vec<u8>,
#[cultcache(key = 1, index = "sku", type_name = "System.Guid")] ident: String,
}"#,
);
assert!(tokens.contains("\"TypeLabel\"") && tokens.contains("\"RawBytes\"") && tokens.contains("\"Ident\""), "{tokens}");
assert!(tokens.contains("\"System.Byte[]\"") && tokens.contains("\"System.Guid\""), "{tokens}");
assert!(tokens.find("\"TypeLabel\"").unwrap() < tokens.find("\"Ident\"").unwrap(), "key order: {tokens}");
assert!(tokens.find("\"Ident\"").unwrap() < tokens.find("\"RawBytes\"").unwrap(), "key order: {tokens}");
}
}

View file

@ -173,6 +173,11 @@ pub trait DatabaseEntry: Serialize + DeserializeOwned + Clone + Send + 'static {
/// 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>] = &[];
/// The catalog rows this type publishes, one per member in slot order. The derive writes every member; a hand impl
/// publishes none.
fn schema_members() -> Vec<SchemaCatalogMember> {
Vec::new()
}
}
/// An index alias and how to read its value from a record; `None` is no value.
@ -215,6 +220,107 @@ macro_rules! lookup_value_by_display {
lookup_value_by_display!(char, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);
/// The C# type name a member's catalog row carries (`CultSchemaTypeNames.FromType`). The std types below name themselves; a
/// derived type names itself with `#[cultcache(type_name = "...")]`, and a field whose type names nothing is written
/// `System.Object`. A field's own `#[cultcache(type_name = "...")]` replaces what its type says.
pub trait CultTypeName {
fn cult_type_name() -> String;
/// A C# value type: an `Option` of it is `System.Nullable<..>`, an `Option` of anything else is the type itself.
const VALUE_TYPE: bool = false;
}
macro_rules! type_name_value {
($($ty:ty => $name:literal),* $(,)?) => {$(
impl CultTypeName for $ty {
fn cult_type_name() -> String {
$name.to_string()
}
const VALUE_TYPE: bool = true;
}
)*};
}
type_name_value!(
bool => "System.Boolean", char => "System.Char", i8 => "System.SByte", u8 => "System.Byte", i16 => "System.Int16",
u16 => "System.UInt16", i32 => "System.Int32", u32 => "System.UInt32", i64 => "System.Int64", u64 => "System.UInt64",
f32 => "System.Single", f64 => "System.Double",
);
impl CultTypeName for String {
fn cult_type_name() -> String {
"System.String".to_string()
}
}
impl CultTypeName for serde_bytes::ByteBuf {
fn cult_type_name() -> String {
"System.Byte[]".to_string()
}
}
impl<T: CultTypeName> CultTypeName for Vec<T> {
fn cult_type_name() -> String {
format!("System.Collections.Generic.List<{}>", T::cult_type_name())
}
}
impl<T: CultTypeName> CultTypeName for Option<T> {
fn cult_type_name() -> String {
if T::VALUE_TYPE { format!("System.Nullable<{}>", T::cult_type_name()) } else { T::cult_type_name() }
}
}
impl<T: CultTypeName> CultTypeName for Box<T> {
fn cult_type_name() -> String {
T::cult_type_name()
}
const VALUE_TYPE: bool = T::VALUE_TYPE;
}
impl<K: CultTypeName, V: CultTypeName> CultTypeName for BTreeMap<K, V> {
fn cult_type_name() -> String {
format!("System.Collections.Generic.Dictionary<{}, {}>", K::cult_type_name(), V::cult_type_name())
}
}
impl<K: CultTypeName, V: CultTypeName, S> CultTypeName for std::collections::HashMap<K, V, S> {
fn cult_type_name() -> String {
format!("System.Collections.Generic.Dictionary<{}, {}>", K::cult_type_name(), V::cult_type_name())
}
}
/// The derive's probe: autoref specialization of "this field type names itself, else `System.Object`".
#[doc(hidden)]
pub struct __TypeNameProbe<T>(std::marker::PhantomData<T>);
impl<T> __TypeNameProbe<T> {
pub fn new() -> Self {
Self(std::marker::PhantomData)
}
}
#[doc(hidden)]
pub trait __NamedType {
fn __cult_type_name(&self) -> String;
}
impl<T: CultTypeName> __NamedType for &__TypeNameProbe<T> {
fn __cult_type_name(&self) -> String {
T::cult_type_name()
}
}
#[doc(hidden)]
pub trait __UnnamedType {
fn __cult_type_name(&self) -> String;
}
impl<T> __UnnamedType for __TypeNameProbe<T> {
fn __cult_type_name(&self) -> String {
"System.Object".to_string()
}
}
/// A global type already holds a record under another key; a second would leave `get_global` with two answers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CultCacheSecondGlobal {
@ -477,12 +583,12 @@ struct PersistedSchemaCatalogEntry(
String,
String,
Vec<String>,
Vec<PersistedSchemaCatalogMember>,
Vec<SchemaCatalogMember>,
);
/// One entry of a store file's schema catalog, read-only: the scalar fields every runtime publishes for a schema id. The members and
/// the canonical schema JSON the file also carries are not exposed. `schema_version` is the version string the writer published
/// (C# `CultSchemaCatalogEntry.SchemaVersion`).
/// One entry of a store file's schema catalog, read-only: the fields every runtime publishes for a schema id. The canonical schema
/// JSON the file also carries is not exposed. `schema_version` is the version string the writer published (C#
/// `CultSchemaCatalogEntry.SchemaVersion`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SchemaCatalogEntry {
pub schema_id: String,
@ -490,6 +596,9 @@ pub struct SchemaCatalogEntry {
pub schema_version: String,
pub content_hash: String,
pub compatible_schema_ids: Vec<String>,
/// The rows the writer published, in slot order; `[]` from a writer that published none (old Rust, synthesized TypeScript or
/// Python entries).
pub members: Vec<SchemaCatalogMember>,
}
impl From<&PersistedSchemaCatalogEntry> for SchemaCatalogEntry {
@ -500,6 +609,7 @@ impl From<&PersistedSchemaCatalogEntry> for SchemaCatalogEntry {
schema_version: entry.2.clone(),
content_hash: entry.3.clone(),
compatible_schema_ids: entry.5.clone(),
members: entry.6.clone(),
}
}
}
@ -513,17 +623,19 @@ pub fn resolve_schema_entry<'a>(catalog: &'a [SchemaCatalogEntry], schema_id: &s
.or_else(|| catalog.iter().find(|entry| entry.compatible_schema_ids.iter().any(|id| id == schema_id)))
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
struct PersistedSchemaCatalogMember(
u32,
String,
String,
bool,
bool,
Option<String>,
bool,
Option<String>,
);
/// One member row of a catalog entry, the 8-array C# reads: `slot`, the member's name and C# type name, whether it is a reference
/// (`is_many`: to many) to `target_schema_name`, whether it is the name member, and its unique-index alias.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SchemaCatalogMember {
pub slot: u32,
pub member_name: String,
pub type_name: String,
pub is_reference: bool,
pub is_many: bool,
pub target_schema_name: Option<String>,
pub is_name: bool,
pub index_alias: Option<String>,
}
#[derive(Clone, Debug, serde::Serialize)]
struct PersistedRecord(
@ -999,6 +1111,7 @@ enum HeldFinding {
struct Definition {
schema_name: &'static str,
unread_slots: fn(&[u8]) -> Result<Option<UnreadSlots>>,
members: fn() -> Vec<SchemaCatalogMember>,
}
/// The payload check for an envelope admitted without a typed decode, the one [`decode_payload`]
@ -1413,6 +1526,10 @@ pub enum TryCompareExchangeSnapshotOutcome {
pub trait CacheBackingStore: Send {
fn pull_all(&self) -> Result<Vec<CultCacheEnvelope>>;
/// The member rows a catalog-writing store publishes for the schema id that type owns. A cache hands it the rows of every
/// type registered with it, whichever of the type and the store it learned of first; the default (redb stores, custom
/// stores) publishes none.
fn describe(&mut self, _entry_type: &str, _members: &[SchemaCatalogMember]) {}
/// Writes `entry` and returns the `stored_at` the store wrote: a store that restamps a replacing write reports the stamp it
/// minted, and the cache holds that one.
fn push(&mut self, entry: &CultCacheEnvelope) -> Result<String>;
@ -1482,11 +1599,13 @@ pub trait CacheBackingStore: Send {
pub struct SingleFileMessagePackBackingStore {
path: PathBuf,
last_read: LastRead,
/// What a cache told this store about the types it registered: cache-only, never consulted when reading.
described: BTreeMap<String, Vec<SchemaCatalogMember>>,
}
impl SingleFileMessagePackBackingStore {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into(), last_read: LastRead::default() }
Self { path: path.into(), last_read: LastRead::default(), described: BTreeMap::new() }
}
pub fn path(&self) -> &Path {
@ -1886,7 +2005,7 @@ impl SingleFileMessagePackBackingStore {
// and never overwritten.
let disk = self.read_store_unlocked()?;
let entries = settle_one_record_per_key(entries, &disk)?;
let bytes = encode_store_snapshot(&entries, &disk)
let bytes = encode_store_snapshot(&entries, &disk, &self.described)
.and_then(|snapshot| rmp_serde::to_vec(&snapshot).context("failed to encode MessagePack"))
.map_err(|error| error.context(failed(CultCacheStoreWriteFailedKind::Rejected)))?;
self.replace_unlocked(&bytes)
@ -2154,6 +2273,10 @@ fn unique_batch_ids(
}
impl CacheBackingStore for SingleFileMessagePackBackingStore {
fn describe(&mut self, entry_type: &str, members: &[SchemaCatalogMember]) {
self.described.insert(entry_type.to_string(), members.to_vec());
}
fn pull_all(&self) -> Result<Vec<CultCacheEnvelope>> {
if is_absent(&self.path)? && is_absent(&self.lock_path())? {
self.last_read.set_all(&[]);
@ -3528,7 +3651,16 @@ impl CultCache {
}
}
}
self.definitions.insert(T::TYPE.to_string(), Definition { schema_name: T::SCHEMA_NAME, unread_slots: unread_slots_of::<T> });
self.definitions.insert(T::TYPE.to_string(), Definition {
schema_name: T::SCHEMA_NAME,
unread_slots: unread_slots_of::<T>,
members: T::schema_members,
},
);
let members = T::schema_members();
for registration in &mut self.stores {
registration.store.describe(T::TYPE, &members);
}
self.schema_name_definitions
.insert(T::SCHEMA_NAME.to_string(), T::TYPE.to_string());
Ok(())
@ -3570,10 +3702,11 @@ impl CultCache {
claimed
));
}
self.stores.push(CultCacheStoreRegistration {
store: Box::new(store),
types,
});
let mut store: Box<dyn CacheBackingStore> = Box::new(store);
for (entry_type, definition) in &self.definitions {
store.describe(entry_type, &(definition.members)());
}
self.stores.push(CultCacheStoreRegistration { store, types });
let loaded_before = self.load.clone();
if self.load == LoadState::Pulled {
self.load = LoadState::Unpulled;
@ -4706,7 +4839,11 @@ fn now_utc_second() -> String {
/// 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
/// a rename under a stable id, and the registered type names the id.
fn encode_store_snapshot(entries: &[CultCacheEnvelope], disk: &DiskStore) -> Result<PersistedStoreSnapshot> {
fn encode_store_snapshot(
entries: &[CultCacheEnvelope],
disk: &DiskStore,
described_types: &BTreeMap<String, Vec<SchemaCatalogMember>>,
) -> Result<PersistedStoreSnapshot> {
let arrived: BTreeMap<(String, String), &CultCacheEnvelope> = disk.envelopes.iter().map(|entry| (entry_id(entry), entry)).collect();
// Per schema id and tier: the type its records carry, and the key of the record that named it.
let mut schema_types = BTreeMap::<(String, bool), (String, String)>::new();
@ -4744,9 +4881,10 @@ fn encode_store_snapshot(entries: &[CultCacheEnvelope], disk: &DiskStore) -> Res
}));
}
}
// An entry the file holds for an id is written back as the file holds it: this runtime keeps no description of another
// runtime's schema, so it never replaces one. It describes an id itself only when the file has no entry for it, or when a
// registered type owns the id under another name (a rename, where the registered type names the id).
// An id a registered type owns is described from that type at every write, whatever the file holds. An entry the file holds for
// any other id is written back as the file holds it: this runtime keeps no description of another runtime's schema, so it
// never replaces one. It describes such an id itself only when the file has no entry for it, or when a registered type owns
// the id under another name (a rename, where the registered type names the id).
let owned: BTreeSet<&str> = entries
.iter()
.filter(|entry| entry.schema_id.as_deref().is_none_or(|schema_id| schema_id == entry.r#type))
@ -4754,6 +4892,13 @@ fn encode_store_snapshot(entries: &[CultCacheEnvelope], disk: &DiskStore) -> Res
.collect();
let mut catalog = BTreeMap::<String, PersistedSchemaCatalogEntry>::new();
for (schema_id, document_type) in named {
if schema_id == document_type
&& let Some(members) = described_types.get(&schema_id)
{
let entry = described(&schema_id, document_type, members);
catalog.entry(entry.0.clone()).or_insert(entry);
continue;
}
let held = disk
.catalog
.iter()
@ -4762,7 +4907,7 @@ fn encode_store_snapshot(entries: &[CultCacheEnvelope], disk: &DiskStore) -> Res
.filter(|entry| !owned.contains(schema_id.as_str()) || entry.1 == document_type);
let entry = match held {
Some(entry) => entry.clone(),
None => described(&schema_id, document_type),
None => described(&schema_id, document_type, &[]),
};
catalog.entry(entry.0.clone()).or_insert(entry);
}
@ -4788,20 +4933,43 @@ fn encode_store_snapshot(entries: &[CultCacheEnvelope], disk: &DiskStore) -> Res
))
}
/// The entry this runtime writes for a schema id it describes itself: its entry type is the id and the schema's name.
fn described(schema_id: &str, document_type: String) -> PersistedSchemaCatalogEntry {
/// The entry this runtime writes for a schema id it describes itself: its entry type is the id and the schema's name, and its
/// rows are the ones a registered type published (none for a type no registration describes). The canonical JSON spells them in
/// C#'s grammar and key order.
fn described(schema_id: &str, document_type: String, members: &[SchemaCatalogMember]) -> PersistedSchemaCatalogEntry {
let member_json = members
.iter()
.map(|member| {
let optional = |value: &Option<String>| match value {
Some(text) => format!("\"{}\"", escape_json_string(text)),
None => "null".to_string(),
};
format!(
"{{\"slot\":{},\"name\":\"{}\",\"type\":\"{}\",\"isReference\":{},\"many\":{},\"targetSchemaName\":{},\"indexAlias\":{},\"isName\":{}}}",
member.slot,
escape_json_string(&member.member_name),
escape_json_string(&member.type_name),
member.is_reference,
member.is_many,
optional(&member.target_schema_name),
optional(&member.index_alias),
member.is_name,
)
})
.collect::<Vec<_>>()
.join(",");
PersistedSchemaCatalogEntry(
schema_id.to_string(),
document_type,
format!("{schema_id}.v1"),
schema_id.to_string(),
format!(
"{{\"schemaName\":\"{}\",\"schemaVersion\":\"{}.v1\",\"members\":[]}}",
"{{\"schemaName\":\"{}\",\"schemaVersion\":\"{}.v1\",\"members\":[{member_json}]}}",
escape_json_string(schema_id),
escape_json_string(schema_id)
),
vec![schema_id.to_string()],
Vec::new(),
members.to_vec(),
)
}
@ -8131,7 +8299,7 @@ mod tests {
"sha256:content".into(),
"{\"schemaName\":\"tests.note\"}".into(),
vec!["sha256:csharp".into()],
vec![PersistedSchemaCatalogMember(0, "Title".into(), "System.String".into(), false, false, None, true, Some("title".into()))],
vec![SchemaCatalogMember { slot: 0, member_name: "Title".into(), type_name: "System.String".into(), is_reference: false, is_many: false, target_schema_name: None, is_name: true, index_alias: Some("title".into()) }],
);
let own = CultCacheEnvelope {
key: "b".into(),

View file

@ -1,14 +1,16 @@
//! `tests/vectors/catalog-members`: a record that holds a value in every member shape, in the two stores the vector folder
//! `tests/vectors/catalog-members`: a record that holds a value in every member shape, in the three stores the vector folder
//! holds. `csharp-members-store.cc` is written by the C# reference and publishes one catalog row per member;
//! `rust-members-empty-store.cc` is written by this runtime as it stood at e503edf2, whose catalog entry holds `members []`.
//! Rust writes the second only under `CULTCACHE_WRITE_VECTORS=1` and it is never regenerated: it pins the bytes old Rust
//! wrote, so a runtime that reads a store with no member rows keeps reading one. Both stores must read back the same record.
//! `rust-members-empty-store.cc` was written by this runtime as it stood at e503edf2, whose catalog entry holds `members []`: it
//! is never regenerated, so a runtime that reads a store with no member rows keeps reading one. `rust-members-store.cc` is
//! written by this runtime under `CULTCACHE_WRITE_VECTORS=1` and compared (catalog entry bytes, not record stamps) on every other
//! run. All three must read back the same record.
use std::path::PathBuf;
use cultcache_rs::{CultCache, CultSlots, CultUnion, DatabaseEntry, SingleFileMessagePackBackingStore};
#[derive(Clone, Debug, PartialEq, CultSlots)]
#[cultcache(type_name = "GameCult.Caching.Tests.CatalogMemberMark")]
struct CatalogMemberMark {
#[cultcache(key = 0)]
label: String,
@ -35,6 +37,7 @@ struct CatalogMemberCountArm {
}
#[derive(Clone, Debug, PartialEq, CultUnion)]
#[cultcache(type_name = "GameCult.Caching.Tests.CatalogMemberArm")]
enum CatalogMemberArm {
#[cultcache(key = 0)]
Text(CatalogMemberTextArm),
@ -72,7 +75,7 @@ impl<'de> serde::Deserialize<'de> for Timestamp {
}
}
/// A field type that names no C# type: no `type_name` attribute, so the row the library cut writes for it is `System.Object`.
/// A field type that names no C# type: no `type_name` attribute, so its row is `System.Object`.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
struct Opaque(String);
@ -100,7 +103,7 @@ struct CatalogMembers {
note: Option<String>,
#[cultcache(key = 9)]
tags: Vec<String>,
#[cultcache(key = 10)]
#[cultcache(key = 10, type_name = "System.String[]")]
labels: Vec<String>,
#[cultcache(key = 11, bytes)]
raw: Vec<u8>,
@ -116,7 +119,7 @@ struct CatalogMembers {
late: i64,
#[cultcache(key = 18)]
items: Vec<CatalogMemberMark>,
#[cultcache(key = 19)]
#[cultcache(key = 19, type_name = "GameCult.Caching.Tests.CatalogMemberMark[]")]
marks: Vec<CatalogMemberMark>,
#[cultcache(key = 20)]
by_label: std::collections::BTreeMap<String, CatalogMemberMark>,
@ -128,13 +131,13 @@ struct CatalogMembers {
grid: Vec<Vec<i32>>,
#[cultcache(key = 24)]
by_number: std::collections::BTreeMap<i32, String>,
#[cultcache(key = 25)]
#[cultcache(key = 25, type_name = "GameCult.Caching.Tests.CatalogMemberKind")]
kind: i32,
#[cultcache(key = 26)]
#[cultcache(key = 26, type_name = "System.Guid")]
ident: String,
#[cultcache(key = 27)]
#[cultcache(key = 27, type_name = "System.DateTime")]
when: Timestamp,
#[cultcache(key = 28)]
#[cultcache(key = 28, type_name = "System.Decimal")]
price: String,
#[cultcache(key = 29)]
opaque: Opaque,
@ -200,16 +203,6 @@ fn read_from(path: &std::path::Path) -> CatalogMembers {
#[test]
fn the_members_empty_store_vector() {
let path = vectors().join("rust-members-empty-store.cc");
if std::env::var("CULTCACHE_WRITE_VECTORS").as_deref() == Ok("1") {
std::fs::create_dir_all(vectors()).unwrap();
let _ = std::fs::remove_file(&path);
let mut cache = CultCache::new();
cache.register_entry_type::<CatalogMembers>().unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
cache.pull_all_backing_stores().unwrap();
cache.put("m:1", &expected()).unwrap();
return;
}
assert_eq!(read_from(&path), expected());
}
@ -246,3 +239,62 @@ fn the_csharp_catalog_holds_every_row_of_the_shared_table() {
fn the_rust_written_catalog_holds_no_rows() {
assert!(catalog_rows("rust-members-empty-store.cc").is_empty());
}
/// The store this runtime writes for `expected()`: under `CULTCACHE_WRITE_VECTORS=1` it is the vector; otherwise a copy in a
/// temporary folder, so the test compares what this runtime writes now.
fn write_rust_store(path: &std::path::Path) {
let _ = std::fs::remove_file(path);
let mut cache = CultCache::new();
cache.register_entry_type::<CatalogMembers>().unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
cache.pull_all_backing_stores().unwrap();
cache.put("m:1", &expected()).unwrap();
}
fn catalog_entries(path: &std::path::Path) -> Vec<Entry> {
let bytes = std::fs::read(path).unwrap();
let (_header, catalog, _records): (String, Vec<Entry>, serde::de::IgnoredAny) = rmp_serde::from_slice(&bytes).unwrap();
catalog
}
#[test]
fn the_rust_written_store_vector() {
let vector = vectors().join("rust-members-store.cc");
if std::env::var("CULTCACHE_WRITE_VECTORS").as_deref() == Ok("1") {
write_rust_store(&vector);
return;
}
let dir = tempfile::tempdir().unwrap();
let written = dir.path().join("store.cc");
write_rust_store(&written);
assert_eq!(catalog_entries(&written), catalog_entries(&vector), "the catalog entry this runtime writes is the vector's");
assert_eq!(read_from(&vector), expected());
}
#[test]
fn rust_rows_equal_csharp_rows() {
let csharp = catalog_rows("csharp-members-store.cc");
let rust = catalog_rows("rust-members-store.cc");
assert_eq!(rust.len(), 29);
for (index, (row, expected)) in rust.iter().zip(&csharp).enumerate() {
assert_eq!(row, expected, "row {index}");
}
assert_eq!(rust.len(), csharp.len());
}
#[test]
fn a_rust_cache_reports_the_rows_it_wrote() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("store.cc");
write_rust_store(&path);
let rows: Vec<cultcache_rs::SchemaCatalogMember> = SingleFileMessagePackBackingStore::new(&path)
.pull_schema_catalog()
.unwrap()
.remove(0)
.members;
assert_eq!(rows.len(), 29);
assert_eq!(rows[0].member_name, "Title");
assert!(rows[0].is_name);
assert_eq!(rows[1].index_alias.as_deref(), Some("sku"));
assert_eq!(rows[28].type_name, "System.Object");
}