From b960186360ef55dc4ffe6bfa1e44d9e41b9d6a0b Mon Sep 17 00:00:00 2001 From: Libby Date: Thu, 12 Nov 2026 03:09:12 +0000 Subject: [PATCH] cultcache-rs: a record whose payload carries unread slots is read-only; every write or removal of it is refused The derives' slot visitors count the slots past the declared ones and note them into a scope the decode entry opens, instead of skipping them silently; a unit arm with slots decodes and marks. Every write entry asks one check over the held envelope, decoded under the mark, and refuses with SchemaConflictError.unread_slots before any store is touched. Breaking for struct-literal construction of SchemaConflictError (0.3.x to 0.4.0). Co-Authored-By: Claude Sonnet 5.5 --- packages/cultcache-rs/CHANGELOG.md | 7 + packages/cultcache-rs/README.md | 11 + .../cultcache-rs-derive/src/lib.rs | 18 +- packages/cultcache-rs/src/lib.rs | 213 ++++++++++- packages/cultcache-rs/tests/common/mod.rs | 235 ++++++++++++ packages/cultcache-rs/tests/slot_readonly.rs | 350 ++++++++++++++++++ packages/cultcache-rs/tests/union_parity.rs | 234 +----------- packages/cultnet-rs/src/replication.rs | 1 + 8 files changed, 828 insertions(+), 241 deletions(-) create mode 100644 packages/cultcache-rs/tests/common/mod.rs create mode 100644 packages/cultcache-rs/tests/slot_readonly.rs diff --git a/packages/cultcache-rs/CHANGELOG.md b/packages/cultcache-rs/CHANGELOG.md index ed7cd60a..e32c12c1 100644 --- a/packages/cultcache-rs/CHANGELOG.md +++ b/packages/cultcache-rs/CHANGELOG.md @@ -8,6 +8,12 @@ only in git history. ### Breaking +Semver: this is a breaking change in the 0.x line (0.3.x to 0.4.0). + +- A record whose payload carries unread slots is read-only. A payload with a slot past its type's declared slots, at any depth (record, nested record, list element, union arm, unit arm), still decodes, and every write or removal of its key is now refused before any store is touched: `put`, `put_envelope`, `put_raw_envelope`, `put_prepared_batch` (the whole batch) and `delete`, so `update` too. The refusal is `SchemaConflictError` with the new `unread_slots`; its message names the type and both slot counts and never a slot value. Holders of such a record used to overwrite it and drop the extra slots silently. The payload nesting refusal still runs first. A held payload the registered type cannot decode at all is not judged, and stays replaceable and removable. +- `SchemaConflictError` gains the public field `unread_slots: Option`; code that builds it with a struct literal must set it (`None`). +- A unit arm with slots (`[N, [extra...]]`) decodes as the unit arm and marks the record, where the derive refused it. +- The registration map's value changes from the schema name to a private struct holding the schema name and the unread-slots check. - A single-file store written as `cultcache.store.v3` is read and written: a store the C# runtime marked v3 (it holds a record with an element id: an owned list element with a `[CultElementId]` member) keeps its header here, and is carried through every rewrite with its ids; this runtime never drops the mark. A runtime from before this change refuses a v3 store by name. Rolling back to an older release after a store has been written as v3 is one-way: there is no carry-back, so restore from a copy taken before upgrading. - A write over a file the reader refuses (a zero-byte file, a truncated store, a stamp this runtime does not read) refuses with `CultCacheStoreUnreadable` and leaves the file as it is. A whole-store write used to replace such a file. This reverses 0.3.1, where `push_all` replaced a file with no readable stamp (healing it); the stamp rule now has one owner, the reader every write asks under the lock, and it accepts v1 and v3 (0.3.1 refused v3). - `#[cultcache(index)]` means unique, as in C# `RefuseIndexSharing`: within one type and one alias no two records hold one non-blank value. A put, batch, push or load that would make two records hold a value is refused, naming both keys and the alias, and a store that already holds a duplicate does not open. A grouping index is no longer expressible; a consumer that relied on shared values must drop the `index` and look up by another way. @@ -22,6 +28,7 @@ only in git history. ### Added +- `UnreadSlots { type_name, slot_count, declared_count, occurrences }`, `decode_payload_marked` (the decode that returns the mark) and `CultCache::is_writable(type, key)`. The derives' slot visitors note into a thread-local scope the decode entry opens (`__enter_slots`, `__note_unread_slots`, `__UnitArmSlots`, doc-hidden); a decode outside that entry notes nothing. - `CultCache::foreign_records()` and `ForeignRecord { key, schema_id, schema_name, stored_at }`: the records the last pull found that no registered type claims, sorted by key. - Lookups, matching the C# `GetByName`, `GetByIndex` and `GetGlobal`. `#[cultcache(name)]` and `#[cultcache(index)]` / `#[cultcache(index = "alias")]` on `DatabaseEntry` fields and `#[cultcache(global)]` on the struct give `CultCache::get_by_name`, `get_by_index` and `get_global`. An empty name and a blank index value are not found; records of one type sharing a name find the one with the smallest key (an index value is unique, below). A second record of a global type under another key is refused on every write path and on load with `CultCacheSecondGlobal`. Two `name` members, or two members with one index alias, are refused at compile time. A member's text comes from `CultLookupValue` (`String`, `Option` of one, integers, `bool`, `char`). - `SchemaConflictError`, the typed refusal of a write the catalog cannot describe: records of different types under one schema id, or an arrived schema and a registered one that share an id and disagree on the schema name. A whole-store write (`push_all`) refuses with it, names the schema id, the names involved and a record key, writes nothing and leaves the file as it is. A caller tells it apart with `error.downcast_ref::()`. diff --git a/packages/cultcache-rs/README.md b/packages/cultcache-rs/README.md index 8a8b8f5e..ed9701d5 100644 --- a/packages/cultcache-rs/README.md +++ b/packages/cultcache-rs/README.md @@ -236,6 +236,17 @@ assert_eq!(rmp_serde::from_slice::(&bytes)?, tree); # Ok::<(), Box>(()) ``` +## Records written by a newer build + +A payload that carries a slot past the slots its type declares, in a record, a nested record, a list element or a union +arm (a unit arm declares none), still decodes: the extra slots are skipped. The cache then holds that record read-only, +because writing it would drop what the newer writer stored. `put`, `put_envelope`, `put_raw_envelope`, +`put_prepared_batch` and `delete` of its key are refused with `SchemaConflictError`, whose `unread_slots` names the type +and the slot counts and never a value; `CultCache::is_writable(type, key)` answers the same check. An untouched +read-only record keeps its bytes through every other write. A short payload (missing trailing slots) is not marked, and +a payload nested past `MAX_PAYLOAD_DEPTH` is refused before anything is read. `decode_payload_marked` is the decode that +returns the `UnreadSlots` mark. This runtime has no compatible schema ids, so no mark is consented. + ## Structure Of Arrays The C# CultCache hot path exposes CPU-local SoA scans as: diff --git a/packages/cultcache-rs/cultcache-rs-derive/src/lib.rs b/packages/cultcache-rs/cultcache-rs-derive/src/lib.rs index c7f9a3a2..b426ae01 100644 --- a/packages/cultcache-rs/cultcache-rs-derive/src/lib.rs +++ b/packages/cultcache-rs/cultcache-rs-derive/src/lib.rs @@ -381,6 +381,7 @@ fn slot_codec(ident: &syn::Ident, slots: &[CultCacheSlot]) -> proc_macro2::Token where __A: ::serde::de::SeqAccess<'de>, { + let __ticket = ::cultcache_rs::__enter_slots(); #(#option_declarations)* let mut index = 0usize; while index <= #max_slot { @@ -390,7 +391,15 @@ fn slot_codec(ident: &syn::Ident, slots: &[CultCacheSlot]) -> proc_macro2::Token } index += 1; } - while let ::std::option::Option::Some(_) = seq.next_element::<::serde::de::IgnoredAny>()? {} + // The slots past the declared ones are skipped and counted: the decode entry marks the record + // that carried them read-only. + let mut __extra = 0usize; + while seq.next_element::<::serde::de::IgnoredAny>()?.is_some() { + __extra += 1; + } + if __extra > 0 { + ::cultcache_rs::__note_unread_slots(__ticket, stringify!(#ident), #max_slot + 1 + __extra, #max_slot + 1); + } Ok(#ident { #(#build_fields),* }) @@ -567,10 +576,13 @@ fn union_codec(input: DeriveInput) -> syn::Result { quote! { #key => { match seq - .next_element::<::std::option::Option<[(); 0]>>() + .next_element::<::std::option::Option<::cultcache_rs::__UnitArmSlots>>() .map_err(|_| ::serde::de::Error::custom(#arity_message))? { - ::std::option::Option::Some(::std::option::Option::Some(_)) => #ident::#variant, + ::std::option::Option::Some(::std::option::Option::Some(slots)) => { + slots.note(stringify!(#variant)); + #ident::#variant + } ::std::option::Option::Some(::std::option::Option::None) => { return ::std::result::Result::Err(::serde::de::Error::custom( format!(#nil_slots_message, #key), diff --git a/packages/cultcache-rs/src/lib.rs b/packages/cultcache-rs/src/lib.rs index 686547f4..942f4e05 100644 --- a/packages/cultcache-rs/src/lib.rs +++ b/packages/cultcache-rs/src/lib.rs @@ -800,6 +800,145 @@ pub fn decode_payload(payload: &[u8]) -> Result< decode_grown(payload).map_err(opaque_decode_error) } +/// What a payload decode found past the slots this build declares, at any depth: the first type read with extra slots, +/// how many slots it carried against how many it declares, and how many objects in the payload did. It holds no slot +/// value, so a refusal can name it. A record whose payload carries it is read-only in the cache +/// ([`CultCache::is_writable`]); this runtime has no compatible schema ids, so every mark is unconsented. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UnreadSlots { + /// The first type read with extra slots (a unit arm is named by its variant). + pub type_name: String, + /// The slots that object carried. + pub slot_count: usize, + /// The slots this build declares for it. + pub declared_count: usize, + /// The objects in the payload that carried extra slots. + pub occurrences: usize, +} + +/// The open mark scope of a decode: how many slot objects it has entered, and the mark of the first entered one that +/// carried extra slots (the reference names the first type read, which is the outermost: it is entered before its members). +#[derive(Default)] +struct MarkScope { + entered: usize, + mark: Option<(usize, UnreadSlots)>, +} + +thread_local! { + /// The open mark scope of a decode on this thread: `None` when no decode entry has one open, so a decode through + /// serde alone notes nothing. The slot visitors the derives write note into it. + static UNREAD_SLOTS: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The derives' sensor, first half: a slot object is entered. Its ticket orders it among the objects of the decode. +#[doc(hidden)] +pub fn __enter_slots() -> usize { + UNREAD_SLOTS.with(|scope| { + scope.borrow_mut().as_mut().map_or(0, |open| { + open.entered += 1; + open.entered + }) + }) +} + +/// The derives' sensor, second half: the object entered as `ticket`, of `type_name`, carried `carried` slots where this +/// build declares `declared`. +#[doc(hidden)] +pub fn __note_unread_slots(ticket: usize, type_name: &str, carried: usize, declared: usize) { + UNREAD_SLOTS.with(|scope| { + let mut scope = scope.borrow_mut(); + let Some(open) = scope.as_mut() else { + return; + }; + let occurrences = open.mark.as_ref().map_or(0, |(_, found)| found.occurrences) + 1; + if open.mark.as_ref().is_none_or(|(first, _)| ticket < *first) { + let named = UnreadSlots { type_name: type_name.to_string(), slot_count: carried, declared_count: declared, occurrences }; + open.mark = Some((ticket, named)); + } else if let Some((_, found)) = open.mark.as_mut() { + found.occurrences = occurrences; + } + }); +} + +/// A unit arm is a zero-slot record: its slots array is read and counted, not refused. +#[doc(hidden)] +pub struct __UnitArmSlots { + ticket: usize, + extra: usize, +} + +impl __UnitArmSlots { + /// Notes the arm if its array held any element. + pub fn note(self, variant: &str) { + if self.extra > 0 { + __note_unread_slots(self.ticket, variant, self.extra, 0); + } + } +} + +impl<'de> serde::Deserialize<'de> for __UnitArmSlots { + fn deserialize>(deserializer: D) -> std::result::Result { + struct Count; + impl<'de> serde::de::Visitor<'de> for Count { + type Value = __UnitArmSlots; + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a slots array") + } + fn visit_seq>(self, mut seq: A) -> std::result::Result { + let ticket = __enter_slots(); + let mut extra = 0usize; + while seq.next_element::()?.is_some() { + extra += 1; + } + Ok(__UnitArmSlots { ticket, extra }) + } + } + deserializer.deserialize_seq(Count) + } +} + +/// Puts the previous scope back whatever the decode did. +struct UnreadScope(Option); + +impl UnreadScope { + fn open() -> Self { + Self(UNREAD_SLOTS.with(|scope| scope.replace(Some(MarkScope::default())))) + } + + fn mark(&self) -> Option { + UNREAD_SLOTS.with(|scope| scope.borrow_mut().as_mut().and_then(|open| open.mark.take()).map(|(_, mark)| mark)) + } +} + +impl Drop for UnreadScope { + fn drop(&mut self) { + UNREAD_SLOTS.with(|scope| *scope.borrow_mut() = self.0.take()); + } +} + +/// [`decode_payload`] with the mark: the same depth check and grown decode, inside a scope the derives' slot +/// visitors note into. A payload past the nesting limit is refused before the decode, never marked. +pub fn decode_payload_marked(payload: &[u8]) -> Result<(T, Option)> { + check_payload_depth(payload)?; + let scope = UnreadScope::open(); + let value = decode_grown(payload).map_err(opaque_decode_error)?; + Ok((value, scope.mark())) +} + +/// The registered check of a held payload: monomorphized by [`CultCache::register_entry_type`] so the untyped write +/// entries can decode a payload they cannot name. +/// A payload the type cannot decode at all carries no finding: replacing or removing it stays allowed, as it was before +/// the mark, so a corrupt record can still be repaired. +fn unread_slots_of(payload: &[u8]) -> Option { + decode_payload_marked::(payload).ok().and_then(|(_, mark)| mark) +} + +/// What a registered type is to the cache: its schema name and how to read the slots a held payload carries. +struct Definition { + schema_name: &'static str, + unread_slots: fn(&[u8]) -> Option, +} + /// The nesting bound for an envelope admitted without a typed decode, from the same walk that /// [`decode_payload`] runs first. Names the entry's type and key, never the payload. fn require_payload_depth(entry: &CultCacheEnvelope) -> Result<()> { @@ -938,10 +1077,26 @@ pub struct SchemaConflictError { pub schema_id: String, pub schema_names: Vec, pub record_key: String, + /// Set when the refusal is a write or removal of a record held read-only for the slots its payload carries past + /// this build's; `None` for every other refusal. + pub unread_slots: Option, } impl std::fmt::Display for SchemaConflictError { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if let Some(unread) = &self.unread_slots { + return write!( + formatter, + "{} record {} is read-only: {} was read with {} slots where this build declares {} ({} object(s) in the record). \ + Writing it would drop data a newer writer stored; read it with types that declare those slots, or write it from that build.", + self.schema_names.first().map_or("", String::as_str), + self.record_key, + unread.type_name, + unread.slot_count, + unread.declared_count, + unread.occurrences + ); + } write!( formatter, "schema id {:?} cannot describe record {:?}: {:?}", @@ -2738,7 +2893,7 @@ struct CultCacheStoreRegistration { } pub struct CultCache { - definitions: BTreeMap, + definitions: BTreeMap, /// The registered types declared `#[cultcache(global)]`. globals: BTreeSet, schema_name_definitions: BTreeMap, @@ -2825,8 +2980,8 @@ impl CultCache { "CultCache entry types must declare a non-empty type" )); } - if let Some(existing_schema) = self.definitions.get(T::TYPE) - && *existing_schema != T::SCHEMA_NAME + if let Some(existing) = self.definitions.get(T::TYPE) + && existing.schema_name != T::SCHEMA_NAME { return Err(anyhow!( "CultCache already has a different definition registered for type {:?}", @@ -2875,7 +3030,7 @@ impl CultCache { } } } - self.definitions.insert(T::TYPE.to_string(), T::SCHEMA_NAME); + self.definitions.insert(T::TYPE.to_string(), Definition { schema_name: T::SCHEMA_NAME, unread_slots: unread_slots_of:: }); self.schema_name_definitions .insert(T::SCHEMA_NAME.to_string(), T::TYPE.to_string()); Ok(()) @@ -3036,6 +3191,40 @@ impl CultCache { Ok(Some(payload)) } + /// Whether a write or removal of `(type_id, key)` would be admitted by the unread-slots rule: false when the held + /// payload carries slots past its registered type's declared slots, at any depth, which makes the record read-only. + /// True for a key the cache does not hold, and for a held payload the registered type cannot decode at all (it + /// carries no finding). An unregistered type is an error. Advisory: the write entries ask the same check themselves. + pub fn is_writable(&self, type_id: &str, key: &str) -> Result { + Ok(self.unread_slots_held(type_id, key)?.is_none()) + } + + /// The one check behind every write entry and [`CultCache::is_writable`]: the held envelope at `(type_id, key)` + /// decoded under the registered type's mark. + fn unread_slots_held(&self, type_id: &str, key: &str) -> Result> { + let Some(definition) = self.definitions.get(type_id) else { + bail!("No entry type registered for CultCache envelope type {type_id:?}"); + }; + let Some(held) = self.entries.get(&entry_id_parts(type_id, key)) else { + return Ok(None); + }; + Ok((definition.unread_slots)(&held.payload)) + } + + /// Refuses a write or removal of a record held read-only for its unread slots, before any store is touched. + fn refuse_unread_slots(&self, type_id: &str, key: &str) -> Result<()> { + let Some(unread) = self.unread_slots_held(type_id, key)? else { + return Ok(()); + }; + let held = &self.entries[&entry_id_parts(type_id, key)]; + Err(anyhow::Error::new(SchemaConflictError { + schema_id: schema_identity(held).to_string(), + schema_names: vec![self.definitions[type_id].schema_name.to_string()], + record_key: key.to_string(), + unread_slots: Some(unread), + })) + } + pub fn get_required(&self, key: &str) -> Result { self.get::(key)? .ok_or_else(|| anyhow!("CultCache has no {:?} entry at key {:?}", T::TYPE, key)) @@ -3166,6 +3355,7 @@ impl CultCache { pub fn put(&mut self, key: impl Into, value: &T) -> Result { let (entry, parsed) = self.prepare_entry(key, value)?; + self.refuse_unread_slots(&entry.r#type, &entry.key)?; self.refuse_second_global(&self.entries, &entry.r#type, &entry.key)?; self.refuse_retype(&self.entries, &self.foreign, &entry)?; let change = self.judge_unique(&[&entry])?; @@ -3266,6 +3456,7 @@ impl CultCache { )); } require_payload_depth(entry)?; + self.refuse_unread_slots(&entry.r#type, &entry.key)?; self.refuse_claimed_id(entry)?; let Some(home) = self.home_index(&entry.r#type)? else { continue; @@ -3308,6 +3499,7 @@ impl CultCache { pub fn put_envelope(&mut self, entry: CultCacheEnvelope) -> Result { let parsed = self.validate_envelope::(&entry)?; + self.refuse_unread_slots(&entry.r#type, &entry.key)?; self.refuse_claimed_id(&entry)?; self.refuse_second_global(&self.entries, &entry.r#type, &entry.key)?; self.refuse_retype(&self.entries, &self.foreign, &entry)?; @@ -3345,6 +3537,7 @@ impl CultCache { )); } require_payload_depth(&entry)?; + self.refuse_unread_slots(&entry.r#type, &entry.key)?; self.refuse_claimed_id(&entry)?; self.refuse_second_global(&self.entries, &entry.r#type, &entry.key)?; self.refuse_retype(&self.entries, &self.foreign, &entry)?; @@ -3400,6 +3593,7 @@ impl CultCache { pub fn delete(&mut self, key: &str) -> Result { self.require_entry_type::()?; + self.refuse_unread_slots(T::TYPE, key)?; let id = entry_id_parts(T::TYPE, key); let Some(entry) = self.entries.get(&id).cloned() else { if let Some((_, foreign)) = self.foreign.iter().find(|(_, foreign)| foreign.key == key) { @@ -3518,7 +3712,7 @@ impl CultCache { } for (slot, keys) in &ordered { if let [first, second, ..] = keys.as_slice() { - let schema = self.definitions.get(&slot.0).copied().unwrap_or(&slot.0); + let schema = self.definitions.get(&slot.0).map_or(slot.0.as_str(), |definition| definition.schema_name); let violation = [slot.1.as_str(), first.as_str(), second.as_str(), schema]; if least.is_none_or(|best| violation_cmp(&violation, &best).is_lt()) { least = Some(violation); @@ -3553,7 +3747,7 @@ impl CultCache { .find(|held_key| held_key.as_str() != key); match held_other { Some(existing_key) => Err(CultCacheSecondGlobal { - schema_name: self.definitions.get(type_id).copied().unwrap_or(type_id).to_string(), + schema_name: self.definitions.get(type_id).map_or(type_id, |definition| definition.schema_name).to_string(), existing_key: existing_key.clone(), key: key.to_string(), } @@ -3597,6 +3791,7 @@ impl CultCache { schema_id: schema_identity(entry).to_string(), schema_names: vec![resolved, entry.r#type.clone()], record_key: entry.key.clone(), + unread_slots: None, })), _ => Ok(()), } @@ -3611,7 +3806,7 @@ impl CultCache { fn require_entry_type(&self) -> Result<()> { match self.definitions.get(T::TYPE) { - Some(schema_name) if *schema_name == T::SCHEMA_NAME => Ok(()), + Some(definition) if definition.schema_name == T::SCHEMA_NAME => Ok(()), _ => Err(anyhow!( "CultCache entry type {:?} is not registered on this cache instance", T::TYPE @@ -3693,6 +3888,7 @@ fn encode_store_snapshot(entries: &[CultCacheEnvelope], disk: &DiskStore) -> Res schema_id, schema_names: vec![existing_type, entry.r#type.clone()], record_key: entry.key.clone(), + unread_slots: None, })); } } @@ -3710,6 +3906,7 @@ fn encode_store_snapshot(entries: &[CultCacheEnvelope], disk: &DiskStore) -> Res schema_id, schema_names: vec![arrived_type, document_type], record_key: key, + unread_slots: None, })); } } @@ -3846,6 +4043,7 @@ fn foreign_conflict(carried: &CultCacheEnvelope, written_type: &str) -> anyhow:: schema_id: schema_identity(carried).to_string(), schema_names: vec![carried.r#type.clone(), written_type.to_string()], record_key: carried.key.clone(), + unread_slots: None, }) } @@ -3856,6 +4054,7 @@ fn retype_conflict(held: &CultCacheEnvelope, written: &CultCacheEnvelope) -> any schema_id: schema_identity(written).to_string(), schema_names: vec![held.r#type.clone(), written.r#type.clone()], record_key: written.key.clone(), + unread_slots: None, }) } diff --git a/packages/cultcache-rs/tests/common/mod.rs b/packages/cultcache-rs/tests/common/mod.rs new file mode 100644 index 00000000..3f893c0f --- /dev/null +++ b/packages/cultcache-rs/tests/common/mod.rs @@ -0,0 +1,235 @@ +//! The union-parity vectors' types and constructed value, shared by the test files that walk them. +#![allow(dead_code)] + +use std::path::PathBuf; + +use cultcache_rs::CultSlots; +use cultcache_rs::CultUnion; +use cultcache_rs::DatabaseEntry; + + +#[derive(Clone, Debug, PartialEq, CultUnion)] +pub enum Node { + #[cultcache(key = 0)] + Box(BoxArm), + #[cultcache(key = 1)] + Text(TextArm), + #[cultcache(key = 2)] + Use(UseArm), + #[cultcache(key = 5)] + Image(ImageArm), + #[cultcache(key = 6)] + Wrap(WrapArm), +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct WrapArm { + #[cultcache(key = 0)] + pub inner: Option>, + #[cultcache(key = 1)] + pub id: String, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct BoxArm { + #[cultcache(key = 0)] + pub id: String, + #[cultcache(key = 1)] + pub children: Vec, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct TextArm { + #[cultcache(key = 0)] + pub id: String, + #[cultcache(key = 1)] + pub content: String, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct UseArm { + #[cultcache(key = 0)] + pub id: String, + #[cultcache(key = 1)] + pub composition: Composition, + #[cultcache(key = 2)] + pub slots: Vec>, +} + +// Slot 2 is retired: a gap written nil. +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct ImageArm { + #[cultcache(key = 0)] + pub id: String, + #[cultcache(key = 1)] + pub uri: String, + #[cultcache(key = 3)] + pub alt: String, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct Composition { + #[cultcache(key = 0)] + pub name: String, + #[cultcache(key = 1)] + pub body: Option>, +} + +#[derive(Clone, Debug, PartialEq, CultUnion)] +pub enum Outcome { + #[cultcache(key = 0)] + Pending(PendingArm), + #[cultcache(key = 1)] + Completed(CompletedArm), + #[cultcache(key = 2)] + Denied(IdArm), + #[cultcache(key = -2147483648)] + Floor(IdArm), + #[cultcache(key = 2147483647)] + Ceiling(IdArm), +} + +// The codec's unit arm (no members, written [key, []]), kept apart from the golden: a document list's arms carry ids. +#[derive(Clone, Debug, PartialEq, CultUnion)] +pub enum UnitOutcome { + #[cultcache(key = 2)] + Denied, + #[cultcache(key = -2147483648)] + Floor, + #[cultcache(key = 2147483647)] + Ceiling, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct PendingArm { + #[cultcache(key = 0)] + pub message: String, + #[cultcache(key = 1)] + pub id: String, +} + +// An arm with no members of its own: just its element id. +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct IdArm { + #[cultcache(key = 0)] + pub id: String, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct CompletedArm { + #[cultcache(key = 0)] + pub source_version: i32, + #[cultcache(key = 1)] + pub id: String, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct NamedArm { + #[cultcache(key = 0)] + pub name: String, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct UsesArm { + #[cultcache(key = 0)] + pub name: String, + #[cultcache(key = 1)] + pub uses: i32, +} + +#[derive(Clone, Debug, PartialEq, CultSlots)] +pub struct CountArm { + #[cultcache(key = 0)] + pub name: String, + #[cultcache(key = 1)] + pub count: i32, +} + +#[derive(Clone, Debug, PartialEq, CultUnion)] +pub enum Item { + #[cultcache(key = 0)] + Gem(NamedArm), + #[cultcache(key = 1)] + Tool(UsesArm), + #[cultcache(key = 2)] + Part(CountArm), +} + +// The same arms as Item under its own keys: key 2 is unknown to it. +#[derive(Clone, Debug, PartialEq, CultUnion)] +pub enum CraftedItem { + #[cultcache(key = 0)] + Tool(UsesArm), + #[cultcache(key = 1)] + Part(CountArm), +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "tests.union_surface", schema = "tests.union_surface.v1")] +pub struct UnionSurface { + #[cultcache(key = 0)] + pub id: String, + #[cultcache(key = 1)] + pub version: i32, + #[cultcache(key = 2)] + pub root: Option, + #[cultcache(key = 3)] + pub outcomes: Vec, + #[cultcache(key = 4)] + pub part: Option, + #[cultcache(key = 5)] + pub crafted: Option, + #[cultcache(key = 6)] + pub missing: Option, +} + +pub fn text(id: &str, content: &str) -> Node { + Node::Text(TextArm { id: id.into(), content: content.into() }) +} + +pub fn image(id: &str, uri: &str, alt: &str) -> Node { + Node::Image(ImageArm { id: id.into(), uri: uri.into(), alt: alt.into() }) +} + +pub fn boxed(id: &str, children: Vec) -> Node { + Node::Box(BoxArm { id: id.into(), children }) +} + +pub fn constructed() -> UnionSurface { + let inner = boxed("0000000000d0", vec![text("0000000000d1", "x"), image("0000000000d2", "uri://a", "alt")]); + UnionSurface { + id: "surface".into(), + version: 3, + root: Some(boxed( + "0000000000c0", + vec![ + text("0000000000c1", "hello"), + Node::Use(UseArm { + id: "0000000000c2".into(), + composition: Composition { name: "comp".into(), body: Some(std::boxed::Box::new(inner)) }, + slots: vec![Some(text("0000000000e1", "slot")), None, Some(boxed("0000000000e2", vec![]))], + }), + image("0000000000c3", "uri://b", ""), + ], + )), + outcomes: vec![ + Outcome::Pending(PendingArm { message: "wait".into(), id: "0000000000a1".into() }), + Outcome::Completed(CompletedArm { source_version: 7, id: "0000000000a2".into() }), + Outcome::Denied(id_arm("0000000000a3")), + ], + part: Some(Item::Tool(UsesArm { name: "hammer".into(), uses: 12 })), + crafted: Some(CraftedItem::Part(CountArm { name: "gear".into(), count: 4 })), + missing: None, + } +} + +pub fn id_arm(id: &str) -> IdArm { + IdArm { id: id.into() } +} + +pub fn vector(name: &str) -> Vec { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../tests/vectors/union-parity") + .join(name); + std::fs::read(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display())) +} diff --git a/packages/cultcache-rs/tests/slot_readonly.rs b/packages/cultcache-rs/tests/slot_readonly.rs new file mode 100644 index 00000000..6bf34375 --- /dev/null +++ b/packages/cultcache-rs/tests/slot_readonly.rs @@ -0,0 +1,350 @@ +//! A record whose payload carries unread slots at any depth is read-only: the C# reference's union-parity vectors +//! (README "Extra trailing slot" and "Slot stores") walked through the cache. This runtime has no compatible schema +//! ids, so every mark is unconsented and no `explained` outcome can arise. + +mod common; + +use std::path::Path; + +use common::*; +use cultcache_rs::CultCache; +use cultcache_rs::CultCacheEnvelope; +use cultcache_rs::DatabaseEntry; +use cultcache_rs::SchemaConflictError; +use cultcache_rs::SingleFileMessagePackBackingStore; +use cultcache_rs::UnreadSlots; +use cultcache_rs::decode_payload_marked; + +/// A row of `slot-outcomes.msgpack`: store, key, writable, explained, type, slots, declared, occurrences, flattenRefusedBy. +type SlotRow = (String, String, bool, Option, Option, Option, Option, Option, Option); + +const SLOT_VALUE: &str = "extra-slot"; + +/// `tests.slot_unit`, a document `[Name, Outcome: UnitOutcome]`. +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "tests.slot_unit", schema = "tests.slot_unit.v1")] +struct SlotUnit { + #[cultcache(key = 0)] + name: String, + #[cultcache(key = 1)] + outcome: UnitOutcome, +} + +/// Two declared slots, the second defaulted: a payload of one slot is short, not marked. +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "tests.shortened", schema = "tests.shortened.v1")] +struct Shortened { + #[cultcache(key = 0)] + id: String, + #[cultcache(key = 1, default)] + note: String, +} + +fn registered() -> CultCache { + let mut cache = CultCache::new(); + cache.register_entry_type::().unwrap(); + cache.register_entry_type::().unwrap(); + cache +} + +/// Any MessagePack value a store holds, enough to drop one record from a store and write the rest back. +#[derive(serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +enum Packed { + Nil(()), + Bool(bool), + Int(i64), + Text(String), + Bin(#[serde(with = "serde_bytes")] Vec), + Array(Vec), +} + +/// The committed store without its `marked-variant` record. A variant is a five-slot record, which this runtime's +/// store reader refuses whole (`the_variant_row_...`), so the other rows are walked from a copy without it. +fn without_variant_row(store: &[u8]) -> Vec { + let Packed::Array(mut parts) = rmp_serde::from_slice(store).unwrap() else { panic!("a store is an array") }; + let Packed::Array(records) = parts.last_mut().unwrap() else { panic!("a store ends in its records") }; + let before = records.len(); + records.retain(|record| !matches!(record, Packed::Array(fields) if matches!(fields.first(), Some(Packed::Text(key)) if key == "marked-variant"))); + assert_eq!(records.len(), before - 1); + rmp_serde::to_vec(&parts).unwrap() +} + +/// A copy of a committed store, opened with both types registered; the vector itself is never written. The slot store +/// is read without its variant row. +fn open_copy(file: &str, dir: &Path) -> (CultCache, std::path::PathBuf) { + let path = dir.join(file); + let bytes = if file == "extra-slot-store.cc" { without_variant_row(&vector(file)) } else { vector(file) }; + std::fs::write(&path, bytes).unwrap(); + let mut cache = registered(); + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap(); + cache.pull_all_backing_stores().unwrap(); + (cache, path) +} + +fn envelope(key: &str, payload: Vec) -> CultCacheEnvelope { + CultCacheEnvelope { + key: key.into(), + r#type: UnionSurface::TYPE.into(), + payload, + stored_at: "2026-01-01T00:00:00Z".into(), + schema_id: None, + } +} + +fn conflict(error: &anyhow::Error) -> &SchemaConflictError { + error.downcast_ref::().unwrap_or_else(|| panic!("not a schema conflict: {error:#}")) +} + +fn mark(type_name: &str, slot_count: usize, declared_count: usize, occurrences: usize) -> UnreadSlots { + UnreadSlots { type_name: type_name.into(), slot_count, declared_count, occurrences } +} + +/// The marks the README table pins, by `detail`. The reference names an arm by its class; here an arm is the +/// `...Arm` struct the union wraps. +fn expected_mark(detail: &str) -> UnreadSlots { + match detail { + "record" | "depth" => mark("UnionSurface", 8, 7, 1), + "nested-record" => mark("Composition", 3, 2, 1), + "arm" => mark("BoxArm", 3, 2, 1), + "list-element" => mark("TextArm", 3, 2, 1), + other => panic!("unknown detail {other}"), + } +} + +fn assert_refused_with(error: &anyhow::Error, key: &str, expected: &UnreadSlots) { + let refusal = conflict(error); + assert_eq!(refusal.unread_slots.as_ref(), Some(expected)); + assert_eq!(refusal.record_key, key); + assert_eq!(refusal.schema_names.len(), 1); + let message = error.to_string(); + assert!(message.contains(&expected.type_name), "{message}"); + assert!(message.contains(&expected.slot_count.to_string()) && message.contains(&expected.declared_count.to_string()), "{message}"); + assert!(!message.contains(SLOT_VALUE), "a refusal echoed the slot value: {message}"); +} + +#[test] +fn every_read_only_vector_decodes_marked_and_is_not_writable() { + let rows: Vec<(String, String, String, Option, String)> = rmp_serde::from_slice(&vector("outcomes.msgpack")).unwrap(); + assert_eq!(rows.len(), 9); + let bounds: Vec = rmp_serde::from_slice(&vector("bounds-outcomes.msgpack")).unwrap(); + let mut cases: Vec<(String, String)> = rows + .into_iter() + .filter(|(_, outcome, ..)| outcome == "read-only") + .map(|(file, _, _, _, detail)| (file, detail)) + .collect(); + for entry in &bounds[1..] { + let fields: Vec<&str> = entry.as_array().unwrap().iter().filter_map(|field| field.as_str()).collect(); + if fields[1] == "read-only" { + cases.push((fields[0].to_string(), fields[3].to_string())); + } + } + assert_eq!(cases.len(), 5); + for (file, detail) in cases { + let payload = vector(&file); + let (value, found) = decode_payload_marked::(&payload).unwrap_or_else(|error| panic!("{file}: {error:#}")); + assert_eq!(value, constructed(), "{file}"); + assert_eq!(found, Some(expected_mark(&detail)), "{file}"); + + let mut cache = registered(); + let dir = tempfile::tempdir().unwrap(); + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(dir.path().join("s.cc"))).unwrap(); + cache.put_raw_envelope(envelope("k", payload.clone())).unwrap(); + assert_eq!(cache.get::("k").unwrap(), Some(constructed()), "{file}"); + assert!(!cache.is_writable(UnionSurface::TYPE, "k").unwrap(), "{file}"); + assert!(cache.is_writable(UnionSurface::TYPE, "unheld").unwrap(), "{file}"); + let error = cache.put("k", &constructed()).unwrap_err(); + assert_refused_with(&error, "k", &expected_mark(&detail)); + } +} + +#[test] +fn clean_and_short_payloads_are_writable_and_unmarked() { + let (value, found) = decode_payload_marked::(&vector("union-surface.msgpack")).unwrap(); + assert_eq!((value, found), (constructed(), None)); + // A payload short of its declared slots keeps its defaults and does not mark. + let (value, found) = decode_payload_marked::(&rmp_serde::to_vec(&("only",)).unwrap()).unwrap(); + assert_eq!((value.id.as_str(), value.note.as_str(), found), ("only", "", None)); +} + +#[test] +fn a_payload_past_the_nesting_limit_is_refused_never_marked() { + for file in ["depth-skipped-past-limit.msgpack", "depth-past-limit.msgpack"] { + let error = decode_payload_marked::(&vector(file)).unwrap_err(); + assert!(error.to_string().contains("the limit is 256"), "{file}: {error:#}"); + } +} + +#[test] +fn a_plain_serde_decode_marks_nothing_and_does_not_leak_a_scope() { + // No scope is open: the visitors note into nothing. + let value: UnionSurface = rmp_serde::from_slice(&vector("extra-slot-record.msgpack")).unwrap(); + assert_eq!(value, constructed()); + // A marked decode followed by a clean one: the first mark does not survive into the second. + assert!(decode_payload_marked::(&vector("extra-slot-record.msgpack")).unwrap().1.is_some()); + assert_eq!(decode_payload_marked::(&vector("union-surface.msgpack")).unwrap().1, None); +} + +#[test] +fn the_slot_store_rows_walk_through_the_cache() { + let rows: Vec = + rmp_serde::from_slice(&vector("slot-outcomes.msgpack")).unwrap(); + assert_eq!(rows.len(), 8); + let dir = tempfile::tempdir().unwrap(); + let mut walked = 0; + for (store, key, writable, _explained, type_name, slots, declared, occurrences, flatten_refused_by) in rows { + // The variant row is a record this runtime cannot hold: see the variant test. The consent store's `writable` and + // `explained` answer the compatible-id declaration, which this runtime has none of; its marks are walked below. + if flatten_refused_by.is_some() || store == "extra-slot-consent.cc" { + continue; + } + let case = dir.path().join(&key); + std::fs::create_dir_all(&case).unwrap(); + let (mut cache, _) = open_copy(&store, &case); + let type_id = if key == "unit-arm" { SlotUnit::TYPE } else { UnionSurface::TYPE }; + assert_eq!(cache.is_writable(type_id, &key).unwrap(), writable, "{store} {key}"); + let removal = if key == "unit-arm" { cache.delete::(&key) } else { cache.delete::(&key) }; + match writable { + true => assert!(removal.unwrap()), + false => { + let found = conflict(&removal.unwrap_err()).unread_slots.clone().unwrap(); + // The reference names the unit arm's class, Denied2; here the variant. + let expected_type = match type_name.as_deref().unwrap() { + "Denied2" => "Denied", + other => other, + }; + assert_eq!((found.type_name.as_str(), Some(found.slot_count), Some(found.declared_count), Some(found.occurrences)), (expected_type, slots, declared, occurrences)); + assert!(cache.snapshot_envelopes().iter().any(|held| held.key == key), "a refused removal removed {key}"); + } + } + walked += 1; + } + assert_eq!(walked, 3); +} + +#[test] +fn the_consent_store_marks_are_unconsented_here() { + let rows: Vec = + rmp_serde::from_slice(&vector("slot-outcomes.msgpack")).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let mut found = 0; + for (store, key, _writable, _explained, _type_name, slots, declared, occurrences, _) in rows { + if store != "extra-slot-consent.cc" { + continue; + } + let (cache, _) = open_copy(&store, dir.path()); + let held = cache.snapshot_envelopes().into_iter().find(|held| held.key == key).unwrap(); + let (_, mark) = decode_payload_marked::(&held.payload).unwrap(); + match slots { + // The reference's `consented` row is writable there (a listed compatible id covers it); here every mark refuses. + None => assert_eq!(mark, None, "{key}"), + Some(slots) => { + let mark = mark.unwrap_or_else(|| panic!("{key} carried no mark")); + // The first type read is the document, whose reference name is SurfaceDeclaring. + assert_eq!(mark.type_name, "UnionSurface", "{key}"); + assert_eq!((Some(mark.slot_count), Some(mark.declared_count), Some(mark.occurrences)), (Some(slots), declared, occurrences), "{key}"); + assert!(!cache.is_writable(UnionSurface::TYPE, &key).unwrap(), "{key}"); + } + } + found += 1; + } + assert_eq!(found, 4); +} + +#[test] +fn every_write_entry_refuses_a_marked_key_before_any_store_is_touched() { + let dir = tempfile::tempdir().unwrap(); + let (mut cache, path) = open_copy("extra-slot-store.cc", dir.path()); + let expected = mark("Composition", 3, 2, 1); + let before = std::fs::read(&path).unwrap(); + let held = cache.snapshot_envelopes().into_iter().find(|held| held.key == "marked").unwrap(); + let clean = cache.snapshot_envelopes().into_iter().find(|held| held.key == "clean").unwrap(); + assert!(!cache.is_writable(UnionSurface::TYPE, "marked").unwrap()); + assert!(cache.is_writable(UnionSurface::TYPE, "clean").unwrap()); + + let replacing = envelope("marked", rmp_serde::to_vec(&constructed()).unwrap()); + assert_refused_with(&cache.put("marked", &constructed()).unwrap_err(), "marked", &expected); + assert_refused_with(&cache.put_envelope::(replacing.clone()).unwrap_err(), "marked", &expected); + assert_refused_with(&cache.put_raw_envelope(replacing.clone()).unwrap_err(), "marked", &expected); + assert_refused_with(&cache.put_prepared_batch(vec![replacing]).unwrap_err(), "marked", &expected); + assert_refused_with(&cache.delete::("marked").unwrap_err(), "marked", &expected); + assert_refused_with( + &cache.update::("marked", |current| current.unwrap()).unwrap_err(), + "marked", + &expected, + ); + + // A batch with a marked key refuses whole: its clean member is not written either. + let mut rewritten = clean.clone(); + rewritten.payload = rmp_serde::to_vec(&UnionSurface { version: 9, ..constructed() }).unwrap(); + let batch = vec![rewritten, envelope("marked", rmp_serde::to_vec(&constructed()).unwrap())]; + assert_refused_with(&cache.put_prepared_batch(batch).unwrap_err(), "marked", &expected); + + assert_eq!(std::fs::read(&path).unwrap(), before, "a refused write touched the store"); + assert_eq!(cache.snapshot_envelopes().into_iter().find(|entry| entry.key == "marked").unwrap(), held); + assert_eq!(cache.snapshot_envelopes().into_iter().find(|entry| entry.key == "clean").unwrap(), clean); + + // A write to another key succeeds, and the marked record's bytes, schema id and stored-at are carried unchanged. + cache.put("clean", &UnionSurface { version: 9, ..constructed() }).unwrap(); + cache.put("other", &constructed()).unwrap(); + assert!(cache.delete::("other").unwrap()); + let mut reopened = registered(); + reopened.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap(); + reopened.pull_all_backing_stores().unwrap(); + let carried = reopened.snapshot_envelopes().into_iter().find(|entry| entry.key == "marked").unwrap(); + assert_eq!(carried, held); + assert_eq!(carried.payload, vector("extra-slot-nested-record.msgpack")); + assert_eq!(reopened.get::("clean").unwrap().unwrap().version, 9); +} + +#[test] +fn a_unit_arm_with_slots_decodes_as_the_unit_arm_and_marks() { + let (document, found) = decode_payload_marked::(&unit_arm_payload()).unwrap(); + assert_eq!(document, SlotUnit { name: "unit-arm".into(), outcome: UnitOutcome::Denied }); + assert_eq!(found, Some(mark("Denied", 1, 0, 1))); + + let dir = tempfile::tempdir().unwrap(); + let (mut cache, _) = open_copy("extra-slot-store.cc", dir.path()); + assert_eq!(cache.get::("unit-arm").unwrap(), Some(document.clone())); + assert!(!cache.is_writable(SlotUnit::TYPE, "unit-arm").unwrap()); + let error = cache.put("unit-arm", &document).unwrap_err(); + assert_refused_with(&error, "unit-arm", &mark("Denied", 1, 0, 1)); + assert_refused_with(&cache.delete::("unit-arm").unwrap_err(), "unit-arm", &mark("Denied", 1, 0, 1)); + + // Several elements are still one marked object, and a clean unit arm is unmarked. + let (_, found) = decode_payload_marked::(&rmp_serde::to_vec(&(2u64, ("a", "b", "c"))).unwrap()).unwrap(); + assert_eq!(found, Some(mark("Denied", 3, 0, 1))); + let (_, found) = decode_payload_marked::(&vector("unit-arm-denied.msgpack")).unwrap(); + assert_eq!(found, None); +} + +fn unit_arm_payload() -> Vec { + let dir = tempfile::tempdir().unwrap(); + let (cache, _) = open_copy("extra-slot-store.cc", dir.path()); + cache.snapshot_envelopes().into_iter().find(|held| held.key == "unit-arm").unwrap().payload +} + +#[test] +fn the_variant_row_of_the_slot_store_is_refused_whole_by_the_store_reader() { + // `marked-variant` is a five-slot record (a variant): this runtime holds no variants, and its v1 snapshot reader + // refuses such a record, so the store as written cannot load here and the other rows are walked without it. + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("extra-slot-store.cc"); + std::fs::write(&path, vector("extra-slot-store.cc")).unwrap(); + let mut cache = registered(); + cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap(); + let error = cache.pull_all_backing_stores().unwrap_err(); + assert!(format!("{error:#}").contains("is not decodable"), "{error:#}"); +} + +#[test] +fn a_held_payload_the_type_cannot_decode_carries_no_finding_and_stays_repairable() { + let mut cache = registered(); + // A text where the document's version belongs: not a record this type reads, marked or otherwise. + let broken = rmp_serde::to_vec(&("surface", "not-a-version")).unwrap(); + cache.put_raw_envelope(envelope("k", broken)).unwrap(); + assert!(cache.is_writable(UnionSurface::TYPE, "k").unwrap()); + cache.put("k", &constructed()).unwrap(); + assert!(cache.delete::("k").unwrap()); + assert!(cache.is_writable("tests.unregistered", "k").is_err()); +} diff --git a/packages/cultcache-rs/tests/union_parity.rs b/packages/cultcache-rs/tests/union_parity.rs index 24fe999a..c51bd3d8 100644 --- a/packages/cultcache-rs/tests/union_parity.rs +++ b/packages/cultcache-rs/tests/union_parity.rs @@ -1,244 +1,17 @@ //! The Rust runtime held to tests/vectors/union-parity, written by the C# reference. //! Bytes and outcomes are read from the committed files; only the constructed value is spelled here. -use std::path::PathBuf; - use cultcache_rs::CultCache; use cultcache_rs::CacheBackingStore; use cultcache_rs::CultCacheEnvelope; use cultcache_rs::MAX_PAYLOAD_DEPTH; use cultcache_rs::PayloadTooDeep; use cultcache_rs::check_payload_depth; -use cultcache_rs::CultSlots; -use cultcache_rs::CultUnion; use cultcache_rs::DatabaseEntry; use cultcache_rs::SingleFileMessagePackBackingStore; -#[derive(Clone, Debug, PartialEq, CultUnion)] -enum Node { - #[cultcache(key = 0)] - Box(BoxArm), - #[cultcache(key = 1)] - Text(TextArm), - #[cultcache(key = 2)] - Use(UseArm), - #[cultcache(key = 5)] - Image(ImageArm), - #[cultcache(key = 6)] - Wrap(WrapArm), -} - -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct WrapArm { - #[cultcache(key = 0)] - inner: Option>, - #[cultcache(key = 1)] - id: String, -} - -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct BoxArm { - #[cultcache(key = 0)] - id: String, - #[cultcache(key = 1)] - children: Vec, -} - -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct TextArm { - #[cultcache(key = 0)] - id: String, - #[cultcache(key = 1)] - content: String, -} - -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct UseArm { - #[cultcache(key = 0)] - id: String, - #[cultcache(key = 1)] - composition: Composition, - #[cultcache(key = 2)] - slots: Vec>, -} - -// Slot 2 is retired: a gap written nil. -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct ImageArm { - #[cultcache(key = 0)] - id: String, - #[cultcache(key = 1)] - uri: String, - #[cultcache(key = 3)] - alt: String, -} - -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct Composition { - #[cultcache(key = 0)] - name: String, - #[cultcache(key = 1)] - body: Option>, -} - -#[derive(Clone, Debug, PartialEq, CultUnion)] -enum Outcome { - #[cultcache(key = 0)] - Pending(PendingArm), - #[cultcache(key = 1)] - Completed(CompletedArm), - #[cultcache(key = 2)] - Denied(IdArm), - #[cultcache(key = -2147483648)] - Floor(IdArm), - #[cultcache(key = 2147483647)] - Ceiling(IdArm), -} - -// The codec's unit arm (no members, written [key, []]), kept apart from the golden: a document list's arms carry ids. -#[derive(Clone, Debug, PartialEq, CultUnion)] -enum UnitOutcome { - #[cultcache(key = 2)] - Denied, - #[cultcache(key = -2147483648)] - Floor, - #[cultcache(key = 2147483647)] - Ceiling, -} - -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct PendingArm { - #[cultcache(key = 0)] - message: String, - #[cultcache(key = 1)] - id: String, -} - -// An arm with no members of its own: just its element id. -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct IdArm { - #[cultcache(key = 0)] - id: String, -} - -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct CompletedArm { - #[cultcache(key = 0)] - source_version: i32, - #[cultcache(key = 1)] - id: String, -} - -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct NamedArm { - #[cultcache(key = 0)] - name: String, -} - -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct UsesArm { - #[cultcache(key = 0)] - name: String, - #[cultcache(key = 1)] - uses: i32, -} - -#[derive(Clone, Debug, PartialEq, CultSlots)] -struct CountArm { - #[cultcache(key = 0)] - name: String, - #[cultcache(key = 1)] - count: i32, -} - -#[derive(Clone, Debug, PartialEq, CultUnion)] -enum Item { - #[cultcache(key = 0)] - Gem(NamedArm), - #[cultcache(key = 1)] - Tool(UsesArm), - #[cultcache(key = 2)] - Part(CountArm), -} - -// The same arms as Item under its own keys: key 2 is unknown to it. -#[derive(Clone, Debug, PartialEq, CultUnion)] -enum CraftedItem { - #[cultcache(key = 0)] - Tool(UsesArm), - #[cultcache(key = 1)] - Part(CountArm), -} - -#[derive(Clone, Debug, PartialEq, DatabaseEntry)] -#[cultcache(type = "tests.union_surface", schema = "tests.union_surface.v1")] -struct UnionSurface { - #[cultcache(key = 0)] - id: String, - #[cultcache(key = 1)] - version: i32, - #[cultcache(key = 2)] - root: Option, - #[cultcache(key = 3)] - outcomes: Vec, - #[cultcache(key = 4)] - part: Option, - #[cultcache(key = 5)] - crafted: Option, - #[cultcache(key = 6)] - missing: Option, -} - -fn text(id: &str, content: &str) -> Node { - Node::Text(TextArm { id: id.into(), content: content.into() }) -} - -fn image(id: &str, uri: &str, alt: &str) -> Node { - Node::Image(ImageArm { id: id.into(), uri: uri.into(), alt: alt.into() }) -} - -fn boxed(id: &str, children: Vec) -> Node { - Node::Box(BoxArm { id: id.into(), children }) -} - -fn constructed() -> UnionSurface { - let inner = boxed("0000000000d0", vec![text("0000000000d1", "x"), image("0000000000d2", "uri://a", "alt")]); - UnionSurface { - id: "surface".into(), - version: 3, - root: Some(boxed( - "0000000000c0", - vec![ - text("0000000000c1", "hello"), - Node::Use(UseArm { - id: "0000000000c2".into(), - composition: Composition { name: "comp".into(), body: Some(std::boxed::Box::new(inner)) }, - slots: vec![Some(text("0000000000e1", "slot")), None, Some(boxed("0000000000e2", vec![]))], - }), - image("0000000000c3", "uri://b", ""), - ], - )), - outcomes: vec![ - Outcome::Pending(PendingArm { message: "wait".into(), id: "0000000000a1".into() }), - Outcome::Completed(CompletedArm { source_version: 7, id: "0000000000a2".into() }), - Outcome::Denied(id_arm("0000000000a3")), - ], - part: Some(Item::Tool(UsesArm { name: "hammer".into(), uses: 12 })), - crafted: Some(CraftedItem::Part(CountArm { name: "gear".into(), count: 4 })), - missing: None, - } -} - -fn id_arm(id: &str) -> IdArm { - IdArm { id: id.into() } -} - -fn vector(name: &str) -> Vec { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../tests/vectors/union-parity") - .join(name); - std::fs::read(&path).unwrap_or_else(|error| panic!("{}: {error}", path.display())) -} +mod common; +use common::*; fn decode(bytes: &[u8]) -> Result { rmp_serde::from_slice(bytes).map_err(|error| error.to_string()) @@ -325,11 +98,10 @@ fn an_unknown_arm_lists_the_declared_keys_and_never_echoes_the_payload() { #[test] fn a_union_that_is_not_a_key_and_slots_pair_is_refused_naming_the_enum() { - let cases: [(&str, Vec); 4] = [ + let cases: [(&str, Vec); 3] = [ ("an empty array", vec![0x90]), ("a trailing element", rmp_serde::to_vec(&(1u64, (7u8,), 0u8)).unwrap()), ("a string key", rmp_serde::to_vec(&("CANARY-key", (7u8,))).unwrap()), - ("a unit arm with slots", rmp_serde::to_vec(&(2u64, ("CANARY-slot",))).unwrap()), ]; for (label, bytes) in cases { let message = rmp_serde::from_slice::(&bytes).unwrap_err().to_string(); diff --git a/packages/cultnet-rs/src/replication.rs b/packages/cultnet-rs/src/replication.rs index 743a28fd..7816e7dd 100644 --- a/packages/cultnet-rs/src/replication.rs +++ b/packages/cultnet-rs/src/replication.rs @@ -146,6 +146,7 @@ impl CultNetDocumentRegistry { schema_id: binding.schema_id.clone(), schema_names: vec![holder.document_type.clone(), binding.document_type.clone()], record_key: String::new(), + unread_slots: None, })); } self.bindings_by_schema_id