From b640b3c9272080b4021bdd3db3eacf71bad7aadc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 03:19:27 +0100 Subject: [PATCH 1/7] Thing 2.0: the shared interest Ledger, the bind diagnostic codes, is_stored_at_stamp from the contract Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-contract/src/lib.rs | 2 +- crates/thing-core/src/diagnostic.rs | 8 +++++ crates/thing-core/src/port/ledger.rs | 53 ++++++++++++++++++++++++++++ crates/thing-core/src/port/mod.rs | 2 ++ crates/thing-core/src/resolve/mod.rs | 2 +- 5 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 crates/thing-core/src/port/ledger.rs diff --git a/crates/thing-contract/src/lib.rs b/crates/thing-contract/src/lib.rs index 602e81a..62085b9 100644 --- a/crates/thing-contract/src/lib.rs +++ b/crates/thing-contract/src/lib.rs @@ -33,7 +33,7 @@ pub use result::*; pub use source::*; pub use style::*; -pub use cultcache_rs::DatabaseEntry; +pub use cultcache_rs::{DatabaseEntry, is_stored_at_stamp}; use cultcache_rs::{CultCache, CultCacheRegistry}; /// Registers the five kinds with a cache. diff --git a/crates/thing-core/src/diagnostic.rs b/crates/thing-core/src/diagnostic.rs index 7d8f174..e5a69fb 100644 --- a/crates/thing-core/src/diagnostic.rs +++ b/crates/thing-core/src/diagnostic.rs @@ -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 { diff --git a/crates/thing-core/src/port/ledger.rs b/crates/thing-core/src/port/ledger.rs new file mode 100644 index 0000000..57a7a27 --- /dev/null +++ b/crates/thing-core/src/port/ledger.rs @@ -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, +} + +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, new: &HashSet) { + 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) + } +} diff --git a/crates/thing-core/src/port/mod.rs b/crates/thing-core/src/port/mod.rs index 1ae2ae8..6c9962c 100644 --- a/crates/thing-core/src/port/mod.rs +++ b/crates/thing-core/src/port/mod.rs @@ -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}; diff --git a/crates/thing-core/src/resolve/mod.rs b/crates/thing-core/src/resolve/mod.rs index 002eb9f..921d85c 100644 --- a/crates/thing-core/src/resolve/mod.rs +++ b/crates/thing-core/src/resolve/mod.rs @@ -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(step: impl FnOnce() -> R) -> R { +pub(crate) fn grow(step: impl FnOnce() -> R) -> R { stacker::maybe_grow(RED_ZONE, SEGMENT, step) } -- 2.47.3 From 70a20dddc264a12ebc18dc33ccd70f6ae9f82a3b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 03:19:29 +0100 Subject: [PATCH 2/7] Thing 2.0: SwarmRenamed, and a test for load_store's fallback to the entry type Closes thing2:finding:cut-state-port.s2.schema-id-fallback-untested. Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-testkit/src/state.rs | 13 +++++++++++++ crates/thing-testkit/tests/state.rs | 25 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/crates/thing-testkit/src/state.rs b/crates/thing-testkit/src/state.rs index 7b92911..59e0f89 100644 --- a/crates/thing-testkit/src/state.rs +++ b/crates/thing-testkit/src/state.rs @@ -38,6 +38,19 @@ 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, +} + #[derive(Clone, Debug, PartialEq, DatabaseEntry)] #[cultcache(type = "gamecult.thing.test.target.v1", schema = "gamecult.thing.test.target.v1")] pub struct Target { diff --git a/crates/thing-testkit/tests/state.rs b/crates/thing-testkit/tests/state.rs index 64c21d0..59f69b2 100644 --- a/crates/thing-testkit/tests/state.rs +++ b/crates/thing-testkit/tests/state.rs @@ -221,3 +221,28 @@ 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 store written without schema ids names a record's schema by its entry type, and the + // catalog's member rows are found under that name. + 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 bytes = thing_testkit::store::bytes(|cache| { + cache.register_entry_type::().unwrap(); + let swarm = Swarm { id: "a".into(), name: "n".into(), load: 1.0 }; + let (mut envelope, _) = cache.prepare_entry("k", &swarm).unwrap(); + envelope.stored_at = thing_testkit::store::PINNED_CLOCK.into(); + envelope.schema_id = None; + cache.put_envelope::(envelope).unwrap(); + }); + std::fs::write(&path, bytes).unwrap(); + let mut state = MemState::new(); + state.load_store(&ProviderId::new(PROVIDER), &path); + let _ = std::fs::remove_dir_all(&dir); + let found = state.read(&at(SWARM_SCHEMA, "k")); + let Lookup::Present(Entry { record: Record::State { schema, value }, .. }) = found else { panic!("{found:?}") }; + assert_eq!(schema, SchemaId::new(SWARM_SCHEMA)); + assert_eq!(value.member("Name"), Some(&Text("n".into()))); +} -- 2.47.3 From 5e5f67978c069c4fe5d4fcffc7cd43fa004efcae Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 03:19:30 +0100 Subject: [PATCH 3/7] Thing 2.0 cut 4: bind (Binder, BoundTree, keyed Repeat instances, Format) with text goldens Co-Authored-By: Claude Sonnet 5.5 --- crates/thing-core/src/bind/format.rs | 172 +++++ crates/thing-core/src/bind/mod.rs | 342 ++++++++++ crates/thing-core/src/bind/repeat.rs | 199 ++++++ crates/thing-core/src/bind/walk.rs | 370 +++++++++++ crates/thing-core/src/lib.rs | 1 + crates/thing-core/tests/bind.rs | 619 ++++++++++++++++++ .../goldens/bind-f01-swarm-dashboard.txt | 14 + .../tests/goldens/bind-f04-form.txt | 11 + 8 files changed, 1728 insertions(+) create mode 100644 crates/thing-core/src/bind/format.rs create mode 100644 crates/thing-core/src/bind/mod.rs create mode 100644 crates/thing-core/src/bind/repeat.rs create mode 100644 crates/thing-core/src/bind/walk.rs create mode 100644 crates/thing-core/tests/bind.rs create mode 100644 crates/thing-core/tests/goldens/bind-f01-swarm-dashboard.txt create mode 100644 crates/thing-core/tests/goldens/bind-f04-form.txt diff --git a/crates/thing-core/src/bind/format.rs b/crates/thing-core/src/bind/format.rs new file mode 100644 index 0000000..85de973 --- /dev/null +++ b/crates/thing-core/src/bind/format.rs @@ -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_stored_at_stamp}; + +/// 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 { + 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 { + 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 { + if is_stored_at_stamp(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]"); + } +} diff --git a/crates/thing-core/src/bind/mod.rs b/crates/thing-core/src/bind/mod.rs new file mode 100644 index 0000000..3a2da9c --- /dev/null +++ b/crates/thing-core/src/bind/mod.rs @@ -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), + Options(Vec), + /// 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>, + repeat_errors: HashMap, +} + +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>, + pub diagnostics: Vec, +} + +/// What a surface's unit read and owns, so a unit can be replaced alone. +struct Owned { + values: Vec<(NodeId, Field)>, + repeats: Vec, + ids: Vec, + nodes: usize, + interests: HashSet, +} + +struct Surface { + key: String, + bound: BoundTree, + tree_ids: HashSet, + parts: HashMap, +} + +pub struct Binder { + limits: Limits, + surfaces: HashMap, +} + +fn tree_ids(tree: &ResolvedTree) -> HashSet { + fn visit(node: &thing_contract::Node, out: &mut HashSet) { + 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 { + 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>, + ) -> (Vec, Vec) { + let before = self.interests(); + let mut old_values: HashMap<(NodeId, Field), Bound> = HashMap::new(); + let mut old_keys: HashMap> = HashMap::new(); + let mut old_errors: HashMap = HashMap::new(); + let retired: Vec = 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 = Vec::new(); + let mut note = |node: &NodeId, code: Code, detail: &str, was: Option| { + 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 = 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 { + 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 = 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) + } +} diff --git a/crates/thing-core/src/bind/repeat.rs b/crates/thing-core/src/bind/repeat.rs new file mode 100644 index 0000000..2f5da1b --- /dev/null +++ b/crates/thing-core/src/bind/repeat.rs @@ -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: +//! `#:/