From 491fc2020f7dfcfbb798c84d1ccd649fe2f340f4 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sat, 28 Nov 2026 02:05:00 +0000 Subject: [PATCH] Thing 2.0: state port values (StateValue, Record::State) and thing-state's by-name decode (#12) --- Cargo.lock | 12 + crates/thing-contract/src/lib.rs | 6 + crates/thing-contract/src/source.rs | 4 +- .../thing-core/src/{port.rs => port/mod.rs} | 9 +- crates/thing-core/src/port/state.rs | 26 ++ crates/thing-state/Cargo.toml | 12 + crates/thing-state/src/lib.rs | 184 +++++++++++++++ crates/thing-state/tests/state_decode.rs | 192 +++++++++++++++ crates/thing-testkit/Cargo.toml | 2 + crates/thing-testkit/fixtures/README.md | 4 +- .../state-swarm-members-empty.state.cc | 3 + .../fixtures/state-swarm.state.cc | Bin 0 -> 1105 bytes crates/thing-testkit/src/lib.rs | 1 + crates/thing-testkit/src/mem_state.rs | 156 +++++++++++- crates/thing-testkit/src/state.rs | 157 ++++++++++++ crates/thing-testkit/tests/state.rs | 223 ++++++++++++++++++ 16 files changed, 981 insertions(+), 10 deletions(-) rename crates/thing-core/src/{port.rs => port/mod.rs} (92%) create mode 100644 crates/thing-core/src/port/state.rs create mode 100644 crates/thing-state/Cargo.toml create mode 100644 crates/thing-state/src/lib.rs create mode 100644 crates/thing-state/tests/state_decode.rs create mode 100644 crates/thing-testkit/fixtures/state-swarm-members-empty.state.cc create mode 100644 crates/thing-testkit/fixtures/state-swarm.state.cc create mode 100644 crates/thing-testkit/src/state.rs create mode 100644 crates/thing-testkit/tests/state.rs diff --git a/Cargo.lock b/Cargo.lock index 9628970..9cba10e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -504,6 +504,16 @@ dependencies = [ "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" @@ -511,8 +521,10 @@ dependencies = [ "anyhow", "cultcache-rs", "rmp-serde", + "serde", "thing-contract", "thing-core", + "thing-state", ] [[package]] diff --git a/crates/thing-contract/src/lib.rs b/crates/thing-contract/src/lib.rs index 39c72a0..602e81a 100644 --- a/crates/thing-contract/src/lib.rs +++ b/crates/thing-contract/src/lib.rs @@ -8,6 +8,12 @@ //! `Deserialize` (CultCache's `DatabaseEntry` requires it). The domains therefore live in the //! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same //! `new` the constructors call, so no door skips a check. +//! +//! Stack hazard: `Node` nests without a bound of its own, and serde's `Deserialize` recurses +//! once per level, so a hostile payload nested deep enough overflows the stack of a caller that +//! decodes it directly. CultCache refuses such a payload on read and on write +//! (`cultcache_rs::check_payload_depth`, 256 containers); a caller that decodes bytes outside a +//! CultCache must run that check first. mod asset; mod command; 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/src/port.rs b/crates/thing-core/src/port/mod.rs similarity index 92% rename from crates/thing-core/src/port.rs rename to crates/thing-core/src/port/mod.rs index 9687fba..1ae2ae8 100644 --- a/crates/thing-core/src/port.rs +++ b/crates/thing-core/src/port/mod.rs @@ -1,6 +1,10 @@ //! What core may ask of state. The port reads and queues changes; nothing in it writes, and //! it never awaits: core drains queued changes inside its frame. +pub mod state; + +pub use state::StateValue; + use thing_contract::{AssetCatalog, CommandResult, CompositionDocument, ProviderId, RecordKey, SchemaId, SurfaceDocument}; /// One record: the provider that holds it, its schema and its key. @@ -46,13 +50,16 @@ impl Interest { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct SubscriptionId(pub u64); -/// A contract record the port carries, decoded. +/// A record the port carries, decoded: a contract kind, or a provider's state by its schema's +/// member names. `State::schema` is the schema the record is stored under, which is not the +/// one asked for when the key holds a record of another. #[derive(Clone, Debug, PartialEq)] pub enum Record { Surface(SurfaceDocument), Composition(CompositionDocument), Result(CommandResult), Catalog(AssetCatalog), + State { schema: SchemaId, value: StateValue }, } #[derive(Clone, Debug, PartialEq)] diff --git a/crates/thing-core/src/port/state.rs b/crates/thing-core/src/port/state.rs new file mode 100644 index 0000000..49f2b8d --- /dev/null +++ b/crates/thing-core/src/port/state.rs @@ -0,0 +1,26 @@ +//! 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)] +pub enum StateValue { + Nil, + Bool(bool), + Int(i128), + Float(f64), + Text(String), + Bytes(Vec), + List(Vec), + Record(Vec<(String, StateValue)>), +} + +impl StateValue { + /// The member of a `Record` by exact name; `None` for any other shape or a missing name. + pub fn member(&self, name: &str) -> Option<&StateValue> { + match self { + StateValue::Record(members) => members.iter().find(|(member, _)| member == name).map(|(_, value)| value), + _ => None, + } + } +} 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-state/tests/state_decode.rs b/crates/thing-state/tests/state_decode.rs new file mode 100644 index 0000000..bf4a1ae --- /dev/null +++ b/crates/thing-state/tests/state_decode.rs @@ -0,0 +1,192 @@ +//! `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_state::{StateDecodeError, decode}; + +const CANARY: &str = "CANARY-7f3a91c2"; + +fn rows(names: &[&str]) -> Vec { + names + .iter() + .enumerate() + .map(|(slot, name)| SchemaCatalogMember { + slot: slot as u32, + member_name: (*name).into(), + type_name: "System.Object".into(), + is_reference: false, + is_many: false, + target_schema_name: None, + is_name: false, + index_alias: None, + }) + .collect() +} + +fn array(elements: &[Vec]) -> Vec { + assert!(elements.len() < 16); + let mut bytes = vec![0x90 | elements.len() as u8]; + bytes.extend(elements.iter().flatten()); + bytes +} + +fn map(pairs: &[(Vec, Vec)]) -> Vec { + let mut bytes = vec![0x80 | pairs.len() as u8]; + for (key, value) in pairs { + bytes.extend(key); + bytes.extend(value); + } + bytes +} + +fn text(value: &str) -> Vec { + let mut bytes = vec![0xa0 | value.len() as u8]; + bytes.extend(value.as_bytes()); + bytes +} + +fn int(value: u8) -> Vec { + assert!(value < 0x80); + vec![value] +} + +fn nil() -> Vec { + vec![0xc0] +} + +fn nested(levels: usize) -> Vec { + let mut bytes = vec![0x91; levels - 1]; + bytes.push(0x90); + bytes +} + +fn record(pairs: &[(&str, StateValue)]) -> StateValue { + Record(pairs.iter().map(|(name, value)| ((*name).to_string(), value.clone())).collect()) +} + +#[test] +fn every_arm_decodes_by_the_rows_names() { + let f64_bytes = [vec![0xcb], 2.5f64.to_be_bytes().to_vec()].concat(); + let f32_bytes = [vec![0xca], 1.5f32.to_be_bytes().to_vec()].concat(); + let u64_max = [vec![0xcf], vec![0xff; 8]].concat(); + let i64_min = [vec![0xd3], i64::MIN.to_be_bytes().to_vec()].concat(); + let payload = array(&[ + nil(), + vec![0xc3], + u64_max, + i64_min, + f64_bytes, + f32_bytes, + text("hi"), + vec![0xc4, 2, 9, 8], + array(&[int(1), int(2)]), + map(&[(text("x"), int(1)), (text("y"), nil())]), + map(&[(int(1), text("one")), (text("k"), int(2))]), + ]); + let names = ["Nil", "Bool", "Max", "Min", "F64", "F32", "Text", "Bytes", "List", "Rec", "PairList"]; + let decoded = decode(&payload, &rows(&names)).unwrap(); + assert_eq!( + decoded, + record(&[ + ("Nil", Nil), + ("Bool", Bool(true)), + ("Max", Int(u64::MAX as i128)), + ("Min", Int(i64::MIN as i128)), + ("F64", Float(2.5)), + ("F32", Float(1.5)), + ("Text", Text("hi".into())), + ("Bytes", Bytes(vec![9, 8])), + ("List", List(vec![Int(1), Int(2)])), + ("Rec", record(&[("x", Int(1)), ("y", Nil)])), + ("PairList", List(vec![List(vec![Int(1), Text("one".into())]), List(vec![Text("k".into()), Int(2)])])), + ]) + ); + assert_eq!(decoded.member("Text"), Some(&Text("hi".into()))); + assert_eq!(decoded.member("text"), None, "names match exactly, with no case folding"); +} + +#[test] +fn a_row_past_the_arrays_end_is_nil() { + let decoded = decode(&array(&[int(7)]), &rows(&["A", "B", "C"])).unwrap(); + assert_eq!(decoded, record(&[("A", Int(7)), ("B", Nil), ("C", Nil)])); +} + +#[test] +fn rows_decode_in_slot_order_whatever_the_order_given() { + let mut given = rows(&["A", "B"]); + given.reverse(); + let decoded = decode(&array(&[int(1), int(2)]), &given).unwrap(); + assert_eq!(decoded, record(&[("A", Int(1)), ("B", Int(2))])); +} + +#[test] +fn a_non_nil_element_at_an_unnamed_slot_is_refused_and_a_nil_one_is_skipped() { + let mut described = rows(&["A", "B", "C"]); + described.remove(1); // slots 0 and 2 + assert_eq!( + decode(&array(&[int(1), int(5), nil()]), &described), + Err(StateDecodeError::UndescribedSlot { slot: 1 }) + ); + assert_eq!(decode(&array(&[int(1), nil(), int(3)]), &described).unwrap(), record(&[("A", Int(1)), ("C", Int(3))])); + assert_eq!(decode(&array(&[int(1), int(2)]), &rows(&["A"])), Err(StateDecodeError::UndescribedSlot { slot: 1 })); +} + +#[test] +fn no_member_rows_refuses_even_a_good_payload() { + assert_eq!(decode(&array(&[int(1)]), &[]), Err(StateDecodeError::NoMembers)); +} + +#[test] +fn the_payload_must_be_one_array_with_nothing_after_it() { + let names = rows(&["A"]); + assert_eq!(decode(&int(1), &names), Err(StateDecodeError::NotARecord)); + assert_eq!(decode(&map(&[(text("A"), int(1))]), &names), Err(StateDecodeError::NotARecord)); + let mut trailing = array(&[int(1)]); + trailing.extend([0xc0, 0xc0, 0xc0]); + assert_eq!(decode(&trailing, &names), Err(StateDecodeError::TrailingBytes { count: 3 })); + assert_eq!(decode(&[0x92, 0x01], &names), Err(StateDecodeError::Malformed)); + assert_eq!(decode(&[], &names), Err(StateDecodeError::Malformed)); +} + +#[test] +fn an_extension_value_is_refused_wherever_it_sits() { + let names = rows(&["A"]); + assert_eq!(decode(&array(&[vec![0xd4, 0x01, 0x00]]), &names), Err(StateDecodeError::Extension)); + assert_eq!(decode(&array(&[array(&[vec![0xd4, 0x01, 0x00]])]), &names), Err(StateDecodeError::Extension)); +} + +#[test] +fn a_repeated_text_key_is_refused_by_position() { + let names = rows(&["A"]); + let twice = map(&[(text("a"), int(1)), (text("b"), int(2)), (text("a"), int(3))]); + assert_eq!(decode(&array(&[twice]), &names), Err(StateDecodeError::DuplicateKey { position: 2 })); + // Distinct keys of different kinds are not duplicates. + let mixed = map(&[(int(1), int(1)), (text("1"), int(2))]); + assert!(decode(&array(&[mixed]), &names).is_ok()); +} + +#[test] +fn nesting_is_bounded_by_cultcaches_depth() { + let names = rows(&["A"]); + assert!(decode(&nested(256), &names).is_ok()); + assert_eq!(decode(&nested(257), &names), Err(StateDecodeError::TooDeep)); +} + +#[test] +fn refusals_never_print_a_value() { + let names = rows(&["A"]); + let secret = text(CANARY); + let cases = [ + array(&[secret.clone(), secret.clone()]), + [array(&[secret.clone()]), vec![0xc0]].concat(), + array(&[map(&[(text(CANARY), int(1)), (text(CANARY), int(2))])]), + array(&[secret.clone(), vec![0xd4, 0x01, 0x00]]), + secret.clone(), + ]; + for payload in cases { + let error = decode(&payload, &names).unwrap_err(); + assert!(!error.to_string().contains(CANARY), "{error}"); + assert!(!format!("{error:?}").contains(CANARY), "{error:?}"); + } +} diff --git a/crates/thing-testkit/Cargo.toml b/crates/thing-testkit/Cargo.toml index f8303c1..c184cd1 100644 --- a/crates/thing-testkit/Cargo.toml +++ b/crates/thing-testkit/Cargo.toml @@ -9,6 +9,8 @@ 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/fixtures/README.md b/crates/thing-testkit/fixtures/README.md index 21ca217..dbc345d 100644 --- a/crates/thing-testkit/fixtures/README.md +++ b/crates/thing-testkit/fixtures/README.md @@ -20,6 +20,8 @@ frozen, and a normal test run only compares and reads them. The rows are the fix | `f11-deep.surface.cc` | One surface: the deepest Box chain whose payload CultCache's `check_payload_depth` accepts, found by the builder | - | | `f11-deep-refused.bin` | The payload of the same chain one Box level deeper, raw: `check_payload_depth` refuses it at depth 257 and so does CultCache. No store can hold it | - | | `f12-text-edge.surface.cc` | One surface of five Text nodes: bidi (Hebrew and Arabic in Latin), CJK wide characters, combining marks, emoji ZWJ sequences, and a paragraph long enough to wrap | - | +| `state-swarm.state.cc` | Provider state, not contract documents: f01's four swarm records (`summary`, `mind-1`..`mind-3`, schema `gamecult.thing.test.swarm.v1`) written with the test type registered, so the store's catalog publishes the member rows `Id`, `Name`, `Load` | - | +| `state-swarm-members-empty.state.cc` | The same four records written through a hand-implemented twin of the type, whose catalog publishes `[]`: every read of it is refused | - | A payload the contract refuses cannot live in a store: f11's refused payload is a raw file here, and an unknown union arm is `crates/thing-contract/tests/goldens/node-unknown-arm.bin`, read in place and fed to @@ -28,5 +30,5 @@ unknown union arm is `crates/thing-contract/tests/goldens/node-unknown-arm.bin`, ## Regenerate `THING_BLESS=1 cargo test -p thing-testkit --test fixtures every_fixture_round_trips` rewrites -the files through `golden::check`, the one bless door; review the diff before committing. Run +the files (the two state stores: `--test state the_committed_stores`) through `golden::check`, the one bless door; review the diff before committing. Run the tests without `THING_BLESS` to compare. diff --git a/crates/thing-testkit/fixtures/state-swarm-members-empty.state.cc b/crates/thing-testkit/fixtures/state-swarm-members-empty.state.cc new file mode 100644 index 0000000..c55bfe6 --- /dev/null +++ b/crates/thing-testkit/fixtures/state-swarm-members-empty.state.cc @@ -0,0 +1,3 @@ +“²cultcache.store.v1‘—¼gamecult.thing.test.swarm.v1¼gamecult.thing.test.swarm.v1¿gamecult.thing.test.swarm.v1.v1¼gamecult.thing.test.swarm.v1Ùl{"schemaName":"gamecult.thing.test.swarm.v1","schemaVersion":"gamecult.thing.test.swarm.v1.v1","members":[]}‘¼gamecult.thing.test.swarm.v1�””¦mind-1¼gamecult.thing.test.swarm.v1´2026-01-01T00:00:00ZÄ“¦mind-1¦EurekaË?Ó× +=p£×”¦mind-2¼gamecult.thing.test.swarm.v1´2026-01-01T00:00:00ZÄ“¦mind-2¥LibbyË?â=p£× +=”¦mind-3¼gamecult.thing.test.swarm.v1´2026-01-01T00:00:00ZÄ“¦mind-3¤KikoË?´záG®{”§summary¼gamecult.thing.test.swarm.v1´2026-01-01T00:00:00ZÄ“§summary¥SwarmË?ÚáG®zá \ No newline at end of file diff --git a/crates/thing-testkit/fixtures/state-swarm.state.cc b/crates/thing-testkit/fixtures/state-swarm.state.cc new file mode 100644 index 0000000000000000000000000000000000000000..cf92c6f7308e35693c952e1385e0a3c10ebc7c84 GIT binary patch literal 1105 zcmc(f!ArtW9LLK`;5o|k&N}9V4g(oM5t4Ms=umWcn@=6?ZL;@PP4SPA33)EHQys!% zkVv;3I|$zFFX^{ArAQ_S5xmRZ_xJt$zQ6Y#b6-?jXDU)Fn5WFNFn^tH-My9(!M?z= zie{8~hAHFe4YCNxk>XpFbCr1#+iGwWq7ZZf0XT_^qH)Qv_8ePOGmRDH&>S2D69vjS z=@L5WCgUU_$r-a|xgr!Wr{*^1 zd<$>bx(-I8h;R3G4MERvht7rzD9z+NM|zPXkpD4>xJZ&W(eE=kFl|N0e|aWX%~s?i zb2}UNx#H80I~t9KqhV*W>mS}SCD!$anJcpy0#Cc$CvZur=yyF31#vGWq+y*2f)uQa z_k*Jn@ &SchemaId { + match self { + Held::Value { schema, .. } => schema, + Held::Refused(refusal) => &refusal.kind, + } + } +} + +/// The schema id of the contract kind whose CultCache entry type is `entry_type`. +fn contract_schema(entry_type: &str) -> Option<&'static str> { + [ + (SurfaceDocument::TYPE, SurfaceDocument::SCHEMA_NAME), + (CompositionDocument::TYPE, CompositionDocument::SCHEMA_NAME), + (CommandResult::TYPE, CommandResult::SCHEMA_NAME), + (AssetCatalog::TYPE, AssetCatalog::SCHEMA_NAME), + ] + .into_iter() + .find_map(|(entry, schema)| (entry == entry_type).then_some(schema)) +} + +fn is_contract(schema: &SchemaId) -> bool { + by_schema!(schema.as_str(), _T => true, else false) +} + pub struct MemState { providers: HashMap, + state: HashMap<(String, String), Held>, refused: HashMap, interests: Vec<(SubscriptionId, Interest)>, next_subscription: u64, @@ -93,6 +137,7 @@ impl MemState { pub fn new() -> Self { Self { providers: HashMap::new(), + state: HashMap::new(), refused: HashMap::new(), interests: Vec::new(), next_subscription: 0, @@ -144,8 +189,79 @@ impl MemState { }, else panic!("no contract record kind has schema {}", address.schema.as_str())) } + /// 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; + let address = Address { provider: provider.clone(), schema: SchemaId::new(T::SCHEMA_NAME), key: RecordKey::new(key) }; + self.put_state_raw(address, payload, &T::schema_members()); + } + + /// Store a provider-state payload under `address`, decoded with the schema's member `rows`. + /// A payload decode refuses makes the key refused, replacing any record it held. + pub fn put_state_raw(&mut self, address: Address, payload: Vec, rows: &[SchemaCatalogMember]) { + assert!(!is_contract(&address.schema), "{} is a contract kind: put_raw", address.schema.as_str()); + let slot = (address.provider.as_str().to_string(), address.key.as_str().to_string()); + match decode(&payload, rows) { + Ok(value) => { + let schema = address.schema.clone(); + self.state.insert(slot, Held::Value { schema: schema.clone(), value: value.clone() }); + self.queue(Change::Upsert(Entry { address, record: Record::State { schema, value } })); + } + Err(error) => { + let detail = format!("{}: {error}", address.schema.as_str()); + let refusal = Refusal { kind: address.schema.clone(), address, detail }; + self.state.insert(slot, Held::Refused(refusal.clone())); + self.queue(Change::Refused(refusal)); + } + } + } + + /// Read a single-file store, routing each record: a contract kind to `put_raw`, anything else + /// to `put_state_raw` with the member rows the store's own catalog publishes for its schema. + /// The store is read from a copy, so the file and its directory are never written. + pub fn load_store(&mut self, provider: &ProviderId, path: &Path) { + let work = store::scratch_dir("load"); + let copy = work.join("store.cc"); + std::fs::copy(path, ©).unwrap(); + let backing = SingleFileMessagePackBackingStore::new(©); + let catalog = backing.pull_schema_catalog().unwrap(); + let mut envelopes = backing.pull_all().unwrap(); + drop(backing); + let _ = std::fs::remove_dir_all(&work); + envelopes.sort_by(|a, b| a.key.cmp(&b.key)); + for envelope in envelopes { + // A store names a record's schema by its entry type: a contract kind's type maps to + // its schema id, and any other type is the schema id of provider state. + let key = RecordKey::new(envelope.key); + if let Some(schema) = contract_schema(&envelope.r#type) { + self.put_raw(Address { provider: provider.clone(), schema: SchemaId::new(schema), key }, envelope.payload); + } else { + let schema = envelope.schema_id.unwrap_or(envelope.r#type); + let rows = resolve_schema_entry(&catalog, &schema).map(|entry| entry.members.clone()); + let address = Address { provider: provider.clone(), schema: SchemaId::new(schema), key }; + self.put_state_raw(address, envelope.payload, &rows.unwrap_or_default()); + } + } + } + /// Remove the record or the refusal at `address`; removing nothing is not a change. pub fn delete(&mut self, address: &Address) { + if !is_contract(&address.schema) { + let slot = (address.provider.as_str().to_string(), address.key.as_str().to_string()); + if self.state.get(&slot).is_some_and(|held| held.schema() == &address.schema) { + self.state.remove(&slot); + self.queue(Change::Delete(address.clone())); + } + return; + } let refused = self.refused.remove(address).is_some(); let stored = by_schema!(address.schema.as_str(), T => { match self.providers.get_mut(address.provider.as_str()) { @@ -199,6 +315,16 @@ impl MemState { impl StatePort for MemState { fn read(&self, address: &Address) -> Lookup { self.calls.borrow_mut().push(Call::Read(address.clone())); + if !is_contract(&address.schema) { + return match self.state.get(&(address.provider.as_str().to_string(), address.key.as_str().to_string())) { + Some(Held::Value { schema, value }) => Lookup::Present(Entry { + address: address.clone(), + record: Record::State { schema: schema.clone(), value: value.clone() }, + }), + Some(Held::Refused(refusal)) => Lookup::Refused(refusal.clone()), + None => Lookup::Absent, + }; + } if let Some(refusal) = self.refused.get(address) { return Lookup::Refused(refusal.clone()); } @@ -208,9 +334,7 @@ impl StatePort for MemState { Some(value) => Lookup::Present(Entry { address: address.clone(), record: value.into_record() }), None => Lookup::Absent, } - // A schema outside the four contract arms reads Absent. Cut 4 replaces this with the provider-state - // answer once thing2:question:provider-state-value is ruled. - }, else Lookup::Absent) + }, else unreachable!("is_contract admitted the schema")) } fn list(&self, prefix: &Prefix) -> Vec { @@ -226,7 +350,24 @@ impl StatePort for MemState { .filter(|refusal| prefix.matches(&refusal.address)) .map(|refusal| (refusal.address.key.as_str().to_string(), Lookup::Refused(refusal.clone()))) .collect(); - by_schema!(prefix.schema.as_str(), T => { + if !is_contract(&prefix.schema) { + for ((provider, key), held) in &self.state { + if provider != prefix.provider.as_str() || !key.starts_with(&prefix.key_prefix) { + continue; + } + match held { + Held::Value { schema, value } if schema == &prefix.schema => { + let record = Record::State { schema: schema.clone(), value: value.clone() }; + found.push((key.clone(), Lookup::Present(Entry { address: at(key), record }))); + } + Held::Refused(refusal) if refusal.kind == prefix.schema => { + found.push((key.clone(), Lookup::Refused(refusal.clone()))); + } + _ => {} + } + } + } else { + by_schema!(prefix.schema.as_str(), T => { if let Some(cache) = self.providers.get(prefix.provider.as_str()) { for (key, value) in cache.get_all_with_keys::().expect("stored records decode") { if key.starts_with(&prefix.key_prefix) { @@ -235,7 +376,8 @@ impl StatePort for MemState { } } } - }, else ()); + }, else unreachable!("is_contract admitted the schema")); + } found.sort_by(|a, b| a.0.cmp(&b.0)); found.into_iter().map(|(_, lookup)| lookup).collect() } diff --git a/crates/thing-testkit/src/state.rs b/crates/thing-testkit/src/state.rs new file mode 100644 index 0000000..7b92911 --- /dev/null +++ b/crates/thing-testkit/src/state.rs @@ -0,0 +1,157 @@ +//! The provider state the fixtures bind: test schemas whose Rust field names, PascalCased, are +//! the member names the fixtures read, and the script that fills a `MemState` with each +//! fixture's records. Fixture builders name these schemas by id; none of them is a contract kind. +//! +//! A CultCache store names a record's schema by its entry type, not by `SCHEMA_NAME`, so each type +//! here is registered under its schema id: the id a Bind names is the id the store holds. + +use cultcache_rs::DatabaseEntry; +use serde::{Deserialize, Serialize}; +use thing_contract::{ProviderId, RecordKey, SchemaId}; +use thing_core::port::Address; + +use crate::fixture::Fixture; +use crate::mem_state::MemState; + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "gamecult.thing.test.swarm.v1", schema = "gamecult.thing.test.swarm.v1")] +pub struct Swarm { + #[cultcache(key = 0)] + pub id: String, + #[cultcache(key = 1)] + pub name: String, + #[cultcache(key = 2)] + pub load: f64, +} + +/// `Swarm`'s twin as today's hand-written crates publish it: the same type, schema and bytes, +/// and no member rows. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct SwarmWithoutRows { + pub id: String, + pub name: String, + pub load: f64, +} + +impl DatabaseEntry for SwarmWithoutRows { + const TYPE: &'static str = "gamecult.thing.test.swarm.v1"; + const SCHEMA_NAME: &'static str = "gamecult.thing.test.swarm.v1"; +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "gamecult.thing.test.target.v1", schema = "gamecult.thing.test.target.v1")] +pub struct Target { + #[cultcache(key = 0)] + pub label: String, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "gamecult.thing.test.settings.v1", schema = "gamecult.thing.test.settings.v1")] +pub struct Settings { + #[cultcache(key = 0)] + pub enabled: bool, + #[cultcache(key = 1)] + pub volume: f64, + #[cultcache(key = 2)] + pub theme: String, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "gamecult.thing.test.item.v1", schema = "gamecult.thing.test.item.v1")] +pub struct Item { + #[cultcache(key = 0)] + pub id: String, + #[cultcache(key = 1)] + pub title: String, +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "gamecult.thing.test.series.v1", schema = "gamecult.thing.test.series.v1")] +pub struct Series { + #[cultcache(key = 0)] + pub values: Vec, +} + +/// The swarm records of f01 and, under the hostile provider, f10's: the three minds and the +/// summary. +pub fn swarm_records() -> Vec<(&'static str, Swarm)> { + let swarm = |id: &str, name: &str, load: f64| Swarm { id: id.into(), name: name.into(), load }; + vec![ + ("summary", swarm("summary", "Swarm", 0.42)), + ("mind-1", swarm("mind-1", "Eureka", 0.31)), + ("mind-2", swarm("mind-2", "Libby", 0.57)), + ("mind-3", swarm("mind-3", "Kiko", 0.08)), + ] +} + +/// Fill `state` with the provider records `fixture`'s surfaces bind. A fixture that binds no +/// provider state adds nothing. +pub fn script(fixture: Fixture, state: &mut MemState) { + match fixture { + Fixture::F01SwarmDashboard => { + let provider = ProviderId::new("provider.swarm"); + for (key, swarm) in swarm_records() { + state.put_state(&provider, key, &swarm); + } + } + Fixture::F03InputTarget => { + state.put_state(&ProviderId::new("provider.muninn"), "cursor", &Target { label: "Ready".into() }); + } + Fixture::F04Form => { + let settings = Settings { enabled: true, volume: 40.0, theme: "dark".into() }; + state.put_state(&ProviderId::new("provider.settings"), "current", &settings); + } + Fixture::F06ScrollList => { + let provider = ProviderId::new("provider.feed"); + for n in 0..1000 { + let id = format!("item-{n:04}"); + state.put_state(&provider, &id, &Item { id: id.clone(), title: format!("Item {n}") }); + } + } + Fixture::F07Plot => { + let series = Series { values: vec![3.0, 5.5, 4.25, 8.0, 6.5] }; + state.put_state(&ProviderId::new("provider.market"), "prices", &series); + } + Fixture::F10Hostile => { + // A swarm record where the hostile surface's Bind asks for nowhere.v1. + let swarm = Swarm { id: "row-1".into(), name: "Elsewhere".into(), load: 0.0 }; + state.put_state(&ProviderId::new("provider.hostile"), "row-1", &swarm); + } + _ => {} + } +} + +/// The address of a record of `schema` at `provider` and `key`. +pub fn address(provider: &str, schema: &str, key: &str) -> Address { + Address { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key: RecordKey::new(key) } +} + +/// The committed store of f01's swarm records, written with `Swarm` registered: its schema +/// publishes member rows. +pub const SWARM_STORE: &str = "state-swarm.state.cc"; + +/// The same records written through `SwarmWithoutRows`: the schema publishes `[]`. +pub const SWARM_STORE_MEMBERS_EMPTY: &str = "state-swarm-members-empty.state.cc"; + +/// Bless or compare the committed swarm store; returns the committed bytes. +pub fn write_swarm_store() -> Vec { + let bytes = crate::store::bytes(|cache| { + cache.register_entry_type::().unwrap(); + for (key, swarm) in swarm_records() { + crate::store::put_pinned(cache, key, &swarm); + } + }); + crate::golden::check(&Fixture::dir(), SWARM_STORE, &bytes) +} + +/// Bless or compare the committed members-`[]` swarm store; returns the committed bytes. +pub fn write_swarm_store_members_empty() -> Vec { + let bytes = crate::store::bytes(|cache| { + cache.register_entry_type::().unwrap(); + for (key, swarm) in swarm_records() { + let twin = SwarmWithoutRows { id: swarm.id, name: swarm.name, load: swarm.load }; + crate::store::put_pinned(cache, key, &twin); + } + }); + crate::golden::check(&Fixture::dir(), SWARM_STORE_MEMBERS_EMPTY, &bytes) +} diff --git a/crates/thing-testkit/tests/state.rs b/crates/thing-testkit/tests/state.rs new file mode 100644 index 0000000..64c21d0 --- /dev/null +++ b/crates/thing-testkit/tests/state.rs @@ -0,0 +1,223 @@ +//! Provider state through MemState: decoded by name from a Rust-written store, refused from a +//! store that published no member rows, and held one record per key as CultCache holds them. + +use cultcache_rs::DatabaseEntry; +use thing_contract::{ProviderId, SchemaId}; +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; +use thing_testkit::state::*; + +use StateValue::*; + +const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1"; +const NOWHERE: &str = "gamecult.thing.test.nowhere.v1"; +const PROVIDER: &str = "provider.swarm"; + +fn at(schema: &str, key: &str) -> Address { + address(PROVIDER, schema, key) +} + +fn prefix(schema: &str, key_prefix: &str) -> Prefix { + Prefix { provider: ProviderId::new(PROVIDER), schema: SchemaId::new(schema), key_prefix: key_prefix.into() } +} + +fn loaded(file: &str) -> MemState { + let mut state = MemState::new(); + state.load_store(&ProviderId::new(PROVIDER), &Fixture::dir().join(file)); + state +} + +fn swarm_value(id: &str, name: &str, load: f64) -> StateValue { + Record(vec![("Id".into(), Text(id.into())), ("Name".into(), Text(name.into())), ("Load".into(), Float(load))]) +} + +#[test] +fn the_committed_stores_are_what_the_crate_writes() { + assert!(!write_swarm_store().is_empty()); + assert!(!write_swarm_store_members_empty().is_empty()); +} + +#[test] +fn a_rust_written_store_reads_by_the_names_it_published() { + let state = loaded(SWARM_STORE); + let found = state.read(&at(SWARM_SCHEMA, "summary")); + let Lookup::Present(entry) = found else { panic!("{found:?}") }; + assert_eq!(entry.address, at(SWARM_SCHEMA, "summary")); + assert_eq!( + entry.record, + Record::State { schema: SchemaId::new(SWARM_SCHEMA), value: swarm_value("summary", "Swarm", 0.42) } + ); + let Record::State { value, .. } = entry.record else { unreachable!() }; + assert_eq!(value.member("Load"), Some(&Float(0.42))); + assert_eq!(state.read(&at(SWARM_SCHEMA, "unused")), Lookup::Absent); + let listed = state.list(&prefix(SWARM_SCHEMA, "mind-")); + let keys: Vec<_> = listed + .iter() + .map(|lookup| match lookup { + Lookup::Present(entry) => entry.address.key.as_str().to_string(), + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(keys, ["mind-1", "mind-2", "mind-3"]); +} + +#[test] +fn a_store_with_no_member_rows_is_refused_never_read_positionally() { + let state = loaded(SWARM_STORE_MEMBERS_EMPTY); + for key in ["summary", "mind-1", "mind-2", "mind-3"] { + let found = state.read(&at(SWARM_SCHEMA, key)); + let Lookup::Refused(refusal) = found else { panic!("{key}: {found:?}") }; + assert_eq!(refusal.kind, SchemaId::new(SWARM_SCHEMA)); + assert!(refusal.detail.contains(SWARM_SCHEMA), "{}", refusal.detail); + assert!(refusal.detail.contains(&StateDecodeError::NoMembers.to_string()), "{}", refusal.detail); + } + let listed = state.list(&prefix(SWARM_SCHEMA, "mind-")); + assert_eq!(listed.len(), 3); + assert!(listed.iter().all(|lookup| matches!(lookup, Lookup::Refused(_))), "{listed:?}"); +} + +#[test] +fn a_script_and_a_store_hold_the_same_records() { + let mut scripted = MemState::new(); + script(Fixture::F01SwarmDashboard, &mut scripted); + let stored = loaded(SWARM_STORE); + for key in ["summary", "mind-1", "mind-2", "mind-3"] { + assert_eq!(scripted.read(&at(SWARM_SCHEMA, key)), stored.read(&at(SWARM_SCHEMA, key)), "{key}"); + } +} + +#[test] +fn another_schema_at_the_key_answers_present_under_its_own_schema() { + let mut state = MemState::new(); + script(Fixture::F10Hostile, &mut state); + let asked = address("provider.hostile", NOWHERE, "row-1"); + let found = state.read(&asked); + let Lookup::Present(entry) = found else { panic!("{found:?}") }; + assert_eq!(entry.address, asked); + let Record::State { schema, .. } = entry.record else { panic!("not state") }; + assert_eq!(schema, SchemaId::new(SWARM_SCHEMA)); + assert_eq!(state.read(&address("provider.hostile", NOWHERE, "row-2")), Lookup::Absent); + // A list names only the records of the schema asked for. + let none = state.list(&Prefix { + provider: ProviderId::new("provider.hostile"), + schema: SchemaId::new(NOWHERE), + key_prefix: String::new(), + }); + assert!(none.is_empty()); +} + +#[test] +fn every_state_script_fills_the_provider_its_fixture_binds() { + let mut feed = MemState::new(); + script(Fixture::F06ScrollList, &mut feed); + let items = feed.list(&Prefix { + provider: ProviderId::new("provider.feed"), + schema: SchemaId::new("gamecult.thing.test.item.v1"), + key_prefix: "item-".into(), + }); + assert_eq!(items.len(), 1000); + let Lookup::Present(first) = &items[0] else { panic!() }; + assert_eq!(first.address.key.as_str(), "item-0000"); + for (fixture, provider, schema, key, member) in [ + (Fixture::F03InputTarget, "provider.muninn", "target", "cursor", "Label"), + (Fixture::F04Form, "provider.settings", "settings", "current", "Volume"), + (Fixture::F07Plot, "provider.market", "series", "prices", "Values"), + ] { + let mut state = MemState::new(); + script(fixture, &mut state); + let found = state.read(&address(provider, &format!("gamecult.thing.test.{schema}.v1"), key)); + let Lookup::Present(Entry { record: Record::State { value, .. }, .. }) = found else { + panic!("{schema}: {found:?}") + }; + assert!(value.member(member).is_some(), "{schema}.{member}"); + } +} + +#[test] +fn a_refused_put_replaces_an_older_good_record() { + let mut state = MemState::new(); + let key = at(SWARM_SCHEMA, "summary"); + state.subscribe(Interest::Record(key.clone())); + let swarm = Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.5 }; + state.put_state(&ProviderId::new(PROVIDER), "summary", &swarm); + assert!(matches!(state.read(&key), Lookup::Present(_))); + state.put_state_raw(key.clone(), vec![0xc1], &Swarm::schema_members()); + let Lookup::Refused(refusal) = state.read(&key) else { panic!("not refused") }; + assert_eq!(refusal.address, key); + // Refused whichever schema is asked at that key. + assert!(matches!(state.read(&at(NOWHERE, "summary")), Lookup::Refused(_))); + let changes = state.drain(); + assert!(matches!(changes.as_slice(), [Change::Upsert(_), Change::Refused(_)]), "{changes:?}"); + // A good record replaces the refusal. + state.put_state(&ProviderId::new(PROVIDER), "summary", &swarm); + assert!(matches!(state.read(&key), Lookup::Present(_))); +} + +#[test] +fn delete_queues_only_under_a_matching_interest_and_only_for_what_was_held() { + let mut state = MemState::new(); + let key = at(SWARM_SCHEMA, "summary"); + state.subscribe(Interest::Prefix(prefix(SWARM_SCHEMA, "sum"))); + let swarm = Swarm { id: "s".into(), name: "n".into(), load: 0.0 }; + state.put_state(&ProviderId::new(PROVIDER), "summary", &swarm); + state.put_state(&ProviderId::new(PROVIDER), "mind-1", &swarm); + state.delete(&at(NOWHERE, "summary")); // another schema's address: nothing held there + assert!(matches!(state.read(&key), Lookup::Present(_))); + state.delete(&key); + state.delete(&key); // already gone + state.delete(&at(SWARM_SCHEMA, "mind-1")); // held, but no interest + assert_eq!(state.read(&key), Lookup::Absent); + assert_eq!(state.read(&at(SWARM_SCHEMA, "mind-1")), Lookup::Absent); + let changes = state.drain(); + assert!( + matches!(changes.as_slice(), [Change::Upsert(_), Change::Delete(deleted)] if *deleted == key), + "{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); + // No member rows are published under the alias, so the record is refused under it; read + // by its entry type it would have decoded. + let found = state.read(&at("gamecult.thing.test.alias.v1", "k")); + let Lookup::Refused(refusal) = found else { panic!("{found:?}") }; + assert_eq!(refusal.kind, SchemaId::new("gamecult.thing.test.alias.v1")); +}