Thing 2.0 cut 3b: the Resolver holds each surface's last good tree, gates versions (M9) and keeps composition interests in step
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d9b09ee5f4
commit
f4a6d0cb88
4 changed files with 379 additions and 1 deletions
|
|
@ -33,6 +33,8 @@ pub enum Code {
|
|||
BindTypeMismatch,
|
||||
/// Two items of one Repeat share a key.
|
||||
RepeatKeyDuplicate,
|
||||
/// A surface offered at a version at or below one already offered; the held tree stays.
|
||||
StaleVersionIgnored,
|
||||
}
|
||||
|
||||
impl Code {
|
||||
|
|
|
|||
127
crates/thing-core/src/resolve/intake.rs
Normal file
127
crates/thing-core/src/resolve/intake.rs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
//! The Resolver: per surface, the highest version offered, the last good tree and the composition
|
||||
//! interests that tree's resolution read. It is handed the changes the frame owner drained and
|
||||
//! never drains itself. Every re-resolve reads the port again; no composition is cached here. The
|
||||
//! interests are held through the shared `Ledger`, so the Binder and the Resolver count one
|
||||
//! subscription per address.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use thing_contract::{SurfaceDocument, Version};
|
||||
|
||||
use super::{Limits, ResolvedTree, resolve};
|
||||
use crate::diagnostic::{Code, Diagnostic};
|
||||
use crate::port::{Address, Change, Interest, Ledger, Record, StatePort};
|
||||
|
||||
/// What the Resolver holds of one surface.
|
||||
struct Held {
|
||||
/// The highest version offered, accepted or refused: the only one resolved again.
|
||||
document: SurfaceDocument,
|
||||
/// The last tree a resolve produced for a version above every earlier one.
|
||||
tree: Option<ResolvedTree>,
|
||||
/// The interests of the last resolve, which was of `document`.
|
||||
interests: HashSet<Interest>,
|
||||
/// Versions already reported stale.
|
||||
reported: HashSet<Version>,
|
||||
}
|
||||
|
||||
pub struct Resolver {
|
||||
limits: Limits,
|
||||
surfaces: HashMap<String, Held>,
|
||||
}
|
||||
|
||||
fn is_surface(address: &Address) -> bool {
|
||||
address.schema.as_str() == SurfaceDocument::SCHEMA_NAME
|
||||
}
|
||||
|
||||
impl Resolver {
|
||||
pub fn new(limits: Limits) -> Self {
|
||||
Self { limits, surfaces: HashMap::new() }
|
||||
}
|
||||
|
||||
/// The tree displayed for a surface key: the last good one.
|
||||
pub fn tree(&self, surface_key: &str) -> Option<&ResolvedTree> {
|
||||
self.surfaces.get(surface_key).and_then(|held| held.tree.as_ref())
|
||||
}
|
||||
|
||||
/// One drained change. A surface offer is judged by the version rule; a change at a
|
||||
/// composition a held surface read resolves that surface again from its held document.
|
||||
pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec<Diagnostic> {
|
||||
let address = match change {
|
||||
Change::Upsert(entry) => &entry.address,
|
||||
Change::Delete(address) => address,
|
||||
Change::Refused(refusal) => &refusal.address,
|
||||
};
|
||||
if is_surface(address) {
|
||||
return match change {
|
||||
Change::Upsert(entry) => match &entry.record {
|
||||
Record::Surface(document) => self.offer(document, port, ledger),
|
||||
_ => Vec::new(),
|
||||
},
|
||||
Change::Delete(address) => {
|
||||
if let Some(held) = self.surfaces.remove(address.key.as_str()) {
|
||||
ledger.diff(port, &held.interests, &HashSet::new());
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
Change::Refused(refusal) => vec![Diagnostic {
|
||||
code: Code::DecodeRefused,
|
||||
surface: address.key.as_str().to_string(),
|
||||
node: None,
|
||||
detail: refusal.detail.clone(),
|
||||
}],
|
||||
};
|
||||
}
|
||||
let mut readers: Vec<String> = self
|
||||
.surfaces
|
||||
.iter()
|
||||
.filter(|(_, held)| held.interests.iter().any(|interest| interest.matches(address)))
|
||||
.map(|(key, _)| key.clone())
|
||||
.collect();
|
||||
readers.sort();
|
||||
let mut diagnostics = Vec::new();
|
||||
for key in readers {
|
||||
let document = self.surfaces[&key].document.clone();
|
||||
diagnostics.extend(self.resolve_held(&key, document, port, ledger));
|
||||
}
|
||||
diagnostics
|
||||
}
|
||||
|
||||
fn offer(&mut self, document: &SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec<Diagnostic> {
|
||||
let key = document.record_key();
|
||||
if let Some(held) = self.surfaces.get_mut(&key)
|
||||
&& document.version <= held.document.version
|
||||
{
|
||||
return if held.reported.insert(document.version) {
|
||||
vec![Diagnostic {
|
||||
code: Code::StaleVersionIgnored,
|
||||
surface: key,
|
||||
node: None,
|
||||
detail: "version at or below the held version, which stays".into(),
|
||||
}]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
}
|
||||
self.resolve_held(&key, document.clone(), port, ledger)
|
||||
}
|
||||
|
||||
/// Resolve `document` as the highest offered for `key`: a tree replaces the held one, no tree
|
||||
/// keeps it. The interests become the reads either way.
|
||||
fn resolve_held(&mut self, key: &str, document: SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec<Diagnostic> {
|
||||
let resolution = resolve(&document, &*port, &self.limits);
|
||||
let interests: HashSet<Interest> = resolution.reads.into_iter().map(Interest::Record).collect();
|
||||
let held = self.surfaces.entry(key.to_string()).or_insert_with(|| Held {
|
||||
document: document.clone(),
|
||||
tree: None,
|
||||
interests: HashSet::new(),
|
||||
reported: HashSet::new(),
|
||||
});
|
||||
ledger.diff(port, &held.interests, &interests);
|
||||
held.interests = interests;
|
||||
held.document = document;
|
||||
if let Some(tree) = resolution.tree {
|
||||
held.tree = Some(tree);
|
||||
}
|
||||
resolution.diagnostics
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +1,17 @@
|
|||
//! Resolve: the pure expansion of a surface document into a tree with no composition left in it.
|
||||
//! This is the only code that reads Thing Script structure (Use, Param, CommandRef, node ids).
|
||||
//! It reads compositions through `StatePort::read` and `thing.std` from a compiled-in table,
|
||||
//! holds no state, subscribes to nothing and never drains.
|
||||
//! holds no state, subscribes to nothing and never drains; `Resolver` is the stateful half.
|
||||
|
||||
mod expand;
|
||||
mod intake;
|
||||
pub mod std;
|
||||
mod validate;
|
||||
|
||||
use thing_contract::SurfaceDocument;
|
||||
|
||||
pub use intake::Resolver;
|
||||
|
||||
use crate::diagnostic::{Code, Diagnostic};
|
||||
use crate::port::{Address, StatePort};
|
||||
|
||||
|
|
|
|||
246
crates/thing-core/tests/intake.rs
Normal file
246
crates/thing-core/tests/intake.rs
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
//! The Resolver: the version rule (M9), the last good tree (M4), a late composition and the
|
||||
//! interests that follow what the held trees read.
|
||||
|
||||
use thing_contract::*;
|
||||
use thing_core::diagnostic::{Code, Diagnostic};
|
||||
use thing_core::port::{Address, Change, Entry, Interest, Ledger, Record, Refusal, StatePort, SubscriptionId};
|
||||
use thing_core::resolve::{Limits, Resolver};
|
||||
use thing_testkit::build::*;
|
||||
use thing_testkit::mem_state::{Call, MemState};
|
||||
|
||||
const PUB: &str = "pub.t";
|
||||
const PROVIDER: &str = "provider.t";
|
||||
|
||||
struct Rig {
|
||||
state: MemState,
|
||||
resolver: Resolver,
|
||||
ledger: Ledger,
|
||||
}
|
||||
|
||||
fn command_button(id: &str, command_id: &str) -> Node {
|
||||
Node::Button(ButtonNode { common: common(id), content: vec![], on_activate: command(command_id), enabled: lit_bool(true) })
|
||||
}
|
||||
|
||||
fn surface(label: &str, version: i64, children: Vec<Node>) -> SurfaceDocument {
|
||||
SurfaceDocument {
|
||||
provider_id: ProviderId::new(PROVIDER),
|
||||
label: seg(label),
|
||||
version: ver(version),
|
||||
title: format!("{label} v{version}"),
|
||||
root: boxed("root", children),
|
||||
commands: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn reference(name: &str) -> CompositionRef {
|
||||
CompositionRef { publisher: PUB.into(), name: seg(name), version: ver(1) }
|
||||
}
|
||||
|
||||
fn use_of(id: &str, name: &str) -> Node {
|
||||
Node::Use(UseNode { common: common(id), composition: reference(name), args: vec![] })
|
||||
}
|
||||
|
||||
fn composition(name: &str, body_text: &str) -> CompositionDocument {
|
||||
CompositionDocument { publisher: PUB.into(), name: seg(name), version: ver(1), params: vec![], body: text(&format!("{name}-body"), body_text) }
|
||||
}
|
||||
|
||||
fn comp_address(name: &str) -> Address {
|
||||
Address { provider: ProviderId::new(PUB), schema: SchemaId::new(CompositionDocument::SCHEMA_NAME), key: RecordKey::new(reference(name).record_key()) }
|
||||
}
|
||||
|
||||
fn surface_address(document: &SurfaceDocument) -> Address {
|
||||
Address {
|
||||
provider: document.provider_id.clone(),
|
||||
schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME),
|
||||
key: RecordKey::new(document.record_key()),
|
||||
}
|
||||
}
|
||||
|
||||
fn codes(diagnostics: &[Diagnostic]) -> Vec<Code> {
|
||||
diagnostics.iter().map(|diagnostic| diagnostic.code).collect()
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new() -> Self {
|
||||
Self { state: MemState::new(), resolver: Resolver::new(Limits::default()), ledger: Ledger::new() }
|
||||
}
|
||||
|
||||
fn apply(&mut self, change: Change) -> Vec<Diagnostic> {
|
||||
self.resolver.apply(&change, &mut self.state, &mut self.ledger)
|
||||
}
|
||||
|
||||
fn offer(&mut self, document: &SurfaceDocument) -> Vec<Diagnostic> {
|
||||
self.apply(Change::Upsert(Entry { address: surface_address(document), record: Record::Surface(document.clone()) }))
|
||||
}
|
||||
|
||||
fn put(&mut self, composition: &CompositionDocument) {
|
||||
self.state.put(&ProviderId::new(PUB), composition);
|
||||
}
|
||||
|
||||
/// Drain the port and apply each change, as the frame owner does.
|
||||
fn settle(&mut self) -> Vec<Diagnostic> {
|
||||
let mut diagnostics = Vec::new();
|
||||
for change in self.state.drain() {
|
||||
diagnostics.extend(self.apply(change));
|
||||
}
|
||||
diagnostics
|
||||
}
|
||||
|
||||
fn title(&self, key: &str) -> Option<String> {
|
||||
self.resolver.tree(key).map(|tree| tree.document().title.clone())
|
||||
}
|
||||
|
||||
fn shows(&self, key: &str, node: &str) -> bool {
|
||||
self.resolver.tree(key).is_some_and(|tree| format!("{:?}", tree.document().root).contains(node))
|
||||
}
|
||||
|
||||
/// Subscribes and unsubscribes so far: a subscribe as its address, an unsubscribe as the address
|
||||
/// that subscription was made for.
|
||||
fn interest_calls(&self) -> Vec<(bool, Address)> {
|
||||
let mut made: Vec<Address> = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
for call in self.state.calls() {
|
||||
match call {
|
||||
Call::Subscribe(Interest::Record(address)) => {
|
||||
made.push(address.clone());
|
||||
out.push((true, address));
|
||||
}
|
||||
Call::Subscribe(other) => panic!("not a record interest: {other:?}"),
|
||||
Call::Unsubscribe(SubscriptionId(id)) => out.push((false, made[id as usize].clone())),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_at_or_below_the_highest_offered_is_ignored_once() {
|
||||
let mut rig = Rig::new();
|
||||
let v1 = surface("main", 1, vec![]);
|
||||
let key = v1.record_key();
|
||||
assert!(rig.offer(&v1).is_empty());
|
||||
assert_eq!(rig.title(&key).as_deref(), Some("main v1"));
|
||||
|
||||
// Equal and lower: one diagnostic per version however often offered; the tree stays.
|
||||
let again = surface("main", 1, vec![boxed("other", vec![])]);
|
||||
let below = surface("main", 0, vec![]);
|
||||
assert_eq!(codes(&rig.offer(&again)), vec![Code::StaleVersionIgnored]);
|
||||
assert!(rig.offer(&again).is_empty());
|
||||
assert!(rig.offer(&v1).is_empty());
|
||||
assert_eq!(codes(&rig.offer(&below)), vec![Code::StaleVersionIgnored]);
|
||||
assert!(rig.offer(&below).is_empty());
|
||||
assert_eq!(rig.title(&key).as_deref(), Some("main v1"));
|
||||
assert!(!rig.shows(&key, "other"));
|
||||
|
||||
// A higher version replaces it.
|
||||
assert!(rig.offer(&surface("main", 2, vec![])).is_empty());
|
||||
assert_eq!(rig.title(&key).as_deref(), Some("main v2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_surface_that_fails_to_resolve_leaves_the_last_good_tree_displayed() {
|
||||
let mut rig = Rig::new();
|
||||
let v1 = surface("main", 1, vec![]);
|
||||
let key = v1.record_key();
|
||||
rig.offer(&v1);
|
||||
|
||||
let bad = surface("main", 2, vec![command_button("go", "undeclared")]);
|
||||
assert_eq!(codes(&rig.offer(&bad)), vec![Code::UndeclaredCommand]);
|
||||
assert_eq!(rig.title(&key).as_deref(), Some("main v1"));
|
||||
// The refused version was offered: it is stale now, not tried again.
|
||||
assert_eq!(codes(&rig.offer(&bad)), vec![Code::StaleVersionIgnored]);
|
||||
assert_eq!(rig.title(&key).as_deref(), Some("main v1"));
|
||||
|
||||
assert!(rig.offer(&surface("main", 3, vec![])).is_empty());
|
||||
assert_eq!(rig.title(&key).as_deref(), Some("main v3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_offer_that_fails_displays_nothing() {
|
||||
let mut rig = Rig::new();
|
||||
let bad = surface("main", 1, vec![command_button("go", "undeclared")]);
|
||||
rig.offer(&bad);
|
||||
assert!(rig.resolver.tree(&bad.record_key()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_surface_keeps_the_held_tree_and_is_not_a_delete() {
|
||||
let mut rig = Rig::new();
|
||||
let v1 = surface("main", 1, vec![]);
|
||||
let key = v1.record_key();
|
||||
rig.offer(&v1);
|
||||
let address = surface_address(&v1);
|
||||
let refusal = Refusal { kind: address.schema.clone(), address, detail: "unknown arm".into() };
|
||||
let diagnostics = rig.apply(Change::Refused(refusal));
|
||||
assert_eq!(codes(&diagnostics), vec![Code::DecodeRefused]);
|
||||
assert_eq!(diagnostics[0].surface, key);
|
||||
assert_eq!(rig.title(&key).as_deref(), Some("main v1"));
|
||||
// The version it was refused at was never taken: the same version is still the highest.
|
||||
assert_eq!(codes(&rig.offer(&v1)), vec![Code::StaleVersionIgnored]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_surface_is_dropped_and_its_version_forgotten() {
|
||||
let mut rig = Rig::new();
|
||||
let v1 = surface("main", 1, vec![]);
|
||||
rig.offer(&v1);
|
||||
rig.apply(Change::Delete(surface_address(&v1)));
|
||||
assert!(rig.resolver.tree(&v1.record_key()).is_none());
|
||||
assert!(rig.offer(&v1).is_empty());
|
||||
assert!(rig.resolver.tree(&v1.record_key()).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_composition_published_late_replaces_the_placeholder_without_a_republish() {
|
||||
let mut rig = Rig::new();
|
||||
let document = surface("main", 1, vec![use_of("ghost-use", "ghost")]);
|
||||
let key = document.record_key();
|
||||
assert_eq!(codes(&rig.offer(&document)), vec![Code::UnresolvedUse]);
|
||||
assert!(!rig.shows(&key, "ghost-body"));
|
||||
|
||||
rig.put(&composition("ghost", "boo"));
|
||||
assert!(rig.settle().is_empty());
|
||||
assert!(rig.shows(&key, "ghost-body"));
|
||||
|
||||
// It goes away: the placeholder returns, and the interest stays.
|
||||
rig.state.delete(&comp_address("ghost"));
|
||||
assert_eq!(codes(&rig.settle()), vec![Code::UnresolvedUse]);
|
||||
assert!(!rig.shows(&key, "ghost-body"));
|
||||
|
||||
// It comes back refused: a refusal is not absence.
|
||||
rig.state.put_raw(comp_address("ghost"), vec![0xc1]);
|
||||
assert_eq!(codes(&rig.settle()), vec![Code::DecodeRefused]);
|
||||
assert_eq!(rig.interest_calls().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interests_follow_what_the_held_trees_read() {
|
||||
let mut rig = Rig::new();
|
||||
let a1 = surface("a", 1, vec![use_of("u1", "one"), use_of("u2", "two")]);
|
||||
let b1 = surface("b", 1, vec![use_of("u1", "one")]);
|
||||
rig.put(&composition("one", "1"));
|
||||
rig.put(&composition("two", "2"));
|
||||
rig.offer(&a1);
|
||||
rig.offer(&b1);
|
||||
let (one, two) = (comp_address("one"), comp_address("two"));
|
||||
// One subscription per address however many surfaces read it.
|
||||
assert_eq!(rig.interest_calls(), vec![(true, one.clone()), (true, two.clone())]);
|
||||
|
||||
// Changes and re-applies never resubscribe what is held.
|
||||
rig.put(&composition("one", "1b"));
|
||||
rig.settle();
|
||||
rig.offer(&a1);
|
||||
assert_eq!(rig.interest_calls().len(), 2);
|
||||
|
||||
// A new version that stops reading `two` lets it go; `one` is untouched.
|
||||
rig.offer(&surface("a", 2, vec![use_of("u1", "one")]));
|
||||
assert_eq!(rig.interest_calls(), vec![(true, one.clone()), (true, two.clone()), (false, two.clone())]);
|
||||
|
||||
// A shared address is released only when its last reader goes.
|
||||
rig.apply(Change::Delete(surface_address(&a1)));
|
||||
assert_eq!(rig.interest_calls().len(), 3);
|
||||
rig.apply(Change::Delete(surface_address(&b1)));
|
||||
assert_eq!(rig.interest_calls().last(), Some(&(false, one)));
|
||||
assert_eq!(rig.interest_calls().len(), 4);
|
||||
}
|
||||
Loading…
Reference in a new issue