Thing 2.0 cut 4: bind (the Binder binds resolved trees to provider state by name) #13

Merged
eureka merged 7 commits from hands/thing2-bind into main 2026-11-28 03:15:14 +00:00
16 changed files with 2303 additions and 2 deletions

View file

@ -34,6 +34,13 @@ pub use source::*;
pub use style::*;
pub use cultcache_rs::DatabaseEntry;
/// Whether `text` is an RFC 3339 UTC-or-offset date-time of the one shape a Thing timestamp is
/// written in (`YYYY-MM-DDThh:mm:ss`, an optional fraction, then `Z` or an offset). A timestamp a
/// provider publishes as text is shown as written only when this accepts it.
pub fn is_timestamp_text(text: &str) -> bool {
cultcache_rs::is_stored_at_stamp(text)
}
use cultcache_rs::{CultCache, CultCacheRegistry};
/// Registers the five kinds with a cache.

View file

@ -0,0 +1,172 @@
//! Format: total and locale-free. Each function takes the value the site read and returns the
//! text, or the reason the value does not fit (a detail that never carries the value).
use thing_contract::{AffixFormat, NumberFormat, is_timestamp_text};
/// Fixed-point text of `n` at `format.precision`, scaled by 100 for a percent, with the percent
/// sign and the unit. Non-finite numbers print as NaN, inf, -inf; negative zero prints as zero.
pub fn number(n: f64, format: &NumberFormat) -> String {
let scaled = if format.percent { n * 100.0 } else { n };
let mut text = if scaled.is_nan() {
"NaN".to_string()
} else if scaled.is_infinite() {
if scaled > 0.0 { "inf" } else { "-inf" }.to_string()
} else {
format!("{scaled:.*}", format.precision.get() as usize)
};
if text.starts_with('-') && text[1..].bytes().all(|byte| byte == b'0' || byte == b'.') {
text.remove(0);
}
if format.percent {
text.push('%');
}
if let Some(unit) = &format.unit {
text.push(' ');
text.push_str(unit);
}
text
}
/// Seconds rounded half away from zero, printed by the largest unit present with the later
/// units at two digits: `5s`, `1m 05s`, `1h 00m 05s`, `1d 01h 00m 00s`, a leading `-` when negative.
pub fn duration(seconds: f64) -> Result<String, &'static str> {
if !seconds.is_finite() {
return Err("a duration is not finite");
}
let total = seconds.round() as i128;
let t = total.unsigned_abs();
let (days, hours, minutes, secs) = (t / 86_400, t % 86_400 / 3_600, t % 3_600 / 60, t % 60);
let body = if days > 0 {
format!("{days}d {hours:02}h {minutes:02}m {secs:02}s")
} else if hours > 0 {
format!("{hours}h {minutes:02}m {secs:02}s")
} else if minutes > 0 {
format!("{minutes}m {secs:02}s")
} else {
format!("{secs}s")
};
Ok(if total < 0 { format!("-{body}") } else { body })
}
const FIRST_SECOND: i128 = -62_135_596_800; // 0001-01-01T00:00:00Z
const LAST_SECOND: i128 = 253_402_300_799; // 9999-12-31T23:59:59Z
/// Unix seconds, floored, as `YYYY-MM-DDTHH:MM:SSZ` in UTC, years 0001 to 9999.
pub fn timestamp(seconds: f64) -> Result<String, &'static str> {
if !seconds.is_finite() {
return Err("a timestamp is not finite");
}
let floored = seconds.floor() as i128;
if !(FIRST_SECOND..=LAST_SECOND).contains(&floored) {
return Err("a timestamp is outside years 0001 to 9999");
}
let (days, rest) = (floored.div_euclid(86_400), floored.rem_euclid(86_400));
let (year, month, day) = civil(days as i64);
Ok(format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", rest / 3_600, rest % 3_600 / 60, rest % 60))
}
/// Days since 1970-01-01 as a proleptic Gregorian date.
fn civil(days: i64) -> (i64, i64, i64) {
let z = days + 719_468;
let era = z.div_euclid(146_097);
let day_of_era = z.rem_euclid(146_097);
let year_of_era = (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_index = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
let month = if month_index < 10 { month_index + 3 } else { month_index - 9 };
(year_of_era + era * 400 + i64::from(month <= 2), month, day)
}
/// Text that is already a `stored_at` stamp, as written.
pub fn stamp(text: &str) -> Result<String, &'static str> {
if is_timestamp_text(text) { Ok(text.to_string()) } else { Err("the text is not a timestamp") }
}
pub fn affix(text: &str, format: &AffixFormat) -> String {
format!("{}{text}{}", format.prefix, format.suffix)
}
#[cfg(test)]
mod tests {
use thing_contract::Count;
use super::*;
fn fmt(precision: i32, percent: bool, unit: Option<&str>) -> NumberFormat {
NumberFormat { precision: Count::new(precision).unwrap(), percent, unit: unit.map(Into::into) }
}
#[test]
fn number_table() {
let table = [
(0.42, fmt(1, true, None), "42.0%"),
(3.14159, fmt(2, false, None), "3.14"),
(2.5, fmt(0, false, None), "2"),
(1234.5, fmt(1, false, Some("MB")), "1234.5 MB"),
(0.5, fmt(0, true, Some("of cap")), "50% of cap"),
(-0.0, fmt(1, false, None), "0.0"),
(-0.04, fmt(1, false, None), "0.0"),
(-1.25, fmt(1, false, None), "-1.2"),
(f64::NAN, fmt(2, true, None), "NaN%"),
(f64::INFINITY, fmt(2, false, Some("x")), "inf x"),
(f64::NEG_INFINITY, fmt(0, false, None), "-inf"),
];
for (n, format, expected) in table {
assert_eq!(number(n, &format), expected, "{n} {format:?}");
}
}
#[test]
fn duration_table() {
let table = [
(0.0, "0s"),
(5.0, "5s"),
(59.4, "59s"),
(59.5, "1m 00s"),
(65.0, "1m 05s"),
(3605.0, "1h 00m 05s"),
(90_000.0, "1d 01h 00m 00s"),
(-65.0, "-1m 05s"),
(-0.4, "0s"),
(-0.5, "-1s"),
];
for (seconds, expected) in table {
assert_eq!(duration(seconds).unwrap(), expected, "{seconds}");
}
assert!(duration(f64::NAN).is_err() && duration(f64::INFINITY).is_err());
}
#[test]
fn timestamp_table() {
let table = [
(0.0, "1970-01-01T00:00:00Z"),
(0.9, "1970-01-01T00:00:00Z"),
(-0.1, "1969-12-31T23:59:59Z"),
(951_782_400.0, "2000-02-29T00:00:00Z"),
(1_767_225_600.0, "2026-01-01T00:00:00Z"),
(-62_135_596_800.0, "0001-01-01T00:00:00Z"),
(253_402_300_799.0, "9999-12-31T23:59:59Z"),
];
for (seconds, expected) in table {
assert_eq!(timestamp(seconds).unwrap(), expected, "{seconds}");
}
assert!(timestamp(253_402_300_800.0).is_err());
assert!(timestamp(-62_135_596_801.0).is_err());
assert!(timestamp(f64::NAN).is_err());
}
#[test]
fn stamp_text_is_printed_as_written() {
assert_eq!(stamp("2026-01-01T00:00:00Z").unwrap(), "2026-01-01T00:00:00Z");
assert_eq!(stamp("2026-01-01T02:00:00.5+02:00").unwrap(), "2026-01-01T02:00:00.5+02:00");
assert!(stamp("yesterday").is_err());
assert!(stamp("2026-01-01 00:00:00Z").is_err());
}
#[test]
fn affix_wraps_text() {
let format = AffixFormat { prefix: "[".into(), suffix: "]".into() };
assert_eq!(affix("ok", &format), "[ok]");
}
}

