Thing 2.0 cut 4b fix: decode moves to thing-state (core holds no reader), registration contract enforced and documented, branch tests
This commit is contained in:
parent
9df7aaced2
commit
c92a3741b7
10 changed files with 267 additions and 190 deletions
14
Cargo.lock
generated
14
Cargo.lock
generated
|
|
@ -499,14 +499,21 @@ dependencies = [
|
|||
name = "thing-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"cultcache-rs",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"stacker",
|
||||
"thing-contract",
|
||||
"thing-testkit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thing-state"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"cultcache-rs",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"thing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thing-testkit"
|
||||
version = "0.1.0"
|
||||
|
|
@ -517,6 +524,7 @@ dependencies = [
|
|||
"serde",
|
||||
"thing-contract",
|
||||
"thing-core",
|
||||
"thing-state",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -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)]
|
||||
|
|
|
|||
|
|
@ -8,9 +8,6 @@ publish = false
|
|||
[dependencies]
|
||||
thing-contract = { path = "../thing-contract" }
|
||||
stacker = "0.1.25"
|
||||
cultcache-rs = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
thing-testkit = { path = "../thing-testkit" }
|
||||
|
|
|
|||
|
|
@ -1,15 +1,6 @@
|
|||
//! The one by-name decode of a provider record. A state port implementation calls `decode` with
|
||||
//! the record's payload and the catalog member rows of its schema; core's pipeline never sees
|
||||
//! bytes. The catalog names only a document's top-level members, so below that level a payload
|
||||
//! decodes by its own shape.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::fmt;
|
||||
use std::io::Cursor;
|
||||
|
||||
use cultcache_rs::{SchemaCatalogMember, check_payload_depth};
|
||||
use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
|
||||
//! A provider record's value as core sees it. Core holds no bytes and no reader of them: a state
|
||||
//! port implementation decodes a record with its schema's member names (the `thing-state` crate)
|
||||
//! and hands core this tree.
|
||||
|
||||
/// A provider record's value: closed, ordered and named, with no case folding.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
|
@ -33,169 +24,3 @@ impl StateValue {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a payload is not a `StateValue`. Display names slots, counts and positions, never a value.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum StateDecodeError {
|
||||
/// The schema published no member rows: a reader cannot name what the writer did not publish.
|
||||
NoMembers,
|
||||
NotARecord,
|
||||
TrailingBytes { count: usize },
|
||||
TooDeep,
|
||||
UndescribedSlot { slot: usize },
|
||||
DuplicateKey { position: usize },
|
||||
Extension,
|
||||
Malformed,
|
||||
}
|
||||
|
||||
impl fmt::Display for StateDecodeError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::NoMembers => f.write_str("the schema published no member rows, so its members cannot be named"),
|
||||
Self::NotARecord => f.write_str("the payload is not one MessagePack array"),
|
||||
Self::TrailingBytes { count } => write!(f, "{count} bytes follow the record"),
|
||||
Self::TooDeep => f.write_str("the payload nests deeper than CultCache admits"),
|
||||
Self::UndescribedSlot { slot } => write!(f, "slot {slot} holds a value no member row names"),
|
||||
Self::DuplicateKey { position } => write!(f, "the map repeats a key at entry {position}"),
|
||||
Self::Extension => f.write_str("the payload holds a MessagePack extension value"),
|
||||
Self::Malformed => f.write_str("the payload is not well-formed MessagePack"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for StateDecodeError {}
|
||||
|
||||
/// Decode `payload`, one MessagePack array, into a `StateValue::Record` of the rows' member
|
||||
/// names in slot order. A row whose slot lies past the array's end is `Nil`; a non-nil element at
|
||||
/// a slot no row names is refused. An empty row list is refused.
|
||||
pub fn decode(payload: &[u8], members: &[SchemaCatalogMember]) -> Result<StateValue, StateDecodeError> {
|
||||
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<usize> = 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<Option<StateDecodeError>>,
|
||||
}
|
||||
|
||||
impl Shape<'_> {
|
||||
fn refuse<E: de::Error>(&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<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<StateValue, D::Error> {
|
||||
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<E: de::Error>(self) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Nil)
|
||||
}
|
||||
|
||||
fn visit_none<E: de::Error>(self) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Nil)
|
||||
}
|
||||
|
||||
fn visit_bool<E: de::Error>(self, value: bool) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Bool(value))
|
||||
}
|
||||
|
||||
fn visit_i64<E: de::Error>(self, value: i64) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Int(value.into()))
|
||||
}
|
||||
|
||||
fn visit_u64<E: de::Error>(self, value: u64) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Int(value.into()))
|
||||
}
|
||||
|
||||
fn visit_f32<E: de::Error>(self, value: f32) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Float(value.into()))
|
||||
}
|
||||
|
||||
fn visit_f64<E: de::Error>(self, value: f64) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Float(value))
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(self, value: &str) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Text(value.into()))
|
||||
}
|
||||
|
||||
fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Bytes(value.into()))
|
||||
}
|
||||
|
||||
fn visit_newtype_struct<D: de::Deserializer<'de>>(self, _: D) -> Result<StateValue, D::Error> {
|
||||
// rmp-serde presents an extension value as a newtype struct.
|
||||
Err(self.refuse(StateDecodeError::Extension))
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<StateValue, A::Error> {
|
||||
let mut elements = Vec::new();
|
||||
while let Some(element) = seq.next_element_seed(self)? {
|
||||
elements.push(element);
|
||||
}
|
||||
Ok(StateValue::List(elements))
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<StateValue, A::Error> {
|
||||
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()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
12
crates/thing-state/Cargo.toml
Normal file
12
crates/thing-state/Cargo.toml
Normal file
|
|
@ -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 }
|
||||
184
crates/thing-state/src/lib.rs
Normal file
184
crates/thing-state/src/lib.rs
Normal file
|
|
@ -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<StateValue, StateDecodeError> {
|
||||
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<usize> = 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<Option<StateDecodeError>>,
|
||||
}
|
||||
|
||||
impl Shape<'_> {
|
||||
fn refuse<E: de::Error>(&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<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<StateValue, D::Error> {
|
||||
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<E: de::Error>(self) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Nil)
|
||||
}
|
||||
|
||||
fn visit_none<E: de::Error>(self) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Nil)
|
||||
}
|
||||
|
||||
fn visit_bool<E: de::Error>(self, value: bool) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Bool(value))
|
||||
}
|
||||
|
||||
fn visit_i64<E: de::Error>(self, value: i64) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Int(value.into()))
|
||||
}
|
||||
|
||||
fn visit_u64<E: de::Error>(self, value: u64) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Int(value.into()))
|
||||
}
|
||||
|
||||
fn visit_f32<E: de::Error>(self, value: f32) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Float(value.into()))
|
||||
}
|
||||
|
||||
fn visit_f64<E: de::Error>(self, value: f64) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Float(value))
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(self, value: &str) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Text(value.into()))
|
||||
}
|
||||
|
||||
fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<StateValue, E> {
|
||||
Ok(StateValue::Bytes(value.into()))
|
||||
}
|
||||
|
||||
fn visit_newtype_struct<D: de::Deserializer<'de>>(self, _: D) -> Result<StateValue, D::Error> {
|
||||
// rmp-serde presents an extension value as a newtype struct.
|
||||
Err(self.refuse(StateDecodeError::Extension))
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<StateValue, A::Error> {
|
||||
let mut elements = Vec::new();
|
||||
while let Some(element) = seq.next_element_seed(self)? {
|
||||
elements.push(element);
|
||||
}
|
||||
Ok(StateValue::List(elements))
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<StateValue, A::Error> {
|
||||
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()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
//! `port::state::decode`: each StateValue arm, the slot rules, and the refusals. Payloads are
|
||||
//! `thing_state::decode`: each StateValue arm, the slot rules, and the refusals. Payloads are
|
||||
//! written byte by byte so the test does not lean on the encoder it checks.
|
||||
|
||||
use cultcache_rs::SchemaCatalogMember;
|
||||
use thing_core::port::StateValue::{self, *};
|
||||
use thing_core::port::state::{StateDecodeError, decode};
|
||||
use thing_state::{StateDecodeError, decode};
|
||||
|
||||
const CANARY: &str = "CANARY-7f3a91c2";
|
||||
|
||||
|
|
@ -9,6 +9,7 @@ publish = false
|
|||
thing-contract = { path = "../thing-contract" }
|
||||
cultcache-rs = { workspace = true }
|
||||
thing-core = { path = "../thing-core" }
|
||||
thing-state = { path = "../thing-state" }
|
||||
anyhow = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
//! record or a delete replaces it.
|
||||
//!
|
||||
//! A provider's own state (any schema outside the contract) is held per (provider, key), one record
|
||||
//! per key as CultCache holds them, already decoded by `thing_core::port::state::decode` with
|
||||
//! per key as CultCache holds them, already decoded by `thing_state::decode` with
|
||||
//! the schema's catalog member rows. A payload that decode refuses is held as a refusal.
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
|
@ -16,7 +16,7 @@ use cultcache_rs::{
|
|||
resolve_schema_entry,
|
||||
};
|
||||
use thing_contract::*;
|
||||
use thing_core::port::state::decode;
|
||||
use thing_state::decode;
|
||||
use thing_core::port::{
|
||||
Address, Change, Entry, Interest, Lookup, Prefix, Record, Refusal, StatePort, StateValue, SubscriptionId,
|
||||
};
|
||||
|
|
@ -192,6 +192,11 @@ impl MemState {
|
|||
/// Store provider state `value` under `key` at `provider`: the type's own schema and member
|
||||
/// rows decode it, as a store written by this type would.
|
||||
pub fn put_state<T: DatabaseEntry>(&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::<T>().unwrap();
|
||||
let payload = cache.prepare_entry(key, value).unwrap().0.payload;
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use thing_contract::{ProviderId, SchemaId};
|
||||
use thing_core::port::state::StateDecodeError;
|
||||
use thing_state::StateDecodeError;
|
||||
use thing_core::port::{Address, Change, Entry, Interest, Lookup, Prefix, Record, StatePort, StateValue};
|
||||
use thing_testkit::fixture::Fixture;
|
||||
use thing_testkit::mem_state::MemState;
|
||||
|
|
@ -176,3 +176,46 @@ fn delete_queues_only_under_a_matching_interest_and_only_for_what_was_held() {
|
|||
"{changes:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
||||
#[cultcache(type = "gamecult.thing.test.other", schema = "gamecult.thing.test.other.v1")]
|
||||
struct TypeIsNotTheSchemaId {
|
||||
#[cultcache(key = 0)]
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "entry type equal to its schema id")]
|
||||
fn put_state_refuses_a_type_that_is_not_its_schema_id() {
|
||||
MemState::new().put_state(&ProviderId::new(PROVIDER), "k", &TypeIsNotTheSchemaId { id: "x".into() });
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "is a contract kind")]
|
||||
fn put_state_raw_refuses_a_contract_schema() {
|
||||
let mut state = MemState::new();
|
||||
state.put_state_raw(at("gamecult.thing.surface.v1", "k"), vec![0x90], &Swarm::schema_members());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_store_names_a_record_by_its_schema_id_when_it_has_one() {
|
||||
// The schema id the store carries is the record's schema, whatever its entry type is called.
|
||||
let dir = std::env::temp_dir().join(format!("thing-state-alias-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("alias.cc");
|
||||
let bytes = thing_testkit::store::bytes(|cache| {
|
||||
cache.register_entry_type::<Swarm>().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::<Swarm>(envelope).unwrap();
|
||||
});
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
let mut state = MemState::new();
|
||||
state.load_store(&ProviderId::new(PROVIDER), &path);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(state.read(&at(SWARM_SCHEMA, "k")), Lookup::Absent);
|
||||
let found = state.read(&at("gamecult.thing.test.alias.v1", "k"));
|
||||
assert!(matches!(found, Lookup::Refused(_) | Lookup::Present(_)), "{found:?}");
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue