From c92a3741b78f4271fea0b1e6cb550d134e8e8a46 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 02:52:33 +0100 Subject: [PATCH] Thing 2.0 cut 4b fix: decode moves to thing-state (core holds no reader), registration contract enforced and documented, branch tests --- Cargo.lock | 14 +- crates/thing-contract/src/source.rs | 4 +- crates/thing-core/Cargo.toml | 3 - crates/thing-core/src/port/state.rs | 181 +---------------- crates/thing-state/Cargo.toml | 12 ++ crates/thing-state/src/lib.rs | 184 ++++++++++++++++++ .../tests/state_decode.rs | 4 +- crates/thing-testkit/Cargo.toml | 1 + crates/thing-testkit/src/mem_state.rs | 9 +- crates/thing-testkit/tests/state.rs | 45 ++++- 10 files changed, 267 insertions(+), 190 deletions(-) create mode 100644 crates/thing-state/Cargo.toml create mode 100644 crates/thing-state/src/lib.rs rename crates/{thing-core => thing-state}/tests/state_decode.rs (98%) diff --git a/Cargo.lock b/Cargo.lock index 9feb7a4..9cba10e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -499,14 +499,21 @@ dependencies = [ name = "thing-core" version = "0.1.0" dependencies = [ - "cultcache-rs", - "rmp-serde", - "serde", "stacker", "thing-contract", "thing-testkit", ] +[[package]] +name = "thing-state" +version = "0.1.0" +dependencies = [ + "cultcache-rs", + "rmp-serde", + "serde", + "thing-core", +] + [[package]] name = "thing-testkit" version = "0.1.0" @@ -517,6 +524,7 @@ dependencies = [ "serde", "thing-contract", "thing-core", + "thing-state", ] [[package]] diff --git a/crates/thing-contract/src/source.rs b/crates/thing-contract/src/source.rs index c304068..0a3cad0 100644 --- a/crates/thing-contract/src/source.rs +++ b/crates/thing-contract/src/source.rs @@ -81,7 +81,9 @@ pub enum StateSource { Item, } -/// A state record. An absent provider is the publisher of the document. +/// A state record. An absent provider is the publisher of the document. `schema` is the id the +/// provider's record type is registered under in its store: a provider's state type must have its +/// entry type equal to that schema id, because a store names a record's schema by its entry type. #[derive(Clone, Debug, PartialEq, CultSlots)] pub struct StateRef { #[cultcache(key = 0)] diff --git a/crates/thing-core/Cargo.toml b/crates/thing-core/Cargo.toml index 16b5957..d12f760 100644 --- a/crates/thing-core/Cargo.toml +++ b/crates/thing-core/Cargo.toml @@ -8,9 +8,6 @@ publish = false [dependencies] thing-contract = { path = "../thing-contract" } stacker = "0.1.25" -cultcache-rs = { workspace = true } -rmp-serde = { workspace = true } -serde = { workspace = true } [dev-dependencies] thing-testkit = { path = "../thing-testkit" } diff --git a/crates/thing-core/src/port/state.rs b/crates/thing-core/src/port/state.rs index 29dab1b..49f2b8d 100644 --- a/crates/thing-core/src/port/state.rs +++ b/crates/thing-core/src/port/state.rs @@ -1,15 +1,6 @@ -//! The one by-name decode of a provider record. A state port implementation calls `decode` with -//! the record's payload and the catalog member rows of its schema; core's pipeline never sees -//! bytes. The catalog names only a document's top-level members, so below that level a payload -//! decodes by its own shape. - -use std::cell::RefCell; -use std::collections::HashSet; -use std::fmt; -use std::io::Cursor; - -use cultcache_rs::{SchemaCatalogMember, check_payload_depth}; -use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor}; +//! A provider record's value as core sees it. Core holds no bytes and no reader of them: a state +//! port implementation decodes a record with its schema's member names (the `thing-state` crate) +//! and hands core this tree. /// A provider record's value: closed, ordered and named, with no case folding. #[derive(Clone, Debug, PartialEq)] @@ -33,169 +24,3 @@ impl StateValue { } } } - -/// Why a payload is not a `StateValue`. Display names slots, counts and positions, never a value. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum StateDecodeError { - /// The schema published no member rows: a reader cannot name what the writer did not publish. - NoMembers, - NotARecord, - TrailingBytes { count: usize }, - TooDeep, - UndescribedSlot { slot: usize }, - DuplicateKey { position: usize }, - Extension, - Malformed, -} - -impl fmt::Display for StateDecodeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::NoMembers => f.write_str("the schema published no member rows, so its members cannot be named"), - Self::NotARecord => f.write_str("the payload is not one MessagePack array"), - Self::TrailingBytes { count } => write!(f, "{count} bytes follow the record"), - Self::TooDeep => f.write_str("the payload nests deeper than CultCache admits"), - Self::UndescribedSlot { slot } => write!(f, "slot {slot} holds a value no member row names"), - Self::DuplicateKey { position } => write!(f, "the map repeats a key at entry {position}"), - Self::Extension => f.write_str("the payload holds a MessagePack extension value"), - Self::Malformed => f.write_str("the payload is not well-formed MessagePack"), - } - } -} - -impl std::error::Error for StateDecodeError {} - -/// Decode `payload`, one MessagePack array, into a `StateValue::Record` of the rows' member -/// names in slot order. A row whose slot lies past the array's end is `Nil`; a non-nil element at -/// a slot no row names is refused. An empty row list is refused. -pub fn decode(payload: &[u8], members: &[SchemaCatalogMember]) -> Result { - if members.is_empty() { - return Err(StateDecodeError::NoMembers); - } - check_payload_depth(payload).map_err(|_| StateDecodeError::TooDeep)?; - let failure = RefCell::new(None); - let mut reader = rmp_serde::Deserializer::new(Cursor::new(payload)); - let value = match (Shape { failure: &failure }).deserialize(&mut reader) { - Ok(value) => value, - Err(_) => return Err(failure.into_inner().unwrap_or(StateDecodeError::Malformed)), - }; - let StateValue::List(elements) = value else { return Err(StateDecodeError::NotARecord) }; - let count = payload.len() - reader.position() as usize; - if count != 0 { - return Err(StateDecodeError::TrailingBytes { count }); - } - let described: HashSet = members.iter().map(|row| row.slot as usize).collect(); - if let Some(slot) = - elements.iter().enumerate().position(|(slot, value)| !described.contains(&slot) && *value != StateValue::Nil) - { - return Err(StateDecodeError::UndescribedSlot { slot }); - } - let mut rows: Vec<&SchemaCatalogMember> = members.iter().collect(); - rows.sort_by_key(|row| row.slot); - Ok(StateValue::Record( - rows.into_iter() - .map(|row| (row.member_name.clone(), elements.get(row.slot as usize).cloned().unwrap_or(StateValue::Nil))) - .collect(), - )) -} - -/// The shape of a payload below the catalog's reach. A semantic refusal is parked in `failure` -/// and surfaces as the serde error that unwinds the walk. -#[derive(Clone, Copy)] -struct Shape<'a> { - failure: &'a RefCell>, -} - -impl Shape<'_> { - fn refuse(&self, error: StateDecodeError) -> E { - self.failure.borrow_mut().get_or_insert(error); - E::custom("refused") - } -} - -impl<'de> DeserializeSeed<'de> for Shape<'_> { - type Value = StateValue; - - fn deserialize>(self, deserializer: D) -> Result { - deserializer.deserialize_any(self) - } -} - -impl<'de> Visitor<'de> for Shape<'_> { - type Value = StateValue; - - fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str("a MessagePack value") - } - - fn visit_unit(self) -> Result { - Ok(StateValue::Nil) - } - - fn visit_none(self) -> Result { - Ok(StateValue::Nil) - } - - fn visit_bool(self, value: bool) -> Result { - Ok(StateValue::Bool(value)) - } - - fn visit_i64(self, value: i64) -> Result { - Ok(StateValue::Int(value.into())) - } - - fn visit_u64(self, value: u64) -> Result { - Ok(StateValue::Int(value.into())) - } - - fn visit_f32(self, value: f32) -> Result { - Ok(StateValue::Float(value.into())) - } - - fn visit_f64(self, value: f64) -> Result { - Ok(StateValue::Float(value)) - } - - fn visit_str(self, value: &str) -> Result { - Ok(StateValue::Text(value.into())) - } - - fn visit_bytes(self, value: &[u8]) -> Result { - Ok(StateValue::Bytes(value.into())) - } - - fn visit_newtype_struct>(self, _: D) -> Result { - // rmp-serde presents an extension value as a newtype struct. - Err(self.refuse(StateDecodeError::Extension)) - } - - fn visit_seq>(self, mut seq: A) -> Result { - let mut elements = Vec::new(); - while let Some(element) = seq.next_element_seed(self)? { - elements.push(element); - } - Ok(StateValue::List(elements)) - } - - fn visit_map>(self, mut map: A) -> Result { - let mut entries: Vec<(StateValue, StateValue)> = Vec::new(); - while let Some(key) = map.next_key_seed(self)? { - let value = map.next_value_seed(self)?; - entries.push((key, value)); - } - if entries.iter().all(|(key, _)| matches!(key, StateValue::Text(_))) { - let mut seen = HashSet::new(); - let mut members = Vec::with_capacity(entries.len()); - for (position, (key, value)) in entries.into_iter().enumerate() { - let StateValue::Text(name) = key else { unreachable!("every key is text") }; - if !seen.insert(name.clone()) { - return Err(self.refuse(StateDecodeError::DuplicateKey { position })); - } - members.push((name, value)); - } - Ok(StateValue::Record(members)) - } else { - Ok(StateValue::List(entries.into_iter().map(|(key, value)| StateValue::List(vec![key, value])).collect())) - } - } -} diff --git a/crates/thing-state/Cargo.toml b/crates/thing-state/Cargo.toml new file mode 100644 index 0000000..81fe55e --- /dev/null +++ b/crates/thing-state/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "thing-state" +version = "0.1.0" +edition = "2024" +license = "MIT" +publish = false + +[dependencies] +thing-core = { path = "../thing-core" } +cultcache-rs = { workspace = true } +rmp-serde = { workspace = true } +serde = { workspace = true } diff --git a/crates/thing-state/src/lib.rs b/crates/thing-state/src/lib.rs new file mode 100644 index 0000000..425db4c --- /dev/null +++ b/crates/thing-state/src/lib.rs @@ -0,0 +1,184 @@ +//! The one by-name decode of a provider record. A state port implementation (`MemState` now, +//! thing-mesh next) calls `decode` with the record's payload and the catalog member rows of its +//! schema; core never sees bytes. The catalog names only a document's top-level members, so below +//! that level a payload decodes by its own shape. +//! +//! Registration contract: a provider's state record type must be registered with its entry type +//! equal to its schema id (`TYPE == SCHEMA_NAME`). A CultCache store names a record's schema by +//! its entry type, so the id a `Bind` names is the id the store holds only when the two are one +//! string; the member rows a reader finds are the rows published under that id. + +use std::cell::RefCell; +use std::collections::HashSet; +use std::fmt; +use std::io::Cursor; + +use cultcache_rs::{SchemaCatalogMember, check_payload_depth}; +use thing_core::port::StateValue; +use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor}; + +/// Why a payload is not a `StateValue`. Display names slots, counts and positions, never a value. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum StateDecodeError { + /// The schema published no member rows: a reader cannot name what the writer did not publish. + NoMembers, + NotARecord, + TrailingBytes { count: usize }, + TooDeep, + UndescribedSlot { slot: usize }, + DuplicateKey { position: usize }, + Extension, + Malformed, +} + +impl fmt::Display for StateDecodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NoMembers => f.write_str("the schema published no member rows, so its members cannot be named"), + Self::NotARecord => f.write_str("the payload is not one MessagePack array"), + Self::TrailingBytes { count } => write!(f, "{count} bytes follow the record"), + Self::TooDeep => f.write_str("the payload nests deeper than CultCache admits"), + Self::UndescribedSlot { slot } => write!(f, "slot {slot} holds a value no member row names"), + Self::DuplicateKey { position } => write!(f, "the map repeats a key at entry {position}"), + Self::Extension => f.write_str("the payload holds a MessagePack extension value"), + Self::Malformed => f.write_str("the payload is not well-formed MessagePack"), + } + } +} + +impl std::error::Error for StateDecodeError {} + +/// Decode `payload`, one MessagePack array, into a `StateValue::Record` of the rows' member +/// names in slot order. A row whose slot lies past the array's end is `Nil`; a non-nil element at +/// a slot no row names is refused. An empty row list is refused. +pub fn decode(payload: &[u8], members: &[SchemaCatalogMember]) -> Result { + if members.is_empty() { + return Err(StateDecodeError::NoMembers); + } + check_payload_depth(payload).map_err(|_| StateDecodeError::TooDeep)?; + let failure = RefCell::new(None); + let mut reader = rmp_serde::Deserializer::new(Cursor::new(payload)); + let value = match (Shape { failure: &failure }).deserialize(&mut reader) { + Ok(value) => value, + Err(_) => return Err(failure.into_inner().unwrap_or(StateDecodeError::Malformed)), + }; + let StateValue::List(elements) = value else { return Err(StateDecodeError::NotARecord) }; + let count = payload.len() - reader.position() as usize; + if count != 0 { + return Err(StateDecodeError::TrailingBytes { count }); + } + let described: HashSet = members.iter().map(|row| row.slot as usize).collect(); + if let Some(slot) = + elements.iter().enumerate().position(|(slot, value)| !described.contains(&slot) && *value != StateValue::Nil) + { + return Err(StateDecodeError::UndescribedSlot { slot }); + } + let mut rows: Vec<&SchemaCatalogMember> = members.iter().collect(); + rows.sort_by_key(|row| row.slot); + Ok(StateValue::Record( + rows.into_iter() + .map(|row| (row.member_name.clone(), elements.get(row.slot as usize).cloned().unwrap_or(StateValue::Nil))) + .collect(), + )) +} + +/// The shape of a payload below the catalog's reach. A semantic refusal is parked in `failure` +/// and surfaces as the serde error that unwinds the walk. +#[derive(Clone, Copy)] +struct Shape<'a> { + failure: &'a RefCell>, +} + +impl Shape<'_> { + fn refuse(&self, error: StateDecodeError) -> E { + self.failure.borrow_mut().get_or_insert(error); + E::custom("refused") + } +} + +impl<'de> DeserializeSeed<'de> for Shape<'_> { + type Value = StateValue; + + fn deserialize>(self, deserializer: D) -> Result { + deserializer.deserialize_any(self) + } +} + +impl<'de> Visitor<'de> for Shape<'_> { + type Value = StateValue; + + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a MessagePack value") + } + + fn visit_unit(self) -> Result { + Ok(StateValue::Nil) + } + + fn visit_none(self) -> Result { + Ok(StateValue::Nil) + } + + fn visit_bool(self, value: bool) -> Result { + Ok(StateValue::Bool(value)) + } + + fn visit_i64(self, value: i64) -> Result { + Ok(StateValue::Int(value.into())) + } + + fn visit_u64(self, value: u64) -> Result { + Ok(StateValue::Int(value.into())) + } + + fn visit_f32(self, value: f32) -> Result { + Ok(StateValue::Float(value.into())) + } + + fn visit_f64(self, value: f64) -> Result { + Ok(StateValue::Float(value)) + } + + fn visit_str(self, value: &str) -> Result { + Ok(StateValue::Text(value.into())) + } + + fn visit_bytes(self, value: &[u8]) -> Result { + Ok(StateValue::Bytes(value.into())) + } + + fn visit_newtype_struct>(self, _: D) -> Result { + // rmp-serde presents an extension value as a newtype struct. + Err(self.refuse(StateDecodeError::Extension)) + } + + fn visit_seq>(self, mut seq: A) -> Result { + let mut elements = Vec::new(); + while let Some(element) = seq.next_element_seed(self)? { + elements.push(element); + } + Ok(StateValue::List(elements)) + } + + fn visit_map>(self, mut map: A) -> Result { + let mut entries: Vec<(StateValue, StateValue)> = Vec::new(); + while let Some(key) = map.next_key_seed(self)? { + let value = map.next_value_seed(self)?; + entries.push((key, value)); + } + if entries.iter().all(|(key, _)| matches!(key, StateValue::Text(_))) { + let mut seen = HashSet::new(); + let mut members = Vec::with_capacity(entries.len()); + for (position, (key, value)) in entries.into_iter().enumerate() { + let StateValue::Text(name) = key else { unreachable!("every key is text") }; + if !seen.insert(name.clone()) { + return Err(self.refuse(StateDecodeError::DuplicateKey { position })); + } + members.push((name, value)); + } + Ok(StateValue::Record(members)) + } else { + Ok(StateValue::List(entries.into_iter().map(|(key, value)| StateValue::List(vec![key, value])).collect())) + } + } +} diff --git a/crates/thing-core/tests/state_decode.rs b/crates/thing-state/tests/state_decode.rs similarity index 98% rename from crates/thing-core/tests/state_decode.rs rename to crates/thing-state/tests/state_decode.rs index 75df7dc..bf4a1ae 100644 --- a/crates/thing-core/tests/state_decode.rs +++ b/crates/thing-state/tests/state_decode.rs @@ -1,9 +1,9 @@ -//! `port::state::decode`: each StateValue arm, the slot rules, and the refusals. Payloads are +//! `thing_state::decode`: each StateValue arm, the slot rules, and the refusals. Payloads are //! written byte by byte so the test does not lean on the encoder it checks. use cultcache_rs::SchemaCatalogMember; use thing_core::port::StateValue::{self, *}; -use thing_core::port::state::{StateDecodeError, decode}; +use thing_state::{StateDecodeError, decode}; const CANARY: &str = "CANARY-7f3a91c2"; diff --git a/crates/thing-testkit/Cargo.toml b/crates/thing-testkit/Cargo.toml index 1ad3bee..c184cd1 100644 --- a/crates/thing-testkit/Cargo.toml +++ b/crates/thing-testkit/Cargo.toml @@ -9,6 +9,7 @@ publish = false thing-contract = { path = "../thing-contract" } cultcache-rs = { workspace = true } thing-core = { path = "../thing-core" } +thing-state = { path = "../thing-state" } anyhow = { workspace = true } rmp-serde = { workspace = true } serde = { workspace = true } diff --git a/crates/thing-testkit/src/mem_state.rs b/crates/thing-testkit/src/mem_state.rs index b50f8fb..26ce94c 100644 --- a/crates/thing-testkit/src/mem_state.rs +++ b/crates/thing-testkit/src/mem_state.rs @@ -4,7 +4,7 @@ //! record or a delete replaces it. //! //! A provider's own state (any schema outside the contract) is held per (provider, key), one record -//! per key as CultCache holds them, already decoded by `thing_core::port::state::decode` with +//! per key as CultCache holds them, already decoded by `thing_state::decode` with //! the schema's catalog member rows. A payload that decode refuses is held as a refusal. use std::cell::RefCell; @@ -16,7 +16,7 @@ use cultcache_rs::{ resolve_schema_entry, }; use thing_contract::*; -use thing_core::port::state::decode; +use thing_state::decode; use thing_core::port::{ Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, StateValue, SubscriptionId, }; @@ -192,6 +192,11 @@ impl MemState { /// Store provider state `value` under `key` at `provider`: the type's own schema and member /// rows decode it, as a store written by this type would. pub fn put_state(&mut self, provider: &ProviderId, key: &str, value: &T) { + assert_eq!( + T::TYPE, + T::SCHEMA_NAME, + "a provider state type must be registered with its entry type equal to its schema id" + ); let mut cache = CultCache::new(); cache.register_entry_type::().unwrap(); let payload = cache.prepare_entry(key, value).unwrap().0.payload; diff --git a/crates/thing-testkit/tests/state.rs b/crates/thing-testkit/tests/state.rs index 2a34eac..6166faa 100644 --- a/crates/thing-testkit/tests/state.rs +++ b/crates/thing-testkit/tests/state.rs @@ -3,7 +3,7 @@ use cultcache_rs::DatabaseEntry; use thing_contract::{ProviderId, SchemaId}; -use thing_core::port::state::StateDecodeError; +use thing_state::StateDecodeError; use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, StatePort, StateValue}; use thing_testkit::fixture::Fixture; use thing_testkit::mem_state::MemState; @@ -176,3 +176,46 @@ fn delete_queues_only_under_a_matching_interest_and_only_for_what_was_held() { "{changes:?}" ); } + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "gamecult.thing.test.other", schema = "gamecult.thing.test.other.v1")] +struct TypeIsNotTheSchemaId { + #[cultcache(key = 0)] + id: String, +} + +#[test] +#[should_panic(expected = "entry type equal to its schema id")] +fn put_state_refuses_a_type_that_is_not_its_schema_id() { + MemState::new().put_state(&ProviderId::new(PROVIDER), "k", &TypeIsNotTheSchemaId { id: "x".into() }); +} + +#[test] +#[should_panic(expected = "is a contract kind")] +fn put_state_raw_refuses_a_contract_schema() { + let mut state = MemState::new(); + state.put_state_raw(at("gamecult.thing.surface.v1", "k"), vec![0x90], &Swarm::schema_members()); +} + +#[test] +fn load_store_names_a_record_by_its_schema_id_when_it_has_one() { + // The schema id the store carries is the record's schema, whatever its entry type is called. + let dir = std::env::temp_dir().join(format!("thing-state-alias-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("alias.cc"); + let bytes = thing_testkit::store::bytes(|cache| { + cache.register_entry_type::().unwrap(); + let swarm = Swarm { id: "a".into(), name: "n".into(), load: 1.0 }; + let (mut envelope, _) = cache.prepare_entry("k", &swarm).unwrap(); + envelope.stored_at = thing_testkit::store::PINNED_CLOCK.into(); + envelope.schema_id = Some("gamecult.thing.test.alias.v1".into()); + cache.put_envelope::(envelope).unwrap(); + }); + std::fs::write(&path, bytes).unwrap(); + let mut state = MemState::new(); + state.load_store(&ProviderId::new(PROVIDER), &path); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(state.read(&at(SWARM_SCHEMA, "k")), Lookup::Absent); + let found = state.read(&at("gamecult.thing.test.alias.v1", "k")); + assert!(matches!(found, Lookup::Refused(_) | Lookup::Present(_)), "{found:?}"); +}