View file

@ -0,0 +1,342 @@
//! Bind: a `ResolvedTree` and provider state become a `BoundTree`, the value of every source
//! site of every node, the instances of every Repeat and the typed faults between. The Binder is
//! handed trees and the changes the frame owner drained; it never drains, never decodes and keeps
//! no state value beside the port: a changed address is read again. The state interests it holds
//! are exactly the ones the bound trees read, held through the shared `Ledger`.
//!
//! A bound tree is a side table over the resolved document, not a second node tree.
mod format;
mod repeat;
mod walk;
use std::collections::{BTreeMap, HashMap, HashSet};
use thing_contract::{NodeId, SelectOption};
use crate::diagnostic::{Code, Diagnostic};
use crate::port::{Address, Change, Interest, Ledger, StatePort};
use crate::resolve::{Limits, ResolvedTree};
use walk::{Unit, Walker};
/// Every source site a node can carry. Closed.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Field {
Visible,
A11yLabel,
Content,
Alt,
Enabled,
Checked,
Value,
Placeholder,
Initial,
Selected,
Options,
Series,
}
impl Field {
pub fn name(self) -> &'static str {
match self {
Field::Visible => "visible",
Field::A11yLabel => "a11y_label",
Field::Content => "content",
Field::Alt => "alt",
Field::Enabled => "enabled",
Field::Checked => "checked",
Field::Value => "value",
Field::Placeholder => "placeholder",
Field::Initial => "initial",
Field::Selected => "selected",
Field::Options => "options",
Field::Series => "series",
}
}
}
/// Why a site or a Repeat has no value. `detail` names the fault and never carries a state value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BindError {
pub code: Code,
pub detail: String,
}
/// What one site shows. A value is never coerced into another site type.
#[derive(Clone, Debug, PartialEq)]
pub enum Bound {
Text(String),
Number(f64),
Bool(bool),
Series(Vec<f64>),
Options(Vec<SelectOption>),
/// The record or the member is not there (or is nil).
Absent,
Error(BindError),
}
/// One instance of a Repeat's template: its key, and the template with derived ids, whose sites
/// are in the same table. A refused item's key is `!` and its record key.
#[derive(Clone, Debug, PartialEq)]
pub struct Instance {
pub key: String,
pub root: thing_contract::Node,
}
/// The values of one resolved document.
#[derive(Clone, Debug, PartialEq)]
pub struct BoundTree {
tree: ResolvedTree,
values: HashMap<(NodeId, Field), Bound>,
instances: HashMap<NodeId, Vec<Instance>>,
repeat_errors: HashMap<NodeId, BindError>,
}
impl BoundTree {
pub fn resolved(&self) -> &ResolvedTree {
&self.tree
}
pub fn value(&self, node: &NodeId, field: Field) -> Option<&Bound> {
self.values.get(&(node.clone(), field))
}
/// The instances of a Repeat, in collection order; none when the Repeat is in error.
pub fn instances(&self, repeat: &NodeId) -> &[Instance] {
self.instances.get(repeat).map_or(&[], Vec::as_slice)
}
/// Why a Repeat has no instances, when it is in error.
pub fn repeat_error(&self, repeat: &NodeId) -> Option<&BindError> {
self.repeat_errors.get(repeat)
}
/// Every bound site, instances' included, sorted by node id and field.
pub fn sites(&self) -> Vec<(&NodeId, Field, &Bound)> {
let mut sites: Vec<_> = self.values.iter().map(|((node, field), bound)| (node, *field, bound)).collect();
sites.sort_by(|a, b| (a.0.as_str(), a.1).cmp(&(b.0.as_str(), b.1)));
sites
}
}
/// What one bind or apply changed: per surface key, the node ids whose value changed (appeared,
/// vanished or differed) or whose Repeat instance set changed; and the diagnostics of sites that
/// entered an error or changed error code.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Applied {
pub dirty: BTreeMap<String, Vec<NodeId>>,
pub diagnostics: Vec<Diagnostic>,
}
/// What a surface's unit read and owns, so a unit can be replaced alone.
struct Owned {
values: Vec<(NodeId, Field)>,
repeats: Vec<NodeId>,
ids: Vec<NodeId>,
nodes: usize,
interests: HashSet<Interest>,
}
struct Surface {
key: String,
bound: BoundTree,
tree_ids: HashSet<NodeId>,
parts: HashMap<Unit, Owned>,
}
pub struct Binder {
limits: Limits,
surfaces: HashMap<String, Surface>,
}
fn tree_ids(tree: &ResolvedTree) -> HashSet<NodeId> {
fn visit(node: &thing_contract::Node, out: &mut HashSet<NodeId>) {
crate::resolve::grow(|| {
out.extend(walk::common(node).map(|common| common.id.clone()));
if let thing_contract::Node::Repeat(repeat) = node {
visit(&repeat.template, out);
}
walk::children(node).iter().for_each(|child| visit(child, out));
})
}
let mut ids = HashSet::new();
visit(&tree.document().root, &mut ids);
ids
}
impl Surface {
fn interests(&self) -> HashSet<Interest> {
self.parts.values().flat_map(|owned| owned.interests.iter().cloned()).collect()
}
/// Bind the units `only` selects (all when `None`), replace what they owned, and report what
/// changed against what they held.
fn run(
&mut self,
limits: &Limits,
port: &mut dyn StatePort,
ledger: &mut Ledger,
only: Option<&HashSet<Unit>>,
) -> (Vec<NodeId>, Vec<Diagnostic>) {
let before = self.interests();
let mut old_values: HashMap<(NodeId, Field), Bound> = HashMap::new();
let mut old_keys: HashMap<NodeId, Vec<String>> = HashMap::new();
let mut old_errors: HashMap<NodeId, Code> = HashMap::new();
let retired: Vec<Unit> = match only {
None => self.parts.keys().cloned().collect(),
Some(only) => only.iter().filter(|unit| self.parts.contains_key(*unit)).cloned().collect(),
};
for unit in retired {
let Some(owned) = self.parts.remove(&unit) else { continue };
for key in owned.values {
if let Some(bound) = self.bound.values.remove(&key) {
old_values.insert(key, bound);
}
}
for repeat in owned.repeats {
if let Some(instances) = self.bound.instances.remove(&repeat) {
old_keys.insert(repeat.clone(), instances.into_iter().map(|instance| instance.key).collect());
}
if let Some(error) = self.bound.repeat_errors.remove(&repeat) {
old_errors.insert(repeat, error.code);
}
}
}
let mut taken = self.tree_ids.clone();
let mut spent = 0;
for owned in self.parts.values() {
taken.extend(owned.ids.iter().cloned());
spent += owned.nodes;
}
let provider = self.bound.tree.document().provider_id.clone();
let parts = Walker::new(&*port, &provider, limits, taken, limits.max_nodes.saturating_sub(spent), only)
.run(&self.bound.tree.document().root);
let mut diagnostics = Vec::new();
let mut dirty: Vec<NodeId> = Vec::new();
let mut note = |node: &NodeId, code: Code, detail: &str, was: Option<Code>| {
if was != Some(code) {
diagnostics.push(Diagnostic { code, surface: self.key.clone(), node: Some(node.clone()), detail: detail.to_string() });
}
};
for (unit, part) in parts {
let mut owned = Owned {
values: Vec::new(),
repeats: Vec::new(),
ids: part.ids,
nodes: part.nodes,
interests: part.interests,
};
for (key, bound) in part.values {
let old = old_values.remove(&key);
if old.as_ref() != Some(&bound) {
dirty.push(key.0.clone());
}
if let Bound::Error(error) = &bound {
note(&key.0, error.code, &error.detail, match &old {
Some(Bound::Error(was)) => Some(was.code),
_ => None,
});
}
owned.values.push(key.clone());
self.bound.values.insert(key, bound);
}
for (repeat, error) in part.errors {
note(&repeat, error.code, &error.detail, old_errors.get(&repeat).copied());
self.bound.repeat_errors.insert(repeat, error);
}
for (repeat, instances) in part.instances {
let keys: Vec<String> = instances.iter().map(|instance| instance.key.clone()).collect();
if old_keys.remove(&repeat).as_ref() != Some(&keys) {
dirty.push(repeat.clone());
}
owned.repeats.push(repeat.clone());
self.bound.instances.insert(repeat, instances);
}
self.parts.insert(unit, owned);
}
// What the retired units held and the new ones no longer do has vanished.
dirty.extend(old_values.into_keys().map(|(node, _)| node));
dirty.extend(old_keys.into_keys());
ledger.diff(port, &before, &self.interests());
let mut seen = HashSet::new();
dirty.retain(|node| seen.insert(node.clone()));
dirty.sort_by(|a, b| a.as_str().cmp(b.as_str()));
(dirty, diagnostics)
}
fn matching(&self, address: &Address) -> HashSet<Unit> {
self.parts
.iter()
.filter(|(_, owned)| owned.interests.iter().any(|interest| interest.matches(address)))
.map(|(unit, _)| unit.clone())
.collect()
}
}
impl Binder {
pub fn new(limits: Limits) -> Self {
Self { limits, surfaces: HashMap::new() }
}
/// Bind a resolved tree. A tree for a surface already held replaces its tree: the walk, the
/// diff against what was bound and the interest diff are the same as an apply's.
pub fn bind(&mut self, tree: ResolvedTree, port: &mut dyn StatePort, ledger: &mut Ledger) -> Applied {
let key = tree.document().record_key();
let ids = tree_ids(&tree);
let surface = self.surfaces.entry(key.clone()).or_insert_with(|| Surface {
key: key.clone(),
bound: BoundTree {
tree: tree.clone(),
values: HashMap::new(),
instances: HashMap::new(),
repeat_errors: HashMap::new(),
},
tree_ids: HashSet::new(),
parts: HashMap::new(),
});
surface.bound.tree = tree;
surface.tree_ids = ids;
let (dirty, diagnostics) = surface.run(&self.limits, port, ledger, None);
Applied { dirty: BTreeMap::from([(key, dirty)]).into_iter().filter(|(_, ids)| !ids.is_empty()).collect(), diagnostics }
}
/// One drained change: nothing is read unless a held interest matches its address; then each
/// unit that read it is bound again from the port.
pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Applied {
let address = match change {
Change::Upsert(entry) => &entry.address,
Change::Delete(address) => address,
Change::Refused(refusal) => &refusal.address,
};
let mut applied = Applied::default();
let mut keys: Vec<String> = self.surfaces.keys().cloned().collect();
keys.sort();
for key in keys {
let surface = self.surfaces.get_mut(&key).expect("key listed");
let units = surface.matching(address);
if units.is_empty() {
continue;
}
let (dirty, diagnostics) = surface.run(&self.limits, port, ledger, Some(&units));
if !dirty.is_empty() {
applied.dirty.insert(key, dirty);
}
applied.diagnostics.extend(diagnostics);
}
applied
}
/// Drop a surface: its interests are released.
pub fn forget(&mut self, surface: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
if let Some(surface) = self.surfaces.remove(surface) {
ledger.diff(port, &surface.interests(), &HashSet::new());
}
}
pub fn tree(&self, surface: &str) -> Option<&BoundTree> {
self.surfaces.get(surface).map(|surface| &surface.bound)
}
}

View file

@ -0,0 +1,199 @@
//! Repeat: a collection's items become instances of the template, keyed so identity follows the
//! item. An instance's ids derive from (repeat id, key, template id) by one scheme:
//! `<repeat>#<key byte length>:<key>/<template id>`; an item the port refused has no key to read,
//! so its identity is its record key in the distinct form `<repeat>!<length>:<record key>/<template id>`.
//! A Repeat that cannot be instantiated is an error of that Repeat alone.
use std::collections::HashSet;
use thing_contract::*;
use super::walk::{Item, Walker, children, common, fault, walk};
use super::{BindError, Instance};
use crate::diagnostic::Code;
use crate::port::{Lookup, Prefix, Record, StateValue};
use crate::resolve::grow;
/// One item of a collection. `record_key` is set for an item that is a record of its own.
pub(super) struct Entry {
pub record_key: Option<String>,
pub item: Item,
}
/// The key of an item: Text as it is, an Int in decimal.
fn key_of(value: &StateValue, path: &MemberPath) -> Result<String, BindError> {
match walk(value, path)? {
Some(StateValue::Text(text)) => Ok(text.clone()),
Some(StateValue::Int(n)) => Ok(n.to_string()),
Some(_) => Err(fault(Code::BindTypeMismatch, "an item key is not Text or Int")),
None => Err(fault(Code::BindTypeMismatch, "an item key is nil")),
}
}
fn collect_ids(node: &Node, out: &mut Vec<NodeId>) {
grow(|| {
out.extend(common(node).map(|common| common.id.clone()));
if let Node::Repeat(repeat) = node {
collect_ids(&repeat.template, out);
}
children(node).iter().for_each(|child| collect_ids(child, out));
})
}
/// Give every id of the template, and every anchor that names one of them, the instance prefix.
fn rewrite(node: &mut Node, prefix: &str, inside: &HashSet<NodeId>) {
grow(|| {
let derive = |id: &mut NodeId| *id = NodeId::new(format!("{prefix}{}", id.as_str()));
match node {
Node::Box(n) => {
derive(&mut n.common.id);
n.children.iter_mut().for_each(|child| rewrite(child, prefix, inside));
}
Node::Button(n) => {
derive(&mut n.common.id);
n.content.iter_mut().for_each(|child| rewrite(child, prefix, inside));
}
Node::Overlay(n) => {
derive(&mut n.common.id);
if let Anchor::Node(anchor) = &mut n.anchor {
if inside.contains(&anchor.node) {
derive(&mut anchor.node);
}
}
n.children.iter_mut().for_each(|child| rewrite(child, prefix, inside));
}
Node::Repeat(n) => {
derive(&mut n.common.id);
rewrite(&mut n.template, prefix, inside);
}
Node::Text(n) => derive(&mut n.common.id),
Node::Image(n) => derive(&mut n.common.id),
Node::Toggle(n) => derive(&mut n.common.id),
Node::Slider(n) => derive(&mut n.common.id),
Node::TextInput(n) => derive(&mut n.common.id),
Node::Select(n) => derive(&mut n.common.id),
Node::Plot(n) => derive(&mut n.common.id),
Node::Embed(n) => derive(&mut n.common.id),
Node::Use(n) => derive(&mut n.common.id),
Node::Slot(_) => {}
}
})
}
impl Walker<'_> {
/// The items of a collection, each a value or the fault that stands for it. Records read the
/// prefix, a Member reads the list of its holder; both leave their interest.
pub(super) fn collection(&mut self, source: &CollectionSource, item: Option<&Item>) -> Result<Vec<Entry>, BindError> {
match source {
CollectionSource::Records(records) => {
let provider = records.provider.clone().unwrap_or_else(|| self.provider.clone());
let prefix = Prefix { provider, schema: records.schema.clone(), key_prefix: records.key_prefix.clone() };
self.part.interests.insert(crate::port::Interest::Prefix(prefix.clone()));
Ok(self
.port
.list(&prefix)
.into_iter()
.filter_map(|lookup| match lookup {
Lookup::Present(entry) => {
let record_key = Some(entry.address.key.as_str().to_string());
Some(match entry.record {
Record::State { schema, value } if schema == records.schema => {
Entry { record_key, item: Item::Value(value) }
}
_ => Entry {
record_key,
item: Item::Fault(fault(
Code::BindSchemaMismatch,
format!("the record is not held under {}", records.schema.as_str()),
)),
},
})
}
Lookup::Refused(refusal) => Some(Entry {
record_key: Some(refusal.address.key.as_str().to_string()),
item: Item::Fault(fault(Code::DecodeRefused, refusal.detail)),
}),
Lookup::Absent => None,
})
.collect())
}
CollectionSource::Member(bind) => self.with_source(&bind.source, item, |held| match held? {
None => Ok(Vec::new()),
Some(holder) => match walk(holder, &bind.member)? {
None => Ok(Vec::new()),
Some(StateValue::List(items)) => Ok(items
.iter()
.map(|value| Entry { record_key: None, item: Item::Value(value.clone()) })
.collect()),
Some(_) => Err(fault(Code::BindTypeMismatch, "a collection member is not a list")),
},
}),
CollectionSource::Param(_) => {
Err(fault(Code::BindTypeMismatch, "a parameter that resolve left in the tree"))
}
}
}
/// Bind the instances of one Repeat, whole or not at all.
pub(super) fn repeat(&mut self, repeat: &RepeatNode, outer: Option<&Item>) {
let id = repeat.common.id.clone();
match self.instances(repeat, outer) {
Ok(instances) => self.part.instances.push((id, instances)),
Err(error) => {
self.part.errors.push((id.clone(), error));
self.part.instances.push((id, Vec::new()));
}
}
}
fn instances(&mut self, repeat: &RepeatNode, outer: Option<&Item>) -> Result<Vec<Instance>, BindError> {
let entries = self.collection(&repeat.collection, outer)?;
let id = repeat.common.id.as_str();
let mut template_ids = Vec::new();
collect_ids(&repeat.template, &mut template_ids);
let inside: HashSet<NodeId> = template_ids.into_iter().collect();
let mut keys = HashSet::new();
let mut built: Vec<(Instance, Item)> = Vec::with_capacity(entries.len());
for entry in entries {
let (key, prefix) = match &entry.item {
Item::Fault(_) => {
let record = entry.record_key.clone().unwrap_or_default();
(format!("!{record}"), format!("{id}!{}:{record}/", record.len()))
}
Item::Value(value) => {
let key = key_of(value, &repeat.key_member)?;
if !keys.insert(key.clone()) {
return Err(fault(Code::RepeatKeyDuplicate, format!("two items of {id} share one key")));
}
let prefix = format!("{id}#{}:{key}/", key.len());
(key, prefix)
}
};
let mut root = (*repeat.template).clone();
rewrite(&mut root, &prefix, &inside);
built.push((Instance { key, root }, entry.item));
}
let mut ids = Vec::new();
for (instance, _) in &built {
collect_ids(&instance.root, &mut ids);
}
if ids.len() > self.budget.min(self.limits.max_nodes) {
return Err(fault(Code::ExpansionLimit, format!("the instances of {id} are past the node limit")));
}
let mut local = HashSet::new();
if ids.iter().any(|derived| self.taken.contains(derived) || !local.insert(derived)) {
return Err(fault(Code::DuplicateNodeId, format!("an instance id of {id} is already an id of the tree")));
}
self.budget -= ids.len();
self.part.nodes += ids.len();
self.taken.extend(ids.iter().cloned());
self.part.ids.extend(ids);
for (instance, item) in &built {
self.instance(&instance.root, item);
}
Ok(built.into_iter().map(|(instance, _)| instance).collect())
}
}

