diff --git a/Cargo.lock b/Cargo.lock index 9628970..9feb7a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -499,6 +499,9 @@ dependencies = [ name = "thing-core" version = "0.1.0" dependencies = [ + "cultcache-rs", + "rmp-serde", + "serde", "stacker", "thing-contract", "thing-testkit", @@ -511,6 +514,7 @@ dependencies = [ "anyhow", "cultcache-rs", "rmp-serde", + "serde", "thing-contract", "thing-core", ] diff --git a/crates/thing-core/Cargo.toml b/crates/thing-core/Cargo.toml index d12f760..16b5957 100644 --- a/crates/thing-core/Cargo.toml +++ b/crates/thing-core/Cargo.toml @@ -8,6 +8,9 @@ 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.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..29dab1b --- /dev/null +++ b/crates/thing-core/src/port/state.rs @@ -0,0 +1,201 @@ +//! 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: 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, + } + } +} + +/// 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-core/tests/state_decode.rs new file mode 100644 index 0000000..75df7dc --- /dev/null +++ b/crates/thing-core/tests/state_decode.rs @@ -0,0 +1,192 @@ +//! `port::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}; + +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..1ad3bee 100644 --- a/crates/thing-testkit/Cargo.toml +++ b/crates/thing-testkit/Cargo.toml @@ -11,4 +11,5 @@ cultcache-rs = { workspace = true } thing-core = { path = "../thing-core" } anyhow = { workspace = true } rmp-serde = { workspace = true } +serde = { workspace = true } diff --git a/crates/thing-testkit/src/lib.rs b/crates/thing-testkit/src/lib.rs index 1107328..a7d5d18 100644 --- a/crates/thing-testkit/src/lib.rs +++ b/crates/thing-testkit/src/lib.rs @@ -5,4 +5,5 @@ pub mod build; pub mod fixture; pub mod golden; pub mod mem_state; +pub mod state; pub mod store; diff --git a/crates/thing-testkit/src/mem_state.rs b/crates/thing-testkit/src/mem_state.rs index b649c4e..935861a 100644 --- a/crates/thing-testkit/src/mem_state.rs +++ b/crates/thing-testkit/src/mem_state.rs @@ -2,13 +2,24 @@ //! contract registered, so a typed value and a raw payload meet one decode door. A payload the //! contract refuses is never stored: the address becomes refused, and stays refused until a //! 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 +//! the schema's catalog member rows. A payload that decode refuses is held as a refusal. use std::cell::RefCell; use std::collections::HashMap; +use std::path::Path; -use cultcache_rs::{CultCache, CultCacheEnvelope, DatabaseEntry}; +use cultcache_rs::{ + CacheBackingStore, CultCache, CultCacheEnvelope, DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore, + resolve_schema_entry, +}; use thing_contract::*; -use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, SubscriptionId}; +use thing_core::port::state::decode; +use thing_core::port::{ + Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, StateValue, SubscriptionId, +}; use crate::store; @@ -74,8 +85,29 @@ pub enum Call { Drain, } +/// What a provider key holds of provider state. +#[derive(Clone)] +enum Held { + Value { schema: SchemaId, value: StateValue }, + Refused(Refusal), +} + +impl Held { + fn schema(&self) -> &SchemaId { + match self { + Held::Value { schema, .. } => schema, + Held::Refused(refusal) => &refusal.kind, + } + } +} + +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 +125,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 +177,71 @@ 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) { + 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 { + let schema = SchemaId::new(envelope.schema_id.clone().unwrap_or_else(|| envelope.r#type.clone())); + let address = Address { provider: provider.clone(), schema, key: RecordKey::new(envelope.key) }; + if is_contract(&address.schema) { + self.put_raw(address, envelope.payload); + } else { + let rows = resolve_schema_entry(&catalog, address.schema.as_str()).map(|entry| entry.members.clone()); + 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 +295,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 +314,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 +330,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 +356,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..3525c77 --- /dev/null +++ b/crates/thing-testkit/src/state.rs @@ -0,0 +1,154 @@ +//! 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. + +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", 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"; + const SCHEMA_NAME: &'static str = "gamecult.thing.test.swarm.v1"; +} + +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache(type = "gamecult.thing.test.target", 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", 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", 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", 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..2a34eac --- /dev/null +++ b/crates/thing-testkit/tests/state.rs @@ -0,0 +1,178 @@ +//! 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_core::port::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:?}" + ); +}