cultcache-rs: catalog member rows for every member, as C#, TypeScript and Python write (#186)

This commit is contained in:
Eureka 2026-11-27 23:30:21 +00:00
commit 4c9af401ae
10 changed files with 678 additions and 59 deletions

View file

@ -46,6 +46,17 @@ class CatalogMembersVectorTests(unittest.TestCase):
self.assertEqual(envelopes[0].catalog_entry.schema_name, "tests.catalog_members")
self.assertEqual(tuple(envelopes[0].catalog_entry.members), ())
def test_the_rust_written_store_with_member_rows_publishes_every_row_of_the_shared_table(self) -> None:
envelopes = pull("rust-members-store.cc")
self.assertEqual([envelope.key for envelope in envelopes], ["m:1"])
entry = envelopes[0].catalog_entry
self.assertEqual(entry.schema_name, "tests.catalog_members")
rows = [
[m.slot, m.member_name, m.type_name, m.is_reference, m.is_many, m.target_schema_name, m.is_name, m.index_alias]
for m in entry.members
]
self.assertEqual(rows, TABLE)
if __name__ == "__main__":
unittest.main()

View file

@ -8,6 +8,7 @@ only in git history.
### Added
- `CultTypeName`, `SchemaCatalogMember`, `SchemaCatalogEntry::members`, `DatabaseEntry::schema_members`, `CacheBackingStore::describe` (provided, a no-op) and `#[cultcache(type_name = "...")]` on a type or a `DatabaseEntry` field: a Rust-written catalog entry carries a member row (slot, name, C# type name) for every member of a registered type, as C#, TypeScript and Python write. A field type with no name is written `System.Object`. Readers keep reading `members []` stores.
- `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`.
@ -19,6 +20,7 @@ only in git history.
### Changed
- 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)`).
- `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).

View file