View file

@ -0,0 +1,370 @@
//! The walk: every source site of a node, read from the state port, a member path and a terminal
//! type. Nothing here keeps a value: the port is the truth.
use std::collections::HashSet;
use thing_contract::*;
use super::format;
use super::{BindError, Bound, Field, Instance};
use crate::diagnostic::Code;
use crate::port::{Address, Entry, Interest, Lookup, Record, StatePort, StateValue};
use crate::resolve::{Limits, grow};
/// What a surface's values are re-evaluated by: one site, or one outermost Repeat (`None`).
pub(super) type Unit = (NodeId, Option<Field>);
/// What one unit bound: its values, its instance lists, its Repeat faults, the ids and node count
/// its instances take, and the interests it read.
#[derive(Default)]
pub(super) struct Part {
pub values: Vec<((NodeId, Field), Bound)>,
pub instances: Vec<(NodeId, Vec<Instance>)>,
pub errors: Vec<(NodeId, BindError)>,
pub ids: Vec<NodeId>,
pub nodes: usize,
pub interests: HashSet<Interest>,
}
/// The value a Repeat's template reads through `Item`.
pub(super) enum Item {
Value(StateValue),
Fault(BindError),
}
pub(super) fn fault(code: Code, detail: impl Into<String>) -> BindError {
BindError { code, detail: detail.into() }
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Want {
Text,
Number,
Bool,
Series,
}
enum Site<'n> {
Bool(&'n BoolSource),
Text(&'n TextSource),
Number(&'n NumberSource),
Bind(&'n Bind, Want),
Options(&'n OptionList),
}
fn kind(value: &StateValue) -> &'static str {
match value {
StateValue::Nil => "nil",
StateValue::Bool(_) => "bool",
StateValue::Int(_) => "int",
StateValue::Float(_) => "float",
StateValue::Text(_) => "text",
StateValue::Bytes(_) => "bytes",
StateValue::List(_) => "list",
StateValue::Record(_) => "record",
}
}
fn number_of(value: &StateValue) -> Option<f64> {
match value {
StateValue::Int(n) => Some(*n as f64),
StateValue::Float(n) => Some(*n),
_ => None,
}
}
/// Walk `path` from `value`. `Ok(None)` is a Nil reached, which is absence.
pub(super) fn walk<'v>(mut value: &'v StateValue, path: &MemberPath) -> Result<Option<&'v StateValue>, BindError> {
for step in &path.steps {
if matches!(value, StateValue::Nil) {
return Ok(None);
}
value = match (step, value) {
(MemberStep::Name(step), StateValue::Record(_)) => value
.member(&step.name)
.ok_or_else(|| fault(Code::BindMemberMissing, format!("the record has no member {}", step.name)))?,
(MemberStep::Index(step), StateValue::List(items)) => items.get(step.index.get() as usize).ok_or_else(|| {
fault(Code::BindMemberMissing, format!("the list has no index {}", step.index.get()))
})?,
(MemberStep::Name(step), other) => {
return Err(fault(Code::BindTypeMismatch, format!("member {} asked of a {}", step.name, kind(other))));
}
(MemberStep::Index(step), other) => {
return Err(fault(Code::BindTypeMismatch, format!("index {} asked of a {}", step.index.get(), kind(other))));
}
};
}
Ok(if matches!(value, StateValue::Nil) { None } else { Some(value) })
}
/// A value at the type its site takes. No value is coerced; a Format is the only road from a
/// number to text.
fn terminal(value: &StateValue, want: Want, format: Option<&Format>) -> Result<Bound, BindError> {
let mismatch = |why: &str| Err(fault(Code::BindTypeMismatch, format!("{why}: a {} value", kind(value))));
if want != Want::Text && format.is_some() {
return mismatch("a Format on a site that is not text");
}
match want {
Want::Number => match number_of(value) {
Some(n) => Ok(Bound::Number(n)),
None => mismatch("a number site"),
},
Want::Bool => match value {
StateValue::Bool(b) => Ok(Bound::Bool(*b)),
_ => mismatch("a bool site"),
},
Want::Series => match value {
StateValue::List(items) => match items.iter().map(number_of).collect::<Option<Vec<f64>>>() {
Some(series) => Ok(Bound::Series(series)),
None => Err(fault(Code::BindTypeMismatch, "a series holds a member that is not a number")),
},
_ => mismatch("a series site"),
},
Want::Text => {
let text = match (value, format) {
(StateValue::Text(text), None) => Ok(text.clone()),
(StateValue::Text(text), Some(Format::Affix(affix))) => Ok(format::affix(text, affix)),
(StateValue::Text(text), Some(Format::Timestamp)) => format::stamp(text),
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Number(spec))) => {
Ok(format::number(number_of(value).unwrap(), spec))
}
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Duration)) => {
format::duration(number_of(value).unwrap())
}
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Timestamp)) => {
format::timestamp(number_of(value).unwrap())
}
_ => Err("the value does not fit the text site and its Format"),
};
text.map(Bound::Text).map_err(|why| fault(Code::BindTypeMismatch, format!("{why}: a {} value", kind(value))))
}
}
}
/// The Text at `path` of an item, for an option's value or label.
pub(super) fn item_text(value: &StateValue, path: &MemberPath) -> Result<String, BindError> {
match walk(value, path)? {
Some(StateValue::Text(text)) => Ok(text.clone()),
Some(other) => Err(fault(Code::BindTypeMismatch, format!("an option member is a {}", kind(other)))),
None => Err(fault(Code::BindTypeMismatch, "an option member is nil")),
}
}
/// The sites of one node, in Field order.
fn sites(node: &Node) -> Vec<(Field, Site<'_>)> {
let mut found = Vec::new();
let Some(common) = common(node) else { return found };
found.push((Field::Visible, Site::Bool(&common.visible)));
if let Some(label) = &common.a11y_label {
found.push((Field::A11yLabel, Site::Text(label)));
}
match node {
Node::Text(n) => found.push((Field::Content, Site::Text(&n.content))),
Node::Image(n) => found.push((Field::Alt, Site::Text(&n.alt))),
Node::Button(n) => found.push((Field::Enabled, Site::Bool(&n.enabled))),
Node::Toggle(n) => found.push((Field::Checked, Site::Bool(&n.checked))),
Node::Slider(n) => found.push((Field::Value, Site::Number(&n.value))),
Node::TextInput(n) => {
found.push((Field::Placeholder, Site::Text(&n.placeholder)));
found.push((Field::Initial, Site::Text(&n.initial)));
}
Node::Select(n) => {
found.push((Field::Options, Site::Options(&n.options)));
found.push((Field::Selected, Site::Bind(&n.value, Want::Text)));
}
Node::Plot(n) => found.push((Field::Series, Site::Bind(&n.series, Want::Series))),
_ => {}
}
found
}
pub(super) fn common(node: &Node) -> Option<&NodeCommon> {
Some(match node {
Node::Box(n) => &n.common,
Node::Text(n) => &n.common,
Node::Image(n) => &n.common,
Node::Button(n) => &n.common,
Node::Toggle(n) => &n.common,
Node::Slider(n) => &n.common,
Node::TextInput(n) => &n.common,
Node::Select(n) => &n.common,
Node::Repeat(n) => &n.common,
Node::Overlay(n) => &n.common,
Node::Plot(n) => &n.common,
Node::Embed(n) => &n.common,
Node::Use(n) => &n.common,
Node::Slot(_) => return None,
})
}
/// The children a walk visits: a Repeat's template is instantiated, never visited as itself.
pub(super) fn children(node: &Node) -> &[Node] {
match node {
Node::Box(n) => &n.children,
Node::Button(n) => &n.content,
Node::Overlay(n) => &n.children,
_ => &[],
}
}
pub(super) struct Walker<'a> {
pub(super) port: &'a dyn StatePort,
pub(super) provider: &'a ProviderId,
pub(super) limits: &'a Limits,
/// Every id of the bound tree outside the units being walked, and the ones walked so far.
pub(super) taken: HashSet<NodeId>,
/// Instance nodes still allowed.
pub(super) budget: usize,
only: Option<&'a HashSet<Unit>>,
pub(super) part: Part,
done: Vec<(Unit, Part)>,
}
impl<'a> Walker<'a> {
pub(super) fn new(
port: &'a dyn StatePort,
provider: &'a ProviderId,
limits: &'a Limits,
taken: HashSet<NodeId>,
budget: usize,
only: Option<&'a HashSet<Unit>>,
) -> Self {
Self { port, provider, limits, taken, budget, only, part: Part::default(), done: Vec::new() }
}
/// Walk the resolved root, binding every unit `only` selects (all when `None`).
pub(super) fn run(mut self, root: &Node) -> Vec<(Unit, Part)> {
self.top(root);
self.done
}
fn selects(&self, unit: &Unit) -> bool {
self.only.is_none_or(|only| only.contains(unit))
}
fn end(&mut self, unit: Unit) {
let part = std::mem::take(&mut self.part);
self.done.push((unit, part));
}
fn top(&mut self, node: &Node) {
grow(|| {
let Some(id) = common(node).map(|common| common.id.clone()) else { return };
for (field, site) in sites(node) {
let unit = (id.clone(), Some(field));
if self.selects(&unit) {
let value = self.eval(site, None);
self.part.values.push(((id.clone(), field), value));
self.end(unit);
}
}
if let Node::Repeat(repeat) = node {
let unit = (id, None);
if self.selects(&unit) {
self.repeat(repeat, None);
self.end(unit);
}
} else {
children(node).iter().for_each(|child| self.top(child));
}
})
}
/// An instance's nodes: every site binds, with `item` as the Item.
pub(super) fn instance(&mut self, node: &Node, item: &Item) {
grow(|| {
let Some(id) = common(node).map(|common| common.id.clone()) else { return };
for (field, site) in sites(node) {
let value = self.eval(site, Some(item));
self.part.values.push(((id.clone(), field), value));
}
if let Node::Repeat(repeat) = node {
self.repeat(repeat, Some(item));
} else {
children(node).iter().for_each(|child| self.instance(child, item));
}
})
}
fn eval(&mut self, site: Site<'_>, item: Option<&Item>) -> Bound {
let unresolved = || Bound::Error(fault(Code::BindTypeMismatch, "a parameter that resolve left in the tree"));
match site {
Site::Bool(BoolSource::Literal(literal)) => Bound::Bool(literal.value),
Site::Bool(BoolSource::Bound(bind)) => self.bind(bind, Want::Bool, item),
Site::Text(TextSource::Literal(literal)) => Bound::Text(literal.value.clone()),
Site::Text(TextSource::Bound(bind)) => self.bind(bind, Want::Text, item),
Site::Number(NumberSource::Literal(literal)) => Bound::Number(literal.value),
Site::Number(NumberSource::Bound(bind)) => self.bind(bind, Want::Number, item),
Site::Bool(BoolSource::Param(_)) | Site::Text(TextSource::Param(_)) | Site::Number(NumberSource::Param(_)) => {
unresolved()
}
Site::Bind(bind, want) => self.bind(bind, want, item),
Site::Options(OptionList::Literal(literal)) => Bound::Options(literal.options.clone()),
Site::Options(OptionList::Bound(bound)) => self.options(bound, item),
}
}
/// Hand `then` what `source` holds: a fault, absence, or the value. Records the interest a
/// Record source reads.
pub(super) fn with_source<R>(
&mut self,
source: &StateSource,
item: Option<&Item>,
then: impl FnOnce(Result<Option<&StateValue>, BindError>) -> R,
) -> R {
match source {
StateSource::Item => match item {
Some(Item::Value(value)) => then(Ok(Some(value))),
Some(Item::Fault(error)) => then(Err(error.clone())),
None => then(Err(fault(Code::BindTypeMismatch, "an Item source outside a Repeat"))),
},
StateSource::Record(reference) => {
let provider = reference.provider.clone().unwrap_or_else(|| self.provider.clone());
let address = Address { provider, schema: reference.schema.clone(), key: reference.key.clone() };
self.part.interests.insert(Interest::Record(address.clone()));
match self.port.read(&address) {
Lookup::Present(Entry { record: Record::State { schema, value }, .. }) if schema == reference.schema => {
then(Ok(Some(&value)))
}
Lookup::Present(_) => then(Err(fault(
Code::BindSchemaMismatch,
format!("the record is not held under {}", reference.schema.as_str()),
))),
Lookup::Absent => then(Ok(None)),
Lookup::Refused(refusal) => then(Err(fault(Code::DecodeRefused, refusal.detail))),
}
}
}
}
fn bind(&mut self, bind: &Bind, want: Want, item: Option<&Item>) -> Bound {
self.with_source(&bind.source, item, |held| match held {
Err(error) => Bound::Error(error),
Ok(None) => Bound::Absent,
Ok(Some(value)) => match walk(value, &bind.member) {
Err(error) => Bound::Error(error),
Ok(None) => Bound::Absent,
Ok(Some(value)) => terminal(value, want, bind.format.as_ref()).unwrap_or_else(Bound::Error),
},
})
}
fn options(&mut self, bound: &BoundOptions, item: Option<&Item>) -> Bound {
let entries = match self.collection(&bound.collection, item) {
Ok(entries) => entries,
Err(error) => return Bound::Error(error),
};
let mut options = Vec::with_capacity(entries.len());
for entry in entries {
let value = match entry.item {
Item::Value(value) => value,
Item::Fault(error) => return Bound::Error(error),
};
match (item_text(&value, &bound.value_member), item_text(&value, &bound.label_member)) {
(Ok(value), Ok(label)) => options.push(SelectOption { value, label }),
(Err(error), _) | (_, Err(error)) => return Bound::Error(error),
}
}
Bound::Options(options)
}
}

