From 0841c0dd8b8b5a73bd73076039ea7a23048055eb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 27 Nov 2026 20:38:17 +0100 Subject: [PATCH] thing-core StatePort and thing-testkit MemState, fixture builders (thing2 cut 2) StatePort reads, lists, subscribes and drains queued changes and has no writer; a refusal is Lookup::Refused / Change::Refused, never absence. MemState is the CultCache-backed fake with a call log; the Fixture enum builds f01, f09 and f10 and loads their frozen stores. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 10 + crates/thing-core/Cargo.toml | 9 + crates/thing-core/src/lib.rs | 4 + crates/thing-core/src/port.rs | 102 ++++++++ crates/thing-testkit/Cargo.toml | 5 + crates/thing-testkit/src/fixture.rs | 323 ++++++++++++++++++++++++ crates/thing-testkit/src/lib.rs | 2 + crates/thing-testkit/src/mem_state.rs | 258 +++++++++++++++++++ crates/thing-testkit/src/store.rs | 13 +- crates/thing-testkit/tests/fixtures.rs | 161 ++++++++++++ crates/thing-testkit/tests/golden.rs | 59 +++++ crates/thing-testkit/tests/mem_state.rs | 245 ++++++++++++++++++ 12 files changed, 1187 insertions(+), 4 deletions(-) create mode 100644 crates/thing-core/Cargo.toml create mode 100644 crates/thing-core/src/lib.rs create mode 100644 crates/thing-core/src/port.rs create mode 100644 crates/thing-testkit/src/fixture.rs create mode 100644 crates/thing-testkit/src/mem_state.rs create mode 100644 crates/thing-testkit/tests/fixtures.rs create mode 100644 crates/thing-testkit/tests/golden.rs create mode 100644 crates/thing-testkit/tests/mem_state.rs diff --git a/Cargo.lock b/Cargo.lock index c4f3b61..c9fe90f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -381,12 +381,22 @@ dependencies = [ "thing-testkit", ] +[[package]] +name = "thing-core" +version = "0.1.0" +dependencies = [ + "thing-contract", +] + [[package]] name = "thing-testkit" version = "0.1.0" dependencies = [ + "anyhow", "cultcache-rs", + "rmp-serde", "thing-contract", + "thing-core", ] [[package]] diff --git a/crates/thing-core/Cargo.toml b/crates/thing-core/Cargo.toml new file mode 100644 index 0000000..d5fb718 --- /dev/null +++ b/crates/thing-core/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "thing-core" +version = "0.1.0" +edition = "2024" +license = "MIT" +publish = false + +[dependencies] +thing-contract = { path = "../thing-contract" } diff --git a/crates/thing-core/src/lib.rs b/crates/thing-core/src/lib.rs new file mode 100644 index 0000000..5b2775a --- /dev/null +++ b/crates/thing-core/src/lib.rs @@ -0,0 +1,4 @@ +//! Thing's core: a function of documents, state, input and time. It touches the world only +//! through ports; it reads no clock, spawns nothing and awaits nothing. + +pub mod port; diff --git a/crates/thing-core/src/port.rs b/crates/thing-core/src/port.rs new file mode 100644 index 0000000..40a77c2 --- /dev/null +++ b/crates/thing-core/src/port.rs @@ -0,0 +1,102 @@ +//! 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. + +use thing_contract::{AssetCatalog, CommandResult, CompositionDocument, ProviderId, RecordKey, SchemaId, SurfaceDocument}; + +/// One record: the provider that holds it, its schema and its key. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Address { + pub provider: ProviderId, + pub schema: SchemaId, + pub key: RecordKey, +} + +/// Every record of one provider and schema whose key starts with `key_prefix`. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Prefix { + pub provider: ProviderId, + pub schema: SchemaId, + pub key_prefix: String, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum Interest { + Record(Address), + Prefix(Prefix), +} + +impl Prefix { + pub fn matches(&self, address: &Address) -> bool { + self.provider == address.provider + && self.schema == address.schema + && address.key.as_str().starts_with(&self.key_prefix) + } +} + +impl Interest { + /// Whether a change at `address` is of interest. + pub fn matches(&self, address: &Address) -> bool { + match self { + Interest::Record(record) => record == address, + Interest::Prefix(prefix) => prefix.matches(address), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct SubscriptionId(pub u64); + +/// A contract record the port carries, decoded. +#[derive(Clone, Debug, PartialEq)] +pub enum Record { + Surface(SurfaceDocument), + Composition(CompositionDocument), + Result(CommandResult), + Catalog(AssetCatalog), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Entry { + pub address: Address, + pub record: Record, +} + +/// A record the contract refused. `detail` is the decoder's message, which never carries a +/// value. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Refusal { + pub address: Address, + pub kind: SchemaId, + pub detail: String, +} + +/// The answer for one address. A refusal is never absence. +#[derive(Clone, Debug, PartialEq)] +pub enum Lookup { + Present(Entry), + Absent, + Refused(Refusal), +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Change { + Upsert(Entry), + Delete(Address), + Refused(Refusal), +} + +/// Core's view of state. Object safe, and no method writes. +pub trait StatePort { + fn read(&self, address: &Address) -> Lookup; + + /// One lookup per record under the prefix, in key order. + fn list(&self, prefix: &Prefix) -> Vec; + + fn subscribe(&mut self, interest: Interest) -> SubscriptionId; + + fn unsubscribe(&mut self, id: SubscriptionId); + + /// Every change since the last drain that some live interest matches, in mutation order, + /// each once. + fn drain(&mut self) -> Vec; +} diff --git a/crates/thing-testkit/Cargo.toml b/crates/thing-testkit/Cargo.toml index 7886d45..523c1c2 100644 --- a/crates/thing-testkit/Cargo.toml +++ b/crates/thing-testkit/Cargo.toml @@ -8,3 +8,8 @@ publish = false [dependencies] thing-contract = { path = "../thing-contract" } cultcache-rs = { workspace = true } +thing-core = { path = "../thing-core" } +anyhow = { workspace = true } + +[dev-dependencies] +rmp-serde = { workspace = true } diff --git a/crates/thing-testkit/src/fixture.rs b/crates/thing-testkit/src/fixture.rs new file mode 100644 index 0000000..8cf2585 --- /dev/null +++ b/crates/thing-testkit/src/fixture.rs @@ -0,0 +1,323 @@ +//! The frozen fixture stores: typed contract documents built here, encoded through CultCache +//! under a pinned clock, committed under `fixtures/`, and loaded back through the same door +//! every consumer uses. `THING_BLESS=1` through `golden::check` is the only writer. + +use std::path::PathBuf; + +use thing_contract::*; + +use crate::build::*; +use crate::{golden, store}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Fixture { + F01SwarmDashboard, + F09CompositionStack, + F10Hostile, +} + +/// The documents of one fixture, each kind in record-key order. +#[derive(Clone, Debug, PartialEq)] +pub struct FixtureSet { + pub surfaces: Vec, + pub compositions: Vec, + pub catalogs: Vec, +} + +impl FixtureSet { + fn new( + mut surfaces: Vec, + mut compositions: Vec, + mut catalogs: Vec, + ) -> Self { + surfaces.sort_by_key(SurfaceDocument::record_key); + compositions.sort_by_key(CompositionDocument::record_key); + catalogs.sort_by_key(AssetCatalog::record_key); + Self { surfaces, compositions, catalogs } + } +} + +impl Fixture { + pub const ALL: [Fixture; 3] = [Fixture::F01SwarmDashboard, Fixture::F09CompositionStack, Fixture::F10Hostile]; + + pub fn file_name(self) -> &'static str { + match self { + Fixture::F01SwarmDashboard => "f01-swarm-dashboard.surface.cc", + Fixture::F09CompositionStack => "f09-composition-stack.surface.cc", + Fixture::F10Hostile => "f10-hostile.surface.cc", + } + } + + pub fn dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures") + } + + /// The documents the builders produce. + pub fn build(self) -> FixtureSet { + match self { + Fixture::F01SwarmDashboard => FixtureSet::new(vec![swarm_dashboard()], vec![], vec![]), + Fixture::F09CompositionStack => FixtureSet::new(vec![composition_stack()], vec![stack_card()], vec![]), + Fixture::F10Hostile => FixtureSet::new(hostile(), vec![hostile_dup()], vec![]), + } + } + + /// Encode the built documents into a store and bless or compare the committed file. + pub fn write(self) { + let scratch = std::env::temp_dir().join(format!("thing-testkit-{}-{}", std::process::id(), self.file_name())); + let mut cache = store::create(&scratch); + let set = self.build(); + for surface in &set.surfaces { + store::put_pinned(&mut cache, &surface.record_key(), surface); + } + for composition in &set.compositions { + store::put_pinned(&mut cache, &composition.record_key(), composition); + } + for catalog in &set.catalogs { + store::put_pinned(&mut cache, &catalog.record_key(), catalog); + } + let bytes = std::fs::read(&scratch).unwrap(); + let _ = std::fs::remove_file(&scratch); + golden::check(&Self::dir(), self.file_name(), &bytes); + } + + /// The committed store, decoded through the contract. + pub fn load(self) -> FixtureSet { + let cache = store::open(&Self::dir().join(self.file_name())); + FixtureSet::new(cache.get_all().unwrap(), cache.get_all().unwrap(), cache.get_all().unwrap()) + } +} + +const SWARM: &str = "provider.swarm"; +const SWARM_SCHEMA: &str = "gamecult.thing.test.swarm.v1"; + +fn swarm_ref(key: &str) -> StateSource { + StateSource::Record(StateRef { + provider: Some(ProviderId::new(SWARM)), + schema: SchemaId::new(SWARM_SCHEMA), + key: RecordKey::new(key), + }) +} + +fn swarm_dashboard() -> SurfaceDocument { + let load = Bind { + source: swarm_ref("summary"), + member: path(&["load"]), + format: Some(Format::Number(NumberFormat { precision: count(1), percent: true, unit: None })), + }; + let load_text = Node::Text(TextNode { + common: common("load"), + content: TextSource::Bound(load), + style_token: "title".into(), + wrap: false, + max_lines: Some(count(1)), + selectable: false, + }); + let minds = Node::Repeat(RepeatNode { + common: common("minds"), + collection: CollectionSource::Records(RecordsSource { + provider: Some(ProviderId::new(SWARM)), + schema: SchemaId::new(SWARM_SCHEMA), + key_prefix: "mind-".into(), + }), + key_member: path(&["id"]), + template: std::boxed::Box::new(Node::Text(TextNode { + common: common("mind-name"), + content: TextSource::Bound(item_bind(path(&["name"]))), + style_token: "body".into(), + wrap: false, + max_lines: Some(count(1)), + selectable: true, + })), + }); + let restart = Node::Button(ButtonNode { + common: common("restart"), + content: vec![text("restart-label", "Restart")], + on_activate: command("restart"), + enabled: lit_bool(true), + }); + let mut grid = style(); + grid.display = Display::Grid; + grid.grid_columns = vec![Dimension::Percent(Scalar { value: 50.0 }), Dimension::Percent(Scalar { value: 50.0 })]; + grid.grid_rows = vec![Dimension::Auto, Dimension::Auto]; + let root = Node::Box(BoxNode { + common: common("root"), + style: grid, + paint: plain_paint(), + role: Role::Group, + children: vec![load_text, minds, restart], + }); + SurfaceDocument { + provider_id: ProviderId::new(SWARM), + label: seg("dashboard"), + version: ver(1), + title: "Swarm".into(), + root, + commands: vec![CommandDecl { + id: CommandId::new("restart"), + payload_schema: SchemaId::new("gamecult.thing.test.restart.v1"), + captures: vec![], + confirm: Some("Restart the swarm?".into()), + }], + } +} + +const STACK: &str = "provider.stack"; + +/// A Use of the publisher's card with one argument of each arm and the given slot children. +fn card_use(id: &str, slot: Vec) -> Node { + let source = Bind { source: swarm_ref("summary"), member: path(&["load"]), format: None }; + let rows = CollectionSource::Records(RecordsSource { + provider: None, + schema: SchemaId::new(SWARM_SCHEMA), + key_prefix: "mind-".into(), + }); + let args = vec![ + Arg { name: "title".into(), value: ArgValue::Text(TextArg { value: "Card".into() }) }, + Arg { name: "count".into(), value: ArgValue::Number(NumberArg { value: 3.0 }) }, + Arg { name: "on".into(), value: ArgValue::Bool(BoolArg { value: true }) }, + Arg { name: "source".into(), value: ArgValue::Bind(source) }, + Arg { name: "rows".into(), value: ArgValue::Collection(CollectionArg { source: rows }) }, + Arg { name: "act".into(), value: ArgValue::Command(CommandArg { command: command("open") }) }, + Arg { name: "body".into(), value: ArgValue::Slot(SlotArg { nodes: slot }) }, + ]; + Node::Use(UseNode { + common: common(id), + composition: CompositionRef { publisher: STACK.into(), name: seg("card"), version: ver(1) }, + args, + }) +} + +fn composition_stack() -> SurfaceDocument { + // Two levels: the outer card's slot holds a second card. + let inner = card_use("inner-card", vec![text("inner-note", "nested")]); + let outer = card_use("outer-card", vec![inner]); + SurfaceDocument { + provider_id: ProviderId::new(STACK), + label: seg("stack"), + version: ver(1), + title: "Stack".into(), + root: boxed("root", vec![outer]), + commands: vec![CommandDecl { + id: CommandId::new("open"), + payload_schema: SchemaId::new("gamecult.thing.test.open.v1"), + captures: vec![], + confirm: None, + }], + } +} + +fn stack_card() -> CompositionDocument { + let title = Node::Text(TextNode { + common: common("card-title"), + content: TextSource::Param(param("title")), + style_token: "title".into(), + wrap: true, + max_lines: None, + selectable: false, + }); + let rows = Node::Repeat(RepeatNode { + common: common("card-rows"), + collection: CollectionSource::Param(param("rows")), + key_member: path(&["id"]), + template: std::boxed::Box::new(Node::Text(TextNode { + common: common("card-row"), + content: TextSource::Bound(item_bind(path(&["name"]))), + style_token: "body".into(), + wrap: false, + max_lines: None, + selectable: false, + })), + }); + let act = Node::Button(ButtonNode { + common: common("card-act"), + content: vec![text("card-act-label", "Open")], + on_activate: CommandRef::Param(param("act")), + enabled: BoolSource::Param(param("on")), + }); + CompositionDocument { + publisher: STACK.into(), + name: seg("card"), + version: ver(1), + params: [ + ("title", ParamKind::Text), + ("count", ParamKind::Number), + ("on", ParamKind::Bool), + ("source", ParamKind::Bind), + ("rows", ParamKind::Collection), + ("act", ParamKind::Command), + ("body", ParamKind::Slot), + ] + .into_iter() + .map(|(name, kind)| ParamDecl { name: name.into(), kind }) + .collect(), + body: boxed("card-root", vec![title, rows, act]), + } +} + +const HOSTILE: &str = "provider.hostile"; + +fn hostile_use(id: &str, name: &str) -> Node { + Node::Use(UseNode { + common: common(id), + composition: CompositionRef { publisher: HOSTILE.into(), name: seg(name), version: ver(1) }, + args: vec![], + }) +} + +fn hostile_surface(label: &str, children: Vec) -> SurfaceDocument { + SurfaceDocument { + provider_id: ProviderId::new(HOSTILE), + label: seg(label), + version: ver(1), + title: label.into(), + root: boxed("root", children), + commands: vec![], + } +} + +/// Four surfaces the resolver must refuse or flag, one hostile shape each. A surface whose +/// bytes the contract itself refuses (an unknown union arm) cannot live in a store, so that +/// case is the committed `node-unknown-arm.bin` golden, fed to a fake by the test. +fn hostile() -> Vec { + let undeclared = Node::Button(ButtonNode { + common: common("go"), + content: vec![text("go-label", "Go")], + on_activate: command("missing"), + enabled: lit_bool(true), + }); + let mismatched = Node::Text(TextNode { + common: common("mismatch"), + content: TextSource::Bound(Bind { + source: StateSource::Record(StateRef { + provider: Some(ProviderId::new(HOSTILE)), + schema: SchemaId::new("gamecult.thing.test.nowhere.v1"), + key: RecordKey::new("row-1"), + }), + member: path(&["name"]), + format: None, + }), + style_token: "body".into(), + wrap: false, + max_lines: None, + selectable: false, + }); + vec![ + hostile_surface("undeclared-command", vec![undeclared]), + // The composition `dup` emits `shared-id`, which the surface also uses. + hostile_surface("duplicate-id", vec![hostile_use("dup-use", "dup"), text("shared-id", "also here")]), + // No composition `ghost` exists anywhere. + hostile_surface("unresolved-use", vec![hostile_use("ghost-use", "ghost")]), + hostile_surface("schema-mismatch", vec![mismatched]), + ] +} + +/// The one composition a hostile surface needs: the duplicate-id case cannot expand without it. +fn hostile_dup() -> CompositionDocument { + CompositionDocument { + publisher: HOSTILE.into(), + name: seg("dup"), + version: ver(1), + params: vec![], + body: boxed("dup-root", vec![text("shared-id", "from the composition")]), + } +} diff --git a/crates/thing-testkit/src/lib.rs b/crates/thing-testkit/src/lib.rs index bab5b04..1107328 100644 --- a/crates/thing-testkit/src/lib.rs +++ b/crates/thing-testkit/src/lib.rs @@ -2,5 +2,7 @@ //! depends on this; no shipped crate does. pub mod build; +pub mod fixture; pub mod golden; +pub mod mem_state; pub mod store; diff --git a/crates/thing-testkit/src/mem_state.rs b/crates/thing-testkit/src/mem_state.rs new file mode 100644 index 0000000..96ec2cb --- /dev/null +++ b/crates/thing-testkit/src/mem_state.rs @@ -0,0 +1,258 @@ +//! `MemState`: an in-memory `StatePort`. Each provider's records live in a CultCache with the +//! 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. + +use std::cell::RefCell; +use std::collections::HashMap; + +use cultcache_rs::{CultCache, CultCacheEnvelope, DatabaseEntry}; +use thing_contract::*; +use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, SubscriptionId}; + +use crate::store; + +/// A contract kind the port carries. +pub trait StateKind: DatabaseEntry { + fn record_key(&self) -> String; + fn into_record(self) -> Record; +} + +macro_rules! state_kinds { + ($($kind:ident => $arm:ident),* $(,)?) => { + $(impl StateKind for $kind { + fn record_key(&self) -> String { + $kind::record_key(self) + } + fn into_record(self) -> Record { + Record::$arm(self) + } + })* + }; +} + +state_kinds!( + SurfaceDocument => Surface, + CompositionDocument => Composition, + CommandResult => Result, + AssetCatalog => Catalog, +); + +/// Run `$body` with `$t` bound to the contract kind whose schema is `$schema`, or `$none` for +/// a schema the port does not carry. +macro_rules! by_schema { + ($schema:expr, $t:ident => $body:expr, else $none:expr) => { + match $schema { + SurfaceDocument::SCHEMA_NAME => { + type $t = SurfaceDocument; + $body + } + CompositionDocument::SCHEMA_NAME => { + type $t = CompositionDocument; + $body + } + CommandResult::SCHEMA_NAME => { + type $t = CommandResult; + $body + } + AssetCatalog::SCHEMA_NAME => { + type $t = AssetCatalog; + $body + } + _ => $none, + } + }; +} + +/// One call the port received. +#[derive(Clone, Debug, PartialEq)] +pub enum Call { + Read(Address), + List(Prefix), + Subscribe(Interest), + Unsubscribe(SubscriptionId), + Drain, +} + +pub struct MemState { + providers: HashMap, + refused: HashMap, + interests: Vec<(SubscriptionId, Interest)>, + next_subscription: u64, + queue: Vec, + calls: RefCell>, +} + +impl Default for MemState { + fn default() -> Self { + Self::new() + } +} + +impl MemState { + pub fn new() -> Self { + Self { + providers: HashMap::new(), + refused: HashMap::new(), + interests: Vec::new(), + next_subscription: 0, + queue: Vec::new(), + calls: RefCell::new(Vec::new()), + } + } + + /// A state holding every document of a fixture, each under the provider that publishes it. + pub fn from_fixture(fixture: crate::fixture::Fixture) -> Self { + let set = fixture.load(); + let mut state = Self::new(); + for surface in &set.surfaces { + state.put(&surface.provider_id, surface); + } + for composition in &set.compositions { + state.put(&ProviderId::new(composition.publisher.clone()), composition); + } + for catalog in &set.catalogs { + state.put(&catalog.provider_id, catalog); + } + state + } + + /// Store a record under its record key at `provider`. + pub fn put(&mut self, provider: &ProviderId, value: &T) { + let address = Address { + provider: provider.clone(), + schema: SchemaId::new(T::SCHEMA_NAME), + key: RecordKey::new(value.record_key()), + }; + let outcome = self.cache(provider).put(address.key.as_str(), value); + self.admit::(address, outcome); + } + + /// Store a payload under `address`; the address's schema names the contract kind. A payload + /// the contract refuses makes the address refused. + pub fn put_raw(&mut self, address: Address, payload: Vec) { + by_schema!(address.schema.as_str(), T => { + let envelope = CultCacheEnvelope { + key: address.key.as_str().into(), + r#type: T::TYPE.into(), + payload, + stored_at: store::PINNED_CLOCK.into(), + schema_id: Some(T::SCHEMA_NAME.into()), + }; + let outcome = self.cache(&address.provider).put_envelope::(envelope); + self.admit::(address, outcome); + }, else panic!("no contract record kind has schema {}", address.schema.as_str())) + } + + /// Remove the record or the refusal at `address`; removing nothing is not a change. + pub fn delete(&mut self, address: &Address) { + 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()) { + Some(cache) => cache.delete::(address.key.as_str()).unwrap(), + None => false, + } + }, else false); + if refused || stored { + self.queue(Change::Delete(address.clone())); + } + } + + /// Every call the port received, in order. + pub fn calls(&self) -> Vec { + self.calls.borrow().clone() + } + + fn cache(&mut self, provider: &ProviderId) -> &mut CultCache { + self.providers.entry(provider.as_str().to_string()).or_insert_with(store::memory) + } + + fn admit(&mut self, address: Address, outcome: anyhow::Result) { + match outcome { + Ok(value) => { + self.refused.remove(&address); + self.queue(Change::Upsert(Entry { address, record: value.into_record() })); + } + Err(error) => { + // The address is now refused: an older valid record under it no longer stands. + self.cache(&address.provider).delete::(address.key.as_str()).unwrap(); + let refusal = + Refusal { address: address.clone(), kind: address.schema.clone(), detail: format!("{error:#}") }; + self.refused.insert(address, refusal.clone()); + self.queue(Change::Refused(refusal)); + } + } + } + + fn queue(&mut self, change: Change) { + let address = match &change { + Change::Upsert(entry) => &entry.address, + Change::Delete(address) => address, + Change::Refused(refusal) => &refusal.address, + }; + if self.interests.iter().any(|(_, interest)| interest.matches(address)) { + self.queue.push(change); + } + } +} + +impl StatePort for MemState { + fn read(&self, address: &Address) -> Lookup { + self.calls.borrow_mut().push(Call::Read(address.clone())); + if let Some(refusal) = self.refused.get(address) { + return Lookup::Refused(refusal.clone()); + } + by_schema!(address.schema.as_str(), T => { + let stored = self.providers.get(address.provider.as_str()); + match stored.and_then(|cache| cache.get::(address.key.as_str()).expect("stored records decode")) { + Some(value) => Lookup::Present(Entry { address: address.clone(), record: value.into_record() }), + None => Lookup::Absent, + } + }, else Lookup::Absent) + } + + fn list(&self, prefix: &Prefix) -> Vec { + self.calls.borrow_mut().push(Call::List(prefix.clone())); + let at = |key: &str| Address { + provider: prefix.provider.clone(), + schema: prefix.schema.clone(), + key: RecordKey::new(key), + }; + let mut found: Vec<(String, Lookup)> = self + .refused + .values() + .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 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) { + let entry = Entry { address: at(&key), record: value.into_record() }; + found.push((key, Lookup::Present(entry))); + } + } + } + }, else ()); + found.sort_by(|a, b| a.0.cmp(&b.0)); + found.into_iter().map(|(_, lookup)| lookup).collect() + } + + fn subscribe(&mut self, interest: Interest) -> SubscriptionId { + self.calls.borrow_mut().push(Call::Subscribe(interest.clone())); + let id = SubscriptionId(self.next_subscription); + self.next_subscription += 1; + self.interests.push((id, interest)); + id + } + + fn unsubscribe(&mut self, id: SubscriptionId) { + self.calls.borrow_mut().push(Call::Unsubscribe(id)); + self.interests.retain(|(live, _)| *live != id); + } + + fn drain(&mut self) -> Vec { + self.calls.borrow_mut().push(Call::Drain); + std::mem::take(&mut self.queue) + } +} diff --git a/crates/thing-testkit/src/store.rs b/crates/thing-testkit/src/store.rs index 7889692..4b8610a 100644 --- a/crates/thing-testkit/src/store.rs +++ b/crates/thing-testkit/src/store.rs @@ -8,11 +8,17 @@ use thing_contract::ThingContract; pub const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z"; +/// A cache with the contract registered and no backing store. +pub fn memory() -> CultCache { + let mut cache = CultCache::new(); + ThingContract.register_entries(&mut cache).unwrap(); + cache +} + /// An empty cache with the contract registered over a fresh single-file store at `path`. pub fn create(path: &Path) -> CultCache { let _ = std::fs::remove_file(path); - let mut cache = CultCache::new(); - ThingContract.register_entries(&mut cache).unwrap(); + let mut cache = memory(); cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); cache } @@ -26,8 +32,7 @@ pub fn put_pinned(cache: &mut CultCache, key: &str, value: &T) /// A cache with the contract registered, pulled from the store at `path`. pub fn open(path: &Path) -> CultCache { - let mut cache = CultCache::new(); - ThingContract.register_entries(&mut cache).unwrap(); + let mut cache = memory(); cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); cache.pull_all_backing_stores().unwrap(); cache diff --git a/crates/thing-testkit/tests/fixtures.rs b/crates/thing-testkit/tests/fixtures.rs new file mode 100644 index 0000000..cd60559 --- /dev/null +++ b/crates/thing-testkit/tests/fixtures.rs @@ -0,0 +1,161 @@ +//! The committed fixture stores: they open through the contract, the builders reproduce them +//! byte for byte, and each holds the shapes its row of the fixture table names. +//! `THING_BLESS=1` on this test rewrites them; any other run compares. + +use thing_contract::*; +use thing_testkit::fixture::{Fixture, FixtureSet}; +use thing_testkit::mem_state::MemState; +use thing_testkit::store; +use thing_core::port::{Address, Lookup, StatePort}; + +/// Decoding runs on a 16 MiB thread until the workspace pin of cultcache-rs carries +/// decode-stack-safety. +fn on_big_stack(work: impl FnOnce() -> T + Send + 'static) -> T { + std::thread::Builder::new().stack_size(16 * 1024 * 1024).spawn(work).unwrap().join().unwrap() +} + +fn load(fixture: Fixture) -> FixtureSet { + on_big_stack(move || fixture.load()) +} + +#[test] +fn every_fixture_round_trips_through_the_contract() { + on_big_stack(|| { + for fixture in Fixture::ALL { + // The builders reproduce the committed file byte for byte (or bless it). + fixture.write(); + let built = fixture.build(); + let loaded = fixture.load(); + assert_eq!(loaded, built, "{}: the store decodes to the built documents", fixture.file_name()); + + // Each record re-encodes to its stored payload. + let cache = store::open(&Fixture::dir().join(fixture.file_name())); + for surface in &loaded.surfaces { + let stored = cache.get_envelope::(&surface.record_key()).unwrap().unwrap(); + assert_eq!(rmp_serde::to_vec(surface).unwrap(), stored.payload); + } + for composition in &loaded.compositions { + let stored = cache.get_envelope::(&composition.record_key()).unwrap().unwrap(); + assert_eq!(rmp_serde::to_vec(composition).unwrap(), stored.payload); + } + assert_eq!( + cache.snapshot_envelopes().len(), + loaded.surfaces.len() + loaded.compositions.len() + loaded.catalogs.len(), + "{}: the store holds the documents and nothing else", + fixture.file_name() + ); + } + }); +} + +fn commands_declared(surface: &SurfaceDocument) -> Vec<&str> { + surface.commands.iter().map(|decl| decl.id.as_str()).collect() +} + +fn box_children(node: &Node) -> &[Node] { + match node { + Node::Box(node) => &node.children, + other => panic!("not a Box: {other:?}"), + } +} + +#[test] +fn f01_is_the_swarm_dashboard() { + let set = load(Fixture::F01SwarmDashboard); + assert_eq!(set.surfaces.len(), 1); + let surface = &set.surfaces[0]; + let Node::Box(root) = &surface.root else { panic!("root is not a Box") }; + assert_eq!(root.style.display, Display::Grid); + let [load, minds, restart] = &root.children[..] else { panic!("three children expected") }; + + let Node::Text(load) = load else { panic!("not a Text") }; + let TextSource::Bound(bind) = &load.content else { panic!("Text is not bound") }; + assert!(matches!(bind.format, Some(Format::Number(_)))); + + let Node::Repeat(minds) = minds else { panic!("not a Repeat") }; + assert!(matches!(minds.collection, CollectionSource::Records(_))); + + let Node::Button(restart) = restart else { panic!("not a Button") }; + let CommandRef::Id(command) = &restart.on_activate else { panic!("not a command id") }; + assert_eq!(commands_declared(surface), [command.id.as_str()]); +} + +#[test] +fn f09_stacks_compositions_with_every_argument_arm() { + let set = load(Fixture::F09CompositionStack); + assert_eq!((set.surfaces.len(), set.compositions.len()), (1, 1)); + let surface = &set.surfaces[0]; + let [outer] = box_children(&surface.root) else { panic!("one Use expected") }; + let Node::Use(outer) = outer else { panic!("not a Use") }; + assert_eq!(outer.composition.publisher, set.compositions[0].publisher); + assert_eq!(outer.composition.name, set.compositions[0].name); + assert_eq!(outer.composition.version, set.compositions[0].version); + + let arms: Vec<&str> = outer + .args + .iter() + .map(|arg| match arg.value { + ArgValue::Text(_) => "text", + ArgValue::Number(_) => "number", + ArgValue::Bool(_) => "bool", + ArgValue::Bind(_) => "bind", + ArgValue::Collection(_) => "collection", + ArgValue::Command(_) => "command", + ArgValue::Slot(_) => "slot", + }) + .collect(); + assert_eq!(arms, ["text", "number", "bool", "bind", "collection", "command", "slot"]); + + // The slot holds a second Use of the same composition: two levels. + let ArgValue::Slot(slot) = &outer.args[6].value else { unreachable!() }; + assert!(slot.nodes.iter().any(|node| matches!(node, Node::Use(inner) if inner.composition == outer.composition))); +} + +#[test] +fn f10_holds_exactly_the_four_hostile_surfaces() { + let set = load(Fixture::F10Hostile); + let labels: Vec<&str> = set.surfaces.iter().map(|surface| surface.label.as_str()).collect(); + assert_eq!(labels, ["duplicate-id", "schema-mismatch", "undeclared-command", "unresolved-use"]); + + let by = |label: &str| set.surfaces.iter().find(|surface| surface.label.as_str() == label).unwrap(); + + let undeclared = by("undeclared-command"); + let Node::Button(button) = &box_children(&undeclared.root)[0] else { panic!("not a Button") }; + let CommandRef::Id(command) = &button.on_activate else { panic!("not a command id") }; + assert!(!commands_declared(undeclared).contains(&command.id.as_str())); + + // The surface uses `shared-id` and so does the composition its Use expands to. + let dup = by("duplicate-id"); + let children = box_children(&dup.root); + assert!(children.iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "shared-id"))); + let Node::Use(used) = &children[0] else { panic!("not a Use") }; + let composition = set.compositions.iter().find(|composition| composition.name == used.composition.name).unwrap(); + assert!(box_children(&composition.body).iter().any(|node| matches!(node, Node::Text(text) if text.common.id.as_str() == "shared-id"))); + + // The unresolved Use names a composition no document holds. + let Node::Use(ghost) = &box_children(&by("unresolved-use").root)[0] else { panic!("not a Use") }; + assert!(set.compositions.iter().all(|composition| composition.name != ghost.composition.name)); + + // The Bind names a schema none of the fixtures use for state. + let Node::Text(text) = &box_children(&by("schema-mismatch").root)[0] else { panic!("not a Text") }; + let TextSource::Bound(Bind { source: StateSource::Record(state), .. }) = &text.content else { + panic!("Text is not bound to a record") + }; + let f01 = load(Fixture::F01SwarmDashboard); + let Node::Box(root) = &f01.surfaces[0].root else { unreachable!() }; + let Node::Text(f01_text) = &root.children[0] else { unreachable!() }; + let TextSource::Bound(Bind { source: StateSource::Record(f01_state), .. }) = &f01_text.content else { unreachable!() }; + assert_ne!(state.schema, f01_state.schema); +} + +#[test] +fn a_state_holds_every_fixture_document_under_its_publisher() { + let state = on_big_stack(|| MemState::from_fixture(Fixture::F09CompositionStack)); + let set = load(Fixture::F09CompositionStack); + let at = Address { + provider: ProviderId::new(set.compositions[0].publisher.clone()), + schema: SchemaId::new("gamecult.thing.composition.v1"), + key: RecordKey::new(set.compositions[0].record_key()), + }; + assert!(matches!(state.read(&at), Lookup::Present(_))); +} diff --git a/crates/thing-testkit/tests/golden.rs b/crates/thing-testkit/tests/golden.rs new file mode 100644 index 0000000..4930d57 --- /dev/null +++ b/crates/thing-testkit/tests/golden.rs @@ -0,0 +1,59 @@ +//! The bless door compares and never writes unless `THING_BLESS=1`. These tests assume it is +//! unset; the bless job runs only the fixtures test. + +use std::panic::catch_unwind; +use std::path::PathBuf; + +use thing_testkit::golden; + +fn scratch(name: &str) -> PathBuf { + let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("golden-{name}")); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn a_mismatch_panics_naming_the_file_and_leaves_it_unchanged() { + let dir = scratch("mismatch"); + std::fs::write(dir.join("a.bin"), b"committed").unwrap(); + + assert_eq!(golden::check(&dir, "a.bin", b"committed"), b"committed"); + + let panic = catch_unwind(|| golden::check(&dir, "a.bin", b"different")).unwrap_err(); + let message = panic.downcast_ref::().cloned().unwrap_or_default(); + assert!(message.contains("a.bin"), "the panic names the file: {message}"); + assert_eq!(std::fs::read(dir.join("a.bin")).unwrap(), b"committed"); +} + +#[test] +fn a_missing_file_is_a_failure_not_a_write() { + let dir = scratch("missing"); + assert!(catch_unwind(|| golden::check(&dir, "absent.bin", b"x")).is_err()); + assert!(catch_unwind(|| golden::read(&dir, "absent.bin")).is_err()); + assert!(!dir.join("absent.bin").exists()); +} + +#[test] +fn the_text_beside_the_binary_is_compared_too() { + let dir = scratch("text"); + std::fs::write(dir.join("s.bin"), b"bytes").unwrap(); + std::fs::write(dir.join("s.txt"), "text").unwrap(); + + assert_eq!(golden::check_with_text(&dir, "s", b"bytes", "text"), b"bytes"); + + let panic = catch_unwind(|| golden::check_with_text(&dir, "s", b"bytes", "other")).unwrap_err(); + let message = panic.downcast_ref::().cloned().unwrap_or_default(); + assert!(message.contains("s.txt"), "the panic names the text file: {message}"); + assert_eq!(std::fs::read(dir.join("s.txt")).unwrap(), b"text"); + + assert!(catch_unwind(|| golden::check_with_text(&dir, "s", b"changed", "text")).is_err()); + assert_eq!(std::fs::read(dir.join("s.bin")).unwrap(), b"bytes"); +} + +#[test] +fn read_returns_the_committed_bytes() { + let dir = scratch("read"); + std::fs::write(dir.join("r.bin"), b"abc").unwrap(); + assert_eq!(golden::read(&dir, "r.bin"), b"abc"); +} diff --git a/crates/thing-testkit/tests/mem_state.rs b/crates/thing-testkit/tests/mem_state.rs new file mode 100644 index 0000000..512160e --- /dev/null +++ b/crates/thing-testkit/tests/mem_state.rs @@ -0,0 +1,245 @@ +//! MemState as core sees it: through `StatePort`, with its own put and delete as the only +//! writers. + +use std::path::PathBuf; + +use thing_contract::*; +use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, StatePort, SubscriptionId}; +use thing_testkit::build::*; +use thing_testkit::golden; +use thing_testkit::mem_state::{Call, MemState}; + +const SURFACE: &str = "gamecult.thing.surface.v1"; +const COMPOSITION: &str = "gamecult.thing.composition.v1"; +const RESULT: &str = "gamecult.thing.command_result.v1"; +const CATALOG: &str = "gamecult.thing.asset_catalog.v1"; +// A value that must never appear in a refusal; node-unknown-arm.bin carries it. +const CANARY: &str = "CANARY-7f3a91c2"; + +fn provider(name: &str) -> ProviderId { + ProviderId::new(name) +} + +fn address(provider_name: &str, schema: &str, key: &str) -> Address { + Address { provider: provider(provider_name), schema: SchemaId::new(schema), key: RecordKey::new(key) } +} + +fn prefix(provider_name: &str, schema: &str, key_prefix: &str) -> Prefix { + Prefix { provider: provider(provider_name), schema: SchemaId::new(schema), key_prefix: key_prefix.into() } +} + +fn surface(provider_name: &str, label: &str) -> SurfaceDocument { + SurfaceDocument { + provider_id: provider(provider_name), + label: seg(label), + version: ver(1), + title: label.into(), + root: boxed("root", vec![]), + commands: vec![], + } +} + +fn composition(publisher: &str, name: &str) -> CompositionDocument { + CompositionDocument { + publisher: publisher.into(), + name: seg(name), + version: ver(1), + params: vec![], + body: boxed("body", vec![]), + } +} + +fn catalog(provider_name: &str, id: &str) -> AssetCatalog { + AssetCatalog { provider_id: provider(provider_name), catalog_id: seg(id), version: ver(1), assets: vec![] } +} + +fn surface_at(provider_name: &str, value: &SurfaceDocument) -> Address { + address(provider_name, SURFACE, &value.record_key()) +} + +fn unknown_arm() -> Vec { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../thing-contract/tests/goldens"); + golden::read(&dir, "node-unknown-arm.bin") +} + +#[test] +fn port_is_object_safe() { + let one = surface("provider.a", "one"); + let mut state = MemState::new(); + state.put(&provider("provider.a"), &one); + let port: &mut dyn StatePort = &mut state; + let id = port.subscribe(Interest::Record(surface_at("provider.a", &one))); + assert!(matches!(port.read(&surface_at("provider.a", &one)), Lookup::Present(_))); + assert_eq!(port.list(&prefix("provider.a", SURFACE, "thing:")).len(), 1); + port.unsubscribe(id); + assert!(port.drain().is_empty()); + let boxed: Box = Box::new(MemState::new()); + assert_eq!(boxed.read(&address("provider.a", SURFACE, "k")), Lookup::Absent); +} + +#[test] +fn a_refusal_is_not_absence() { + let main = surface("provider.a", "main"); + let at = surface_at("provider.a", &main); + assert_eq!(at.key.as_str(), "thing:surface:provider.a.main"); + let mut state = MemState::new(); + state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:"))); + + state.put_raw(at.clone(), unknown_arm()); + + let drained = state.drain(); + assert_eq!(drained.len(), 1, "one change: {drained:?}"); + let Change::Refused(refusal) = &drained[0] else { panic!("not a refusal: {drained:?}") }; + assert_eq!(refusal.address, at); + assert_eq!(refusal.kind, SchemaId::new(SURFACE)); + assert!(refusal.detail.contains(at.key.as_str()), "the detail names the key: {}", refusal.detail); + assert!(!refusal.detail.contains(CANARY), "the detail echoed a value: {}", refusal.detail); + assert_eq!(state.read(&at), Lookup::Refused(refusal.clone())); + assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:")), vec![Lookup::Refused(refusal.clone())]); + + // A valid record replaces the refusal; a refusal over a valid record leaves the address + // refused, not the older record. + state.put(&provider("provider.a"), &main); + assert!(matches!(state.read(&at), Lookup::Present(_))); + state.put_raw(at.clone(), unknown_arm()); + assert!(matches!(state.read(&at), Lookup::Refused(_))); + assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:")).len(), 1); + state.drain(); + + // Deleting a refusal is a change; deleting nothing is not. + state.delete(&at); + assert_eq!(state.read(&at), Lookup::Absent); + assert_eq!(state.drain(), vec![Change::Delete(at.clone())]); + state.delete(&at); + assert!(state.drain().is_empty()); +} + +#[test] +fn changes_drain_in_mutation_order_for_live_interests() { + let provider_a = provider("provider.a"); + let one = surface("provider.a", "one"); + let two = surface("provider.a", "two"); + let panel = composition("provider.a", "panel"); + let other = composition("provider.a", "other"); + let icons = catalog("provider.a", "icons"); + let one_at = surface_at("provider.a", &one); + let panel_at = address("provider.a", COMPOSITION, &panel.record_key()); + + let mut state = MemState::new(); + let ids: Vec = vec![ + state.subscribe(Interest::Record(one_at.clone())), + state.subscribe(Interest::Record(panel_at.clone())), + state.subscribe(Interest::Prefix(prefix("provider.a", SURFACE, "thing:"))), + ]; + + state.put(&provider_a, &one); // matches two interests and drains once + state.put(&provider_a, &panel); + state.put(&provider_a, &icons); // another schema under the same provider + state.put(&provider_a, &other); // a composition nobody asked for + // The same key and schema under another provider. + state.put_raw(address("provider.b", SURFACE, &two.record_key()), rmp_serde::to_vec(&two).unwrap()); + state.put(&provider_a, &two); + state.delete(&one_at); + + let entry = |address: Address, record: Record| Change::Upsert(Entry { address, record }); + assert_eq!( + state.drain(), + vec![ + entry(one_at.clone(), Record::Surface(one.clone())), + entry(panel_at, Record::Composition(panel)), + entry(surface_at("provider.a", &two), Record::Surface(two.clone())), + Change::Delete(one_at), + ] + ); + assert!(state.drain().is_empty(), "each change drains once"); + + for id in ids { + state.unsubscribe(id); + } + state.put(&provider_a, &one); + assert!(state.drain().is_empty()); +} + +#[test] +fn without_a_live_interest_nothing_queues() { + let mut state = MemState::new(); + state.put_raw(address("provider.a", SURFACE, "thing:surface:provider.a.main"), unknown_arm()); + state.put(&provider("provider.a"), &surface("provider.a", "one")); + assert!(state.drain().is_empty()); +} + +#[test] +fn each_kind_reads_back_as_its_own_arm() { + let provider_a = provider("provider.a"); + let mut state = MemState::new(); + let first = surface("provider.a", "b"); + let invocation = invocation(); + let result = CommandResult::pending(&invocation, seq(1), "working"); + let panel = composition("provider.a", "panel"); + let icons = catalog("provider.a", "icons"); + state.put(&provider_a, &first); + state.put(&provider_a, &panel); + state.put(&provider_a, &result); + state.put(&provider_a, &icons); + + let present = |at: Address, record: Record| Lookup::Present(Entry { address: at, record }); + let first_at = surface_at("provider.a", &first); + assert_eq!(state.read(&first_at), present(first_at.clone(), Record::Surface(first.clone()))); + let panel_at = address("provider.a", COMPOSITION, &panel.record_key()); + assert_eq!(state.read(&panel_at), present(panel_at.clone(), Record::Composition(panel))); + let result_at = address("provider.a", RESULT, &result.record_key()); + assert_eq!(state.read(&result_at), present(result_at.clone(), Record::Result(result))); + let icons_at = address("provider.a", CATALOG, &icons.record_key()); + assert_eq!(state.read(&icons_at), present(icons_at.clone(), Record::Catalog(icons))); + + // A newer record replaces the older; an absent key, another provider and another schema read Absent. + let mut newer = first.clone(); + newer.title = "newer".into(); + state.put(&provider_a, &newer); + assert_eq!(state.read(&first_at), present(first_at.clone(), Record::Surface(newer))); + assert_eq!(state.read(&address("provider.a", SURFACE, "missing")), Lookup::Absent); + assert_eq!(state.read(&address("provider.b", SURFACE, first_at.key.as_str())), Lookup::Absent); + assert_eq!(state.read(&address("provider.a", COMPOSITION, first_at.key.as_str())), Lookup::Absent); + assert_eq!(state.read(&address("provider.a", "gamecult.thing.nowhere.v1", "k")), Lookup::Absent); + + // A list holds the prefix's records in key order and no others. + let a = surface("provider.a", "a"); + let c = surface("provider.a", "c"); + state.put(&provider_a, &c); + state.put(&provider_a, &a); + let keys: Vec = state + .list(&prefix("provider.a", SURFACE, "thing:surface:provider.a.")) + .into_iter() + .map(|lookup| match lookup { + Lookup::Present(entry) => entry.address.key.as_str().to_string(), + other => panic!("{other:?}"), + }) + .collect(); + assert_eq!(keys, ["thing:surface:provider.a.a", "thing:surface:provider.a.b", "thing:surface:provider.a.c"]); + assert_eq!(state.list(&prefix("provider.a", SURFACE, "thing:surface:provider.a.b")).len(), 1); + assert!(state.list(&prefix("provider.b", SURFACE, "thing:")).is_empty()); +} + +#[test] +fn every_call_is_logged_in_order() { + let at = address("provider.a", SURFACE, "k"); + let under = prefix("provider.a", SURFACE, "p"); + let mut state = MemState::new(); + state.read(&at); + let id = state.subscribe(Interest::Prefix(under.clone())); + state.list(&under); + state.drain(); + state.unsubscribe(id); + assert_eq!( + state.calls(), + vec![ + Call::Read(at.clone()), + Call::Subscribe(Interest::Prefix(under.clone())), + Call::List(under), + Call::Drain, + Call::Unsubscribe(id), + ] + ); + let second = state.subscribe(Interest::Record(at)); + assert_ne!(second, id, "a subscription id is never reused"); +}