@ -353,6 +353,15 @@ marked `default` use `Default::default()` when older payloads are read. Deleted
field slots should stay reserved until an explicit store migration rewrites the
data.
A store this cache writes carries a catalog row for every member of a type the cache has registered: the slot, the member name (the
field's name in PascalCase, as C#, TypeScript and Python spell it) and a C# type name. `CultTypeName` supplies the type name of the
std types (`i32` is `System.Int32`, `Vec<T>` is `System.Collections.Generic.List<T>`, an `Option` of a value type is
`System.Nullable<T>`, a map is `System.Collections.Generic.Dictionary<K, V>`, `serde_bytes::ByteBuf` and a `bytes` field are
`System.Byte[]`). Name your own type with `#[cultcache(type_name = "Ns.Type")]` on a `DatabaseEntry`, `CultSlots` or `CultUnion`, and
override one member with `#[cultcache(key = N, type_name = "System.Guid")]` on a `DatabaseEntry` field. A field type that names
nothing is written `System.Object`. `pull_schema_catalog` returns the rows as `SchemaCatalogEntry::members`. A C# reader refuses a
store whose row differs from its own declaration in type name, name flag or index alias, so annotate the types a C# peer also reads.
The single-file MessagePack store rewrites an atomic snapshot. That is a sane
starting point for small typed state surfaces, settings, Epiphany agent memory,
heartbeat state, and other compact control-plane data. Large corpora should use

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,71 @@ 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}");
}
#[test]
fn a_type_level_attribute_other_than_type_name_is_refused_on_slots_and_unions() {
let message = slots_result(r#"#[cultcache(type = "t")] struct S { #[cultcache(key = 0)] a: String }"#).unwrap_err().to_string();
assert!(message.contains("unsupported cultcache attribute"), "{message}");
let input: DeriveInput = syn::parse_str(r#"#[cultcache(global)] enum U { #[cultcache(key = 0)] A }"#).unwrap();
let message = union_codec(input).unwrap_err().to_string();
assert!(message.contains("unsupported cultcache attribute"), "{message}");
}
#[test]
fn an_explicit_type_name_wins_over_bytes_and_bytes_names_a_byte_array() {
let tokens = entry_tokens(r#"#[cultcache(type = "t")] struct S { #[cultcache(key = 0, bytes, type_name = "Ns.Blob")] a: Vec<u8> }"#);
assert!(tokens.contains("\"Ns.Blob\"") && !tokens.contains("\"System.Byte[]\""), "{tokens}");
let tokens = entry_tokens(r#"#[cultcache(type = "t")] struct S { #[cultcache(key = 0, bytes)] a: Vec<u8> }"#);
assert!(tokens.contains("\"System.Byte[]\""), "{tokens}");
}
}

View file

@ -16,7 +16,7 @@ const INTEROP_SCHEMA_VERSION: &str = "cultcache.interop_note.v1";
struct CultCacheInteropNote {
#[cultcache(key = 0)]
schema_version: String,
#[cultcache(key = 1)]
#[cultcache(key = 1, name)]
document_id: String,
#[cultcache(key = 2)]
author_runtime_id: String,
@ -24,7 +24,7 @@ struct CultCacheInteropNote {
title: String,
#[cultcache(key = 4)]
body: String,
#[cultcache(key = 5, default)]
#[cultcache(key = 5, default, type_name = "System.String[]")]
tags: Vec<String>,
}
@ -35,14 +35,15 @@ struct CultCacheInteropMark(String, String);
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "cultcache.interop-deck", schema = "CultCacheInteropDeck")]
struct CultCacheInteropDeck {
#[cultcache(key = 0)]
#[cultcache(key = 0, name)]
document_id: String,
#[cultcache(key = 1, default)]
#[cultcache(key = 1, default, type_name = "System.Collections.Generic.List<CultCacheInteropMark>")]
marks: Vec<CultCacheInteropMark>,
}
// A union field and nested bytes: the shapes a Bifrost-style store holds beyond plain strings.
#[derive(Clone, Debug, PartialEq, Eq, CultUnion)]
#[cultcache(type_name = "InteropArm")]
enum InteropArm {
#[cultcache(key = 0)]
Text(InteropTextArm),
@ -67,7 +68,7 @@ struct InteropPackArm {
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(type = "cultcache.interop-shape", schema = "CultCacheInteropShape")]
struct CultCacheInteropShape {
#[cultcache(key = 0)]
#[cultcache(key = 0, name)]
document_id: String,
#[cultcache(key = 1)]
arm: InteropArm,

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 and describes (a hand impl describes no rows) 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).filter(|members| !members.is_empty())
{
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(),
@ -8179,6 +8347,163 @@ mod tests {
Ok(())
}
// Member rows: a registered type owns its id and describes it from the type at every write.
fn note_rows() -> Vec<SchemaCatalogMember> {
let row = |slot: u32, name: &str| SchemaCatalogMember {
slot,
member_name: name.into(),
type_name: "System.String".into(),
is_reference: false,
is_many: false,
target_schema_name: None,
is_name: false,
index_alias: None,
};
vec![row(0, "Title"), row(1, "Body")]
}
fn written_catalog(path: &Path) -> Result<Vec<PersistedSchemaCatalogEntry>> {
Ok(decode_store_snapshot(&std::fs::read(path)?)?.1)
}
#[test]
fn the_derive_writes_a_row_for_every_member() {
assert_eq!(Note::schema_members(), note_rows());
}
#[test]
fn an_owned_id_is_described_from_its_registered_type_over_what_the_file_holds() -> Result<()> {
let stale_alias = SchemaCatalogMember { index_alias: Some("stale".into()), ..note_rows().remove(0) };
for held_members in [Vec::new(), vec![stale_alias]] {
let temp = tempfile::tempdir()?;
let path = temp.path().join("store.cc");
let held = PersistedSchemaCatalogEntry(
"note".into(), "note".into(), "note.v1".into(), "note".into(), "{}".into(), vec!["note".into()], held_members,
);
let record = PersistedRecord("carried".into(), "note".into(), "2026-09-30T00:00:00Z".into(), rmp_serde::to_vec(&note_one())?);
std::fs::write(&path, rmp_serde::to_vec(&PersistedStoreSnapshot("cultcache.store.v1".into(), vec![held], vec![record]))?)?;
let mut cache = CultCache::new();
cache.register_entry_type::<Note>()?;
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))?;
cache.pull_all_backing_stores()?;
cache.put("another", &note_one())?;
let catalog = written_catalog(&path)?;
assert_eq!(catalog.len(), 1);
assert_eq!(catalog[0].6, note_rows());
assert_eq!(SchemaCatalogEntry::from(&catalog[0]).members, note_rows());
assert!(catalog[0].4.contains("\"members\":[{\"slot\":0,\"name\":\"Title\",\"type\":\"System.String\""), "{}", catalog[0].4);
}
Ok(())
}
#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct HandWritten {
a: String,
}
impl DatabaseEntry for HandWritten {
const TYPE: &'static str = "handnote";
}
#[test]
fn a_hand_impl_that_describes_no_rows_keeps_the_rows_the_file_holds() -> Result<()> {
let temp = tempfile::tempdir()?;
let path = temp.path().join("store.cc");
let row = note_rows().remove(0);
let held = PersistedSchemaCatalogEntry(
"handnote".into(), "handnote".into(), "handnote.v1".into(), "handnote".into(), "{}".into(), vec!["handnote".into()], vec![row.clone()],
);
let record = PersistedRecord("carried".into(), "handnote".into(), "2026-09-30T00:00:00Z".into(), rmp_serde::to_vec(&HandWritten { a: "x".into() })?);
std::fs::write(&path, rmp_serde::to_vec(&PersistedStoreSnapshot("cultcache.store.v1".into(), vec![held], vec![record]))?)?;
let mut cache = CultCache::new();
cache.register_entry_type::<HandWritten>()?;
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))?;
cache.pull_all_backing_stores()?;
cache.put("another", &HandWritten { a: "y".into() })?;
let catalog = written_catalog(&path)?;
assert_eq!(catalog.len(), 1);
assert_eq!(catalog[0].6, vec![row], "one row before, one row after");
Ok(())
}
#[test]
fn a_type_no_registration_describes_gets_members_empty() -> Result<()> {
let temp = tempfile::tempdir()?;
let path = temp.path().join("store.cc");
let mut store = SingleFileMessagePackBackingStore::new(&path);
store.describe("note", &note_rows());
store.push(&CultCacheEnvelope {
key: "a".into(),
r#type: "tests.other".into(),
payload: b"x".to_vec(),
stored_at: "2026-09-30T00:00:00Z".into(),
schema_id: Some("tests.other".into()),
})?;
let catalog = written_catalog(&path)?;
assert_eq!(catalog.len(), 1);
assert!(catalog[0].6.is_empty());
assert!(catalog[0].4.ends_with("\"members\":[]}"), "{}", catalog[0].4);
Ok(())
}
#[test]
fn describe_reaches_the_store_whichever_of_the_type_and_the_store_comes_first() -> Result<()> {
for type_first in [true, false] {
let temp = tempfile::tempdir()?;
let path = temp.path().join("store.cc");
let mut cache = CultCache::new();
if type_first {
cache.register_entry_type::<Note>()?;
}
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path))?;
if !type_first {
cache.register_entry_type::<Note>()?;
}
cache.pull_all_backing_stores()?;
cache.put("a", &note_one())?;
assert_eq!(written_catalog(&path)?[0].6, note_rows(), "type first: {type_first}");
}
Ok(())
}
#[test]
fn described_canonical_json_members_are_the_ones_csharp_writes() -> Result<()> {
let bytes = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/vectors/catalog-members/csharp-members-store.cc"))?;
let csharp = decode_store_snapshot(&bytes)?.1.remove(0);
assert_eq!(csharp.6.len(), 29);
let ours = described("tests.catalog_members", "tests.catalog_members".into(), &csharp.6);
let members_of = |json: &str| json[json.find("\"members\":").expect("members")..].to_string();
assert_eq!(members_of(&ours.4), members_of(&csharp.4));
assert_eq!(ours.6, csharp.6);
Ok(())
}
#[test]
fn type_names_follow_the_csharp_grammar() {
assert_eq!(<Option<i32>>::cult_type_name(), "System.Nullable<System.Int32>");
assert_eq!(<Option<String>>::cult_type_name(), "System.String");
assert_eq!(<Option<Option<i32>>>::cult_type_name(), "System.Nullable<System.Int32>");
assert_eq!(<Vec<Vec<u8>>>::cult_type_name(), "System.Collections.Generic.List<System.Collections.Generic.List<System.Byte>>");
assert_eq!(<Box<u64>>::cult_type_name(), "System.UInt64");
assert_eq!(<Option<Box<bool>>>::cult_type_name(), "System.Nullable<System.Boolean>");
assert_eq!(
<std::collections::HashMap<String, Vec<f32>>>::cult_type_name(),
"System.Collections.Generic.Dictionary<System.String, System.Collections.Generic.List<System.Single>>"
);
for (name, expected) in [
(char::cult_type_name(), "System.Char"), (i8::cult_type_name(), "System.SByte"), (u8::cult_type_name(), "System.Byte"),
(i16::cult_type_name(), "System.Int16"), (u16::cult_type_name(), "System.UInt16"), (u32::cult_type_name(), "System.UInt32"),
(i64::cult_type_name(), "System.Int64"), (f64::cult_type_name(), "System.Double"),
(serde_bytes::ByteBuf::cult_type_name(), "System.Byte[]"),
] {
assert_eq!(name, expected);
}
use crate::{__NamedType as _, __UnnamedType as _};
struct Nameless;
assert_eq!((&&__TypeNameProbe::<Vec<Nameless>>::new()).__cult_type_name(), "System.Object");
assert_eq!((&&__TypeNameProbe::<Vec<i16>>::new()).__cult_type_name(), "System.Collections.Generic.List<System.Int16>");
}
// Store read and write faults: what a consumer can tell apart, and what a failed
// write leaves on disk.

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");
}

View file

@ -45,3 +45,21 @@ test("the Rust written store publishes members [] for tests.catalog_members and
assert.equal(envelopes[0].catalogEntry?.schemaName, "tests.catalog_members");
assert.deepEqual(envelopes[0].catalogEntry?.members ?? [], []);
});
test("the Rust written store with member rows publishes every row of the shared table and one record m:1", () => {
const { envelopes } = readSingleFileStore(join(vectors, "rust-members-store.cc"));
assert.deepEqual(envelopes.map((envelope) => envelope.key), ["m:1"]);
const entry = envelopes[0].catalogEntry;
assert.equal(entry?.schemaName, "tests.catalog_members");
const rows = (entry?.members ?? []).map((member) => [
member.slot,
member.memberName,
member.typeName,
member.isReference ?? false,
member.isMany ?? false,
member.targetSchemaName ?? null,
member.isName ?? false,
member.indexAlias ?? null,
]);
assert.deepEqual(rows, table);
});

View file

@ -264,5 +264,23 @@ namespace GameCult.Caching.Tests
["defaulted_missing_slot"] = 29,
}));
}
[Test]
public void RustWrittenStoreReadsWithItsRows()
{
// A Rust-written store with member rows loads typed with no refusal. Only the two id/hash drifts remain (the Rust entry's id and
// content hash are the schema name); the members-[] store adds defaulted_missing_slot x29, which the rows remove.
AssertEqualToExpected(ReadM1("rust-members-store.cc", out var reports));
var warnings = reports.SelectMany(report => report.Warnings).GroupBy(warning => warning.Code).ToDictionary(group => group.Key, group => group.Count());
Assert.That(warnings, Is.EquivalentTo(new Dictionary<string, int>
{
["compatible_schema_id_drift"] = 1,
["content_hash_drift"] = 1,
}));
var expected = ExpectedRows();
var actual = CatalogRows("rust-members-store.cc");
Assert.That(actual, Has.Count.EqualTo(expected.Count));
for (var i = 0; i < expected.Count; i++) Assert.That(actual[i], Is.EqualTo(expected[i]), "row " + i);
}
}
}

Binary file not shown.