View file

@ -25,6 +25,14 @@ pub enum Code {
/// The input nests deeper than the expander can recurse. A stack bound, not the depth rule: the depth
/// rule is judged on the finished tree and reports ExpansionLimit.
TooDeepToResolve,
/// A state record held under another schema than the Bind names.
BindSchemaMismatch,
/// A member path names a member the value does not have.
BindMemberMissing,
/// A value of another type than its site takes; no value is coerced.
BindTypeMismatch,
/// Two items of one Repeat share a key.
RepeatKeyDuplicate,
}
impl Code {

View file

@ -1,6 +1,7 @@
//! 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 bind;
pub mod diagnostic;
pub mod port;
pub mod resolve;

View file

@ -0,0 +1,53 @@
//! The one interest ledger: core holds a state interest once however many readers ask for it. A
//! reader (the Resolver or the Binder) holds and releases through the ledger, never through the
//! port, so one `SubscriptionId` per interest is shared by count and an interest nothing reads
//! is unsubscribed.
use std::collections::{HashMap, HashSet};
use super::{Interest, StatePort, SubscriptionId};
#[derive(Debug, Default)]
pub struct Ledger {
held: HashMap<Interest, (SubscriptionId, usize)>,
}
impl Ledger {
pub fn new() -> Self {
Self::default()
}
/// One more reader of `interest`; the port is asked only for the first.
pub fn hold(&mut self, port: &mut dyn StatePort, interest: &Interest) -> SubscriptionId {
let (id, count) = self.held.entry(interest.clone()).or_insert_with(|| (port.subscribe(interest.clone()), 0));
*count += 1;
*id
}
/// One reader fewer; the port is told when the last goes. Releasing what is not held does nothing.
pub fn release(&mut self, port: &mut dyn StatePort, interest: &Interest) {
let Some((id, count)) = self.held.get_mut(interest) else { return };
*count -= 1;
if *count == 0 {
let id = *id;
self.held.remove(interest);
port.unsubscribe(id);
}
}
/// Move one reader from the interests it held to the ones it holds now: hold only the added,
/// release only the removed, touch nothing else.
pub fn diff(&mut self, port: &mut dyn StatePort, old: &HashSet<Interest>, new: &HashSet<Interest>) {
for added in new.difference(old) {
self.hold(port, added);
}
for removed in old.difference(new) {
self.release(port, removed);
}
}
/// How many readers hold `interest`.
pub fn readers(&self, interest: &Interest) -> usize {
self.held.get(interest).map_or(0, |(_, count)| *count)
}
}

View file

@ -1,8 +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 ledger;
pub mod state;
pub use ledger::Ledger;
pub use state::StateValue;
use thing_contract::{AssetCatalog, CommandResult, CompositionDocument, ProviderId, RecordKey, SchemaId, SurfaceDocument};

View file

@ -19,7 +19,7 @@ const RED_ZONE: usize = 512 * 1024;
const SEGMENT: usize = 2 * 1024 * 1024;
/// Runs one recursive step with room for the next, growing the stack when it is nearly spent.
fn grow<R>(step: impl FnOnce() -> R) -> R {
pub(crate) fn grow<R>(step: impl FnOnce() -> R) -> R {
stacker::maybe_grow(RED_ZONE, SEGMENT, step)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,14 @@
load visible bool true
load content text "42.0%"
minds visible bool true
minds#6:mind-1/mind-name visible bool true
minds#6:mind-1/mind-name content text "Eureka"
minds#6:mind-2/mind-name visible bool true
minds#6:mind-2/mind-name content text "Libby"
minds#6:mind-3/mind-name visible bool true
minds#6:mind-3/mind-name content text "Kiko"
restart visible bool true
restart enabled bool true
restart-label visible bool true
restart-label content text "Restart"
root visible bool true

View file

@ -0,0 +1,11 @@
enabled visible bool true
enabled checked bool true
port visible bool true
port placeholder text "port"
port initial text "8080"
root visible bool true
theme visible bool true
theme selected text "dark"
theme options options [dark=Dark, light=Light]
volume visible bool true
volume value number 40

View file

@ -204,6 +204,17 @@ impl MemState {
self.put_state_raw(address, payload, &T::schema_members());
}
/// Store an already-decoded provider-state `value` under `address`, as a port that decoded it
/// would hand it over: for the kinds a typed record cannot hold (bytes, a float where an int is
/// asked), which the tests of a reader feed through the one door.
pub fn put_value(&mut self, address: Address, value: StateValue) {
assert!(!is_contract(&address.schema), "{} is a contract kind: put", address.schema.as_str());
let slot = (address.provider.as_str().to_string(), address.key.as_str().to_string());
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 } }));
}
/// 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<u8>, rows: &[SchemaCatalogMember]) {

View file

@ -5,7 +5,7 @@
//! A CultCache store names a record's schema by its entry type, not by `SCHEMA_NAME`, so each type
//! here is registered under its schema id: the id a Bind names is the id the store holds.
use cultcache_rs::DatabaseEntry;
use cultcache_rs::{CultSlots, DatabaseEntry};
use serde::{Deserialize, Serialize};
use thing_contract::{ProviderId, RecordKey, SchemaId};
use thing_core::port::Address;
@ -38,6 +38,60 @@ impl DatabaseEntry for SwarmWithoutRows {
const SCHEMA_NAME: &'static str = "gamecult.thing.test.swarm.v1";
}
/// `Swarm` with its load member named Burden: the record a provider that renamed a member holds
/// under the same schema id.
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.thing.test.swarm.v1", schema = "gamecult.thing.test.swarm.v1")]
pub struct SwarmRenamed {
#[cultcache(key = 0)]
pub id: String,
#[cultcache(key = 1)]
pub name: String,
#[cultcache(key = 2)]
pub burden: f64,
}
/// A nested record: it decodes as a positional list, `[label, weight]`.
#[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct Inner {
#[cultcache(key = 0)]
pub label: String,
#[cultcache(key = 1)]
pub weight: f64,
}
/// One member of every kind a site can be asked for: text, int, bool, nil, a nested record, a
/// list of text and a stamp.
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.thing.test.mixed.v1", schema = "gamecult.thing.test.mixed.v1")]
pub struct Mixed {
#[cultcache(key = 0)]
pub id: String,
#[cultcache(key = 1)]
pub count: i64,
#[cultcache(key = 2)]
pub flag: bool,
#[cultcache(key = 3)]
pub maybe: Option<String>,
#[cultcache(key = 4)]
pub inner: Inner,
#[cultcache(key = 5)]
pub tags: Vec<String>,
#[cultcache(key = 6)]
pub when: String,
}
/// A committed-store stand-in: the bytes of a store holding `records` under the pinned clock,
/// written by the real cache with `Mixed` registered, for `MemState::load_store`.
pub fn mixed_store(records: &[(&str, Mixed)]) -> Vec<u8> {
crate::store::bytes(|cache| {
cache.register_entry_type::<Mixed>().unwrap();
for (key, record) in records {
crate::store::put_pinned(cache, key, record);
}
})
}
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
#[cultcache(type = "gamecult.thing.test.target.v1", schema = "gamecult.thing.test.target.v1")]
pub struct Target {

View file

@ -221,3 +221,27 @@ fn load_store_names_a_record_by_its_schema_id_when_it_has_one() {
let Lookup::Refused(refusal) = found else { panic!("{found:?}") };
assert_eq!(refusal.kind, SchemaId::new("gamecult.thing.test.alias.v1"));
}
#[test]
fn load_store_falls_back_to_the_entry_type_when_an_envelope_has_no_schema_id() {
// A legacy envelope array carries no schema id and no catalog: a record's schema is then its
// entry type, which is the id a provider's state type is registered under. With no member
// rows the record is refused, and refused under that schema.
let dir = std::env::temp_dir().join(format!("thing-state-noschema-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("noschema.cc");
let mut cache = thing_testkit::store::memory();
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 = None;
std::fs::write(&path, rmp_serde::to_vec_named(&vec![envelope]).unwrap()).unwrap();
let mut state = MemState::new();
state.load_store(&ProviderId::new(PROVIDER), &path);
let _ = std::fs::remove_dir_all(&dir);
let found = state.read(&at(SWARM_SCHEMA, "k"));
let Lookup::Refused(refusal) = found else { panic!("{found:?}") };
assert_eq!(refusal.kind, SchemaId::new(SWARM_SCHEMA));
assert_eq!(refusal.address, at(SWARM_SCHEMA, "k"));
}