From f86a4836fc62937538301f00af5bd80e200a307c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 21:01:10 +0100 Subject: [PATCH] Thing 2.0 cut 7a: commands (one activate primitive, Drafts, minted invocations, result lifecycle, effects as data) thing_core::command owns invocation minting, the lifecycle (Issued, Pending, Completed, Denied, Failed, Malformed, TimedOut), result validation, timeouts and the confirm state. thing_core::input::Drafts is the one owner of uncommitted input values. Core::frame runs the step after the Binder's and returns outbound invocations and host effects; Config gains the invocation timeout and client kind; Ports gains an IdSource. Resolve refuses a capture that names no input. BoundTree::index replaces render's private index and Instance::scope_prefix is the one instance id scheme. Co-Authored-By: Claude Opus 5.5 --- crates/thing-core/src/bind/mod.rs | 22 + crates/thing-core/src/bind/repeat.rs | 7 +- crates/thing-core/src/bind/scope.rs | 111 +++ crates/thing-core/src/command/capture.rs | 89 ++ crates/thing-core/src/command/lifecycle.rs | 170 ++++ crates/thing-core/src/command/mod.rs | 427 +++++++++ crates/thing-core/src/command/validate.rs | 58 ++ crates/thing-core/src/diagnostic.rs | 16 +- crates/thing-core/src/frame.rs | 108 ++- crates/thing-core/src/input/drafts.rs | 47 + crates/thing-core/src/input/mod.rs | 5 +- crates/thing-core/src/lib.rs | 1 + crates/thing-core/src/port/mod.rs | 6 + crates/thing-core/src/render/mod.rs | 35 +- crates/thing-core/src/resolve/mod.rs | 2 +- crates/thing-core/src/resolve/validate.rs | 15 +- crates/thing-core/src/time.rs | 31 + crates/thing-core/tests/command.rs | 951 +++++++++++++++++++++ crates/thing-core/tests/frame.rs | 5 +- crates/thing-testkit/src/ids.rs | 58 ++ crates/thing-testkit/src/lib.rs | 1 + crates/thing-testkit/src/mem_state.rs | 5 +- crates/thing-testkit/src/store.rs | 3 + 23 files changed, 2118 insertions(+), 55 deletions(-) create mode 100644 crates/thing-core/src/bind/scope.rs create mode 100644 crates/thing-core/src/command/capture.rs create mode 100644 crates/thing-core/src/command/lifecycle.rs create mode 100644 crates/thing-core/src/command/mod.rs create mode 100644 crates/thing-core/src/command/validate.rs create mode 100644 crates/thing-core/src/input/drafts.rs create mode 100644 crates/thing-core/tests/command.rs create mode 100644 crates/thing-testkit/src/ids.rs diff --git a/crates/thing-core/src/bind/mod.rs b/crates/thing-core/src/bind/mod.rs index 7081e45..835fb44 100644 --- a/crates/thing-core/src/bind/mod.rs +++ b/crates/thing-core/src/bind/mod.rs @@ -8,8 +8,11 @@ mod format; mod repeat; +mod scope; mod walk; +pub use scope::Located; + use std::collections::{BTreeMap, HashMap, HashSet}; use thing_contract::{AssetEntry, NodeId, SelectOption}; @@ -81,9 +84,14 @@ pub enum Bound { /// 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. +/// +/// The one id scheme is `scope_prefix`: an id inside an instance is its prefix followed by the +/// template's id, so a node in nested instances is the inner prefix, then the outer, then its declared id. #[derive(Clone, Debug, PartialEq)] pub struct Instance { pub key: String, + /// What `Instance::scope_prefix` derived for this instance: each of the template's ids is this followed by the template id. + pub prefix: String, pub root: thing_contract::Node, } @@ -344,3 +352,17 @@ impl Binder { self.surfaces.get(surface).map(|surface| &surface.bound) } } + +impl Instance { + /// The prefix of every id of the instance of `repeat` (a laid id) whose key is `key`: + /// `#:/`; an item the port refused has no key to read, so its + /// identity is its record key in the distinct form `!:/`. Resolve's + /// instance ids and command captures both derive scope here, so there is one scheme. + pub fn scope_prefix(repeat: &str, key: &str, refused: bool) -> String { + if refused { + format!("{repeat}!{}:{key}/", key.len()) + } else { + format!("{repeat}#{}:{key}/", key.len()) + } + } +} diff --git a/crates/thing-core/src/bind/repeat.rs b/crates/thing-core/src/bind/repeat.rs index 2f5da1b..16d92cc 100644 --- a/crates/thing-core/src/bind/repeat.rs +++ b/crates/thing-core/src/bind/repeat.rs @@ -159,20 +159,21 @@ impl Walker<'_> { let (key, prefix) = match &entry.item { Item::Fault(_) => { let record = entry.record_key.clone().unwrap_or_default(); - (format!("!{record}"), format!("{id}!{}:{record}/", record.len())) + let prefix = Instance::scope_prefix(id, &record, true); + (format!("!{record}"), prefix) } 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()); + let prefix = Instance::scope_prefix(id, &key, false); (key, prefix) } }; let mut root = (*repeat.template).clone(); rewrite(&mut root, &prefix, &inside); - built.push((Instance { key, root }, entry.item)); + built.push((Instance { key, prefix, root }, entry.item)); } let mut ids = Vec::new(); diff --git a/crates/thing-core/src/bind/scope.rs b/crates/thing-core/src/bind/scope.rs new file mode 100644 index 0000000..58d2948 --- /dev/null +++ b/crates/thing-core/src/bind/scope.rs @@ -0,0 +1,111 @@ +//! Where a node sits in a bound tree: the one id -> node index, and the Repeat instances that +//! enclose a node, which commands read to name a row and to find the inputs beside a button. + +use std::collections::HashMap; + +use thing_contract::{Node, NodeId}; + +use super::walk::{children, common}; +use super::BoundTree; +use crate::resolve::grow; + +/// A node and the Repeat instances around it, read off the tree. +#[derive(Clone, Debug, PartialEq)] +pub struct Located<'a> { + pub node: &'a Node, + /// The id the author declared: the laid id with its instance prefixes removed. + pub declared: NodeId, + /// The prefix of each enclosing instance, innermost first. An id declared at the top of the + /// document, reached from here, is these joined in order followed by it. + pub prefixes: Vec, + /// The key of each enclosing instance, outermost first. + pub items: Vec, +} + +struct Walk<'a, 'b> { + tree: &'a BoundTree, + prefixes: Vec<&'a str>, + items: Vec<&'a str>, + visit: &'b mut dyn FnMut(Located<'a>) -> bool, +} + +impl<'a> Walk<'a, '_> { + /// Visit the node, then what it holds; stops (`true`) as soon as a visit says so. + fn node(&mut self, node: &'a Node) -> bool { + grow(|| { + let Some(common) = common(node) else { return false }; + let skip: usize = self.prefixes.iter().map(|prefix| prefix.len()).sum(); + let declared = NodeId::new(common.id.as_str().get(skip..).unwrap_or(common.id.as_str())); + let located = Located { + node, + declared, + prefixes: self.prefixes.iter().rev().map(|prefix| prefix.to_string()).collect(), + items: self.items.iter().map(|item| item.to_string()).collect(), + }; + if (self.visit)(located) { + return true; + } + if let Node::Repeat(repeat) = node { + for instance in self.tree.instances(&repeat.common.id) { + self.prefixes.push(&instance.prefix); + self.items.push(&instance.key); + let stop = self.node(&instance.root); + self.prefixes.pop(); + self.items.pop(); + if stop { + return true; + } + } + return false; + } + children(node).iter().any(|child| self.node(child)) + }) + } +} + +impl BoundTree { + /// Every node of the document by laid id, Repeat instances included (ids are unique after + /// resolve). The one index render, hit-test and commands share. + pub fn index(&self) -> HashMap<&NodeId, &Node> { + let mut found = HashMap::new(); + self.walk(&mut |located| { + if let Some(common) = common(located.node) { + found.insert(&common.id, located.node); + } + false + }); + found + } + + /// The node with laid id `id`, and where it sits. + pub fn locate(&self, id: &NodeId) -> Option> { + let mut found = None; + self.walk(&mut |located| { + let hit = common(located.node).is_some_and(|common| &common.id == id); + if hit { + found = Some(located); + } + hit + }); + found + } + + /// The first node declared as `declared` inside the instances keyed `items` (outermost first). + pub fn locate_source(&self, declared: &NodeId, items: &[String]) -> Option> { + let mut found = None; + self.walk(&mut |located| { + let hit = &located.declared == declared && located.items == items; + if hit { + found = Some(located); + } + hit + }); + found + } + + fn walk<'a>(&'a self, visit: &mut dyn FnMut(Located<'a>) -> bool) { + let mut walk = Walk { tree: self, prefixes: Vec::new(), items: Vec::new(), visit }; + walk.node(&self.resolved().document().root); + } +} + diff --git a/crates/thing-core/src/command/capture.rs b/crates/thing-core/src/command/capture.rs new file mode 100644 index 0000000..3179429 --- /dev/null +++ b/crates/thing-core/src/command/capture.rs @@ -0,0 +1,89 @@ +//! Captures: the values an invocation carries, read at the user's action from the drafts over the +//! bound values. An input beside a button in a Repeat row is found by scope: the activating node's +//! innermost instance first, then outward, then the declared id itself. + +use std::collections::HashMap; + +use thing_contract::{BoolValue, CapturedInput, ChoiceValue, CommandDecl, InputKind, InputValue, Node, NodeId, NumberValue, TextValue}; + +use crate::bind::{Bound, BoundTree, Field}; +use crate::input::Drafts; + +/// What the captures of one command came to: the values to send, and the laid ids they were read +/// from (the drafts a completed result clears). +pub(super) struct Captured { + pub inputs: Vec, + pub laid: Vec, +} + +/// The laid id of `declared` as seen from a node whose enclosing instance prefixes are `scope` +/// (innermost first): the most specific one the tree holds. +pub(super) fn laid_id(index: &HashMap<&NodeId, &Node>, scope: &[String], declared: &NodeId) -> Option { + (0..=scope.len()) + .map(|start| NodeId::new(format!("{}{}", scope[start..].concat(), declared.as_str()))) + .find(|candidate| index.contains_key(candidate)) +} + +fn number(text: &str) -> Option { + text.trim().parse::().ok().filter(|value| value.is_finite()) +} + +/// The value one input sends: its draft when it has one of the right kind, else what it is bound to. +fn value(tree: &BoundTree, drafts: &Drafts, surface: &str, laid: &NodeId, node: &Node) -> Option { + let draft = drafts.get(surface, laid); + let bound = |field| tree.value(laid, field); + match node { + Node::Toggle(_) => match (draft, bound(Field::Checked)) { + (Some(InputValue::Bool(held)), _) => Some(InputValue::Bool(held.clone())), + (_, Some(Bound::Bool(checked))) => Some(InputValue::Bool(BoolValue { value: *checked })), + _ => None, + }, + Node::Slider(_) => match (draft, bound(Field::Value)) { + (Some(InputValue::Number(held)), _) => Some(InputValue::Number(held.clone())), + (_, Some(Bound::Number(at))) => Some(InputValue::Number(NumberValue { value: *at })), + _ => None, + }, + Node::Select(_) => match (draft, bound(Field::Selected)) { + (Some(InputValue::Choice(held)), _) => Some(InputValue::Choice(held.clone())), + (_, Some(Bound::Text(selected))) => Some(InputValue::Choice(ChoiceValue { value: selected.clone() })), + _ => None, + }, + Node::TextInput(input) => { + let initial = match bound(Field::Initial) { + Some(Bound::Text(text)) => Some(text.as_str()), + _ => None, + }; + match input.input_kind { + InputKind::Text => match (draft, initial) { + (Some(InputValue::Text(held)), _) => Some(InputValue::Text(held.clone())), + (_, Some(text)) => Some(InputValue::Text(TextValue { value: text.to_string() })), + _ => None, + }, + InputKind::Number => { + let typed = match draft { + Some(InputValue::Text(held)) => number(&held.value), + Some(InputValue::Number(held)) => Some(held.value).filter(|value| value.is_finite()), + _ => initial.and_then(number), + }; + typed.map(|value| InputValue::Number(NumberValue { value })) + } + } + } + _ => None, + } +} + +/// The captures of `decl`, in declared order, resolved from the scope of the activating node. The +/// error is the declared id of the first capture with no value to send. +pub(super) fn capture(tree: &BoundTree, drafts: &Drafts, surface: &str, scope: &[String], decl: &CommandDecl) -> Result { + let index = tree.index(); + let mut captured = Captured { inputs: Vec::new(), laid: Vec::new() }; + for declared in &decl.captures { + let laid = laid_id(&index, scope, declared).ok_or_else(|| declared.clone())?; + let node = index.get(&laid).ok_or_else(|| declared.clone())?; + let value = value(tree, drafts, surface, &laid, node).ok_or_else(|| declared.clone())?; + captured.inputs.push(CapturedInput { node: declared.clone(), value }); + captured.laid.push(laid); + } + Ok(captured) +} diff --git a/crates/thing-core/src/command/lifecycle.rs b/crates/thing-core/src/command/lifecycle.rs new file mode 100644 index 0000000..0733ccb --- /dev/null +++ b/crates/thing-core/src/command/lifecycle.rs @@ -0,0 +1,170 @@ +//! The invocation lifecycle: `Issued -> Pending* -> Completed | Denied | Failed`, with the core-only +//! terminal states `Malformed` and `TimedOut`. Terminal is final: a later result is a diagnostic, +//! never a state change. Core decides every transition; a provider only offers results. + +use thing_contract::{CommandResult, DatabaseEntry, Outcome}; + +use super::{Commands, HostEffect, Live, Mark, State, capture, fault, validate}; +use crate::bind::BoundTree; +use crate::diagnostic::{Code, Diagnostic}; +use crate::input::Drafts; +use crate::port::{Change, Ledger, Record, StatePort}; +use crate::time::Timestamp; + +/// What one drained change did: the effects for the host to run, and what core says about it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Answered { + pub effects: Vec, + pub diagnostics: Vec, +} + +impl Commands { + /// One drained change. Only a command result is this module's; any other address is not and + /// answers empty. A result under no held invocation is `UnknownInvocation`, logged only. + /// `trees` finds a surface's bound tree by record key. + pub fn apply<'t>( + &mut self, + change: &Change, + now: Timestamp, + trees: &dyn Fn(&str) -> Option<&'t BoundTree>, + drafts: &mut Drafts, + port: &mut dyn StatePort, + ledger: &mut Ledger, + ) -> Answered { + let mut answered = Answered::default(); + let address = match change { + Change::Upsert(entry) => &entry.address, + Change::Delete(address) => address, + Change::Refused(refusal) => &refusal.address, + }; + if address.schema.as_str() != CommandResult::SCHEMA_NAME { + return answered; + } + let Some(at) = self.live.iter().position(|live| live.interest.matches(address)) else { + if !matches!(change, Change::Delete(_)) { + answered.diagnostics.push(fault( + address.key.as_str(), + None, + Code::UnknownInvocation, + "no invocation of this id is held", + )); + } + return answered; + }; + if matches!(change, Change::Delete(_)) { + return answered; + } + let surface = self.live[at].surface.clone(); + let issuing = self.live[at].issuing.clone(); + if self.live[at].state.is_terminal() { + answered.diagnostics.push(fault(&surface, issuing.as_ref(), Code::ResultAfterTerminal, "the invocation is already terminal")); + return answered; + } + let result = match change { + Change::Upsert(entry) => match &entry.record { + // One equality catches a body naming another invocation, and a seq that is not the key's. + Record::Result(result) if result.record_key() == address.key.as_str() => result, + Record::Result(_) => { + self.malformed(at, "the result is not the one its key names", &mut answered, port, ledger); + return answered; + } + _ => { + self.malformed(at, "the record at a result address is not a result", &mut answered, port, ledger); + return answered; + } + }, + _ => { + self.malformed(at, "the result was refused at decode", &mut answered, port, ledger); + return answered; + } + }; + let seq = result.seq().get(); + if seq <= self.live[at].highest { + return answered; + } + self.live[at].highest = seq; + match result.outcome() { + Outcome::Pending(pending) => { + self.live[at].state = State::Pending(pending.message.clone()); + self.live[at].deadline = now.plus_ms(self.timeout_ms); + } + Outcome::Completed(completed) => { + let effect = match &completed.effect { + None => None, + Some(effect) => match validate::effect(effect, trees(&surface), &self.live[at]) { + Ok(effect) => Some(effect), + Err(detail) => { + self.malformed(at, &detail, &mut answered, port, ledger); + return answered; + } + }, + }; + if completed.clear_drafts { + drafts.clear(&surface, &self.live[at].laid); + } + answered.effects.extend(effect); + self.settle(at, State::Completed, None, port, ledger); + } + Outcome::Denied(denied) => { + let mut target = issuing.clone(); + if let Some(declared) = &denied.node { + let found = trees(&surface).and_then(|tree| capture::laid_id(&tree.index(), &self.live[at].scope, declared)); + match found { + Some(laid) => target = Some(laid), + None => answered.diagnostics.push(fault( + &surface, + issuing.as_ref(), + Code::MalformedResult, + "denied node not in the surface", + )), + } + } + self.settle(at, State::Denied, None, port, ledger); + if let Some(node) = target { + self.marks.insert((surface, node), Mark::Denied { reason: denied.reason.clone() }); + } + } + Outcome::Failed(failed) => { + self.settle(at, State::Failed, Some(Mark::Failed { reason: failed.reason.clone() }), port, ledger); + } + } + answered + } + + /// Move every non-terminal invocation whose deadline has come to `TimedOut`. A deadline is + /// compared with the time given: a wall clock that went backward delays a timeout, never fires one early. + pub fn tick(&mut self, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec { + let mut diagnostics = Vec::new(); + for at in 0..self.live.len() { + let live = &self.live[at]; + if !live.state.is_terminal() && live.deadline <= now { + diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::InvocationTimedOut, "no result by the deadline")); + self.settle(at, State::TimedOut, Some(Mark::TimedOut), port, ledger); + } + } + diagnostics + } + + /// The earliest deadline of an invocation still waiting; the frame's `next_wake`. + pub fn next_deadline(&self) -> Option { + self.live.iter().filter(|live| !live.state.is_terminal()).map(|live: &Live| live.deadline).min() + } + + /// A result core will not take: the invocation is `Malformed`, and nothing it carried runs. + fn malformed(&mut self, at: usize, detail: &str, answered: &mut Answered, port: &mut dyn StatePort, ledger: &mut Ledger) { + let live = &self.live[at]; + answered.diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::MalformedResult, detail)); + self.settle(at, State::Malformed, Some(Mark::Malformed), port, ledger); + } + + /// Enter a terminal state: the interest in results is released in the same call, and the + /// issuing node shows the mark. + fn settle(&mut self, at: usize, state: State, mark: Option, port: &mut dyn StatePort, ledger: &mut Ledger) { + let live = &mut self.live[at]; + live.state = state; + ledger.release(port, &live.interest); + if let (Some(mark), Some(node)) = (mark, &live.issuing) { + self.marks.insert((live.surface.clone(), node.clone()), mark); + } + } +} diff --git a/crates/thing-core/src/command/mod.rs b/crates/thing-core/src/command/mod.rs new file mode 100644 index 0000000..6431661 --- /dev/null +++ b/crates/thing-core/src/command/mod.rs @@ -0,0 +1,427 @@ +//! Commands: the one owner of invocation minting, the invocation lifecycle and result validation. +//! It follows the Resolver and Binder: it is handed what the frame drained and never drains, reads +//! no clock (time is a parameter) and awaits nothing. Core writes no record but an invocation, and +//! that leaves through `take_outbound`, never through a port. +//! +//! Every way of minting (a press, a key, a confirmed dialog, a resume after an external step) +//! ends in `mint`. A user action mints one id; nothing re-mints. + +mod capture; +mod lifecycle; +mod validate; + +use std::collections::HashMap; + +use thing_contract::{ + CapturedInput, CommandDecl, CommandId, CommandInvocation, CommandRef, CommandResult, DatabaseEntry, InputValue, Node, NodeId, + ProviderId, RecordPayload, SchemaId, Seq, Version, +}; + +use crate::bind::{Bound, BoundTree, Field}; +use crate::diagnostic::{Code, Diagnostic}; +use crate::input::Drafts; +use crate::port::{IdSource, Interest, Ledger, Prefix, StatePort}; +use crate::time::Timestamp; + +pub use lifecycle::Answered; + +/// The empty MessagePack array: a payload record with no slots. Thing Script has no payload source yet. +const EMPTY_PAYLOAD: [u8; 1] = [0x90]; + +/// What the user did to one node. +#[derive(Clone, Debug, PartialEq)] +pub struct Activation { + /// The laid id, instance ids included. + pub node: NodeId, + pub kind: ActivationKind, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ActivationKind { + /// A Button or an Overlay's dismissal. + Press, + /// A Toggle, a Slider or a Select took a value; it is written to Drafts first, then the command fires. + Change(InputValue), + /// A TextInput's submit. + Submit, +} + +/// What the host runs for a provider's result. Closed. +#[derive(Clone, Debug, PartialEq)] +pub enum HostEffect { + OpenSurface { key: String }, + OpenExternal { url: String, resume: Resume }, +} + +/// The command to run when an external step returns. The host holds it across a navigation (the +/// session dies on `location.assign`) and hands it to `Core::resume`. `source` and `items` are the +/// invocation's, so a resumed command names the same row. +#[derive(Clone, Debug, PartialEq)] +pub struct Resume { + pub surface_key: String, + pub command: CommandId, + pub source: NodeId, + pub items: Vec, +} + +/// Why a node shows a fault: the last terminal answer of an invocation issued from it, until it mints again. +#[derive(Clone, Debug, PartialEq)] +pub enum Mark { + Denied { reason: String }, + Failed { reason: String }, + Malformed, + TimedOut, +} + +/// What render and accessibility read of one node. Derived from the live invocations; nothing is +/// stored on a node. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct NodeState { + /// A non-terminal invocation was issued from this node. + pub busy: bool, + pub mark: Option, + /// The message of the latest Pending result of a busy node's invocation. + pub pending: Option, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct NodeStates { + nodes: HashMap, +} + +impl NodeStates { + /// The state of a laid node; a node nothing happened to is the default. + pub fn get(&self, node: &NodeId) -> NodeState { + self.nodes.get(node).cloned().unwrap_or_default() + } +} + +/// A command waiting for the user's yes. Its captures are the values at the user's action. +#[derive(Clone, Debug, PartialEq)] +pub struct Confirming { + pub surface: String, + pub node: NodeId, + pub command: CommandId, + pub text: String, + prepared: Prepared, +} + +impl Confirming { + pub fn captured(&self) -> &[CapturedInput] { + &self.prepared.captured + } +} + +/// Everything an invocation is except its id and its time: what a confirm holds until the user answers. +#[derive(Clone, Debug, PartialEq)] +struct Prepared { + surface: String, + provider: ProviderId, + version: Version, + command: CommandId, + payload_schema: SchemaId, + captured: Vec, + laid: Vec, + source: NodeId, + items: Vec, + /// The laid node the user acted on; a resume has none. + issuing: Option, + /// The instance prefixes around the issuing node, innermost first. + scope: Vec, +} + +/// An invocation core issued. Terminal ones stay so a late result is judged, not lost. +#[derive(Clone, Debug)] +struct Live { + surface: String, + issuing: Option, + state: State, + /// The highest result `seq` taken. + highest: i32, + deadline: Timestamp, + laid: Vec, + scope: Vec, + interest: Interest, + source: NodeId, + items: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +enum State { + Issued, + Pending(String), + Completed, + Denied, + Failed, + Malformed, + TimedOut, +} + +impl State { + fn is_terminal(&self) -> bool { + !matches!(self, State::Issued | State::Pending(_)) + } +} + +pub struct Commands { + client: String, + timeout_ms: u32, + live: Vec, + marks: HashMap<(String, NodeId), Mark>, + confirming: Option, + outbound: Vec, +} + +fn fault(surface: &str, node: Option<&NodeId>, code: Code, detail: impl Into) -> Diagnostic { + Diagnostic { code, surface: surface.to_string(), node: node.cloned(), detail: detail.into() } +} + +/// A v4 UUID from 16 bytes: the version and variant bits are core's, so a minted id is always +/// UUID-shaped and dot-free (a result key splits at its last dot). +fn uuid(ids: &mut dyn IdSource) -> String { + let mut bytes = [0u8; 16]; + ids.fill(&mut bytes); + bytes[6] = bytes[6] & 0x0f | 0x40; + bytes[8] = bytes[8] & 0x3f | 0x80; + let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect(); + format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32]) +} + +/// The key prefix every result of `invocation` shares, derived from the contract's one key +/// scheme: a result's key is this followed by its `seq`. +fn result_prefix(invocation: &CommandInvocation) -> String { + let key = CommandResult::pending(invocation, Seq::FIRST, "").record_key(); + key[..key.rfind('.').map_or(key.len(), |dot| dot + 1)].to_string() +} + +/// The command a node fires for an activation, when the node takes that kind of activation. +fn command_of<'a>(node: &'a Node, kind: &ActivationKind) -> Option<&'a CommandRef> { + match (node, kind) { + (Node::Button(n), ActivationKind::Press) => Some(&n.on_activate), + (Node::Overlay(n), ActivationKind::Press) => Some(&n.dismiss), + (Node::TextInput(n), ActivationKind::Submit) => Some(&n.submit), + (Node::Toggle(n), ActivationKind::Change(InputValue::Bool(_))) => Some(&n.on_change), + (Node::Slider(n), ActivationKind::Change(InputValue::Number(_))) => Some(&n.commit), + (Node::Select(n), ActivationKind::Change(InputValue::Choice(_))) => Some(&n.on_change), + _ => None, + } +} + +/// Where a command is fired from: the declared id of its source, and the instances around it. +struct Origin { + issuing: Option, + source: NodeId, + scope: Vec, + items: Vec, +} + +impl Commands { + pub fn new(client: impl Into, timeout_ms: u32) -> Self { + Self { + client: client.into(), + timeout_ms, + live: Vec::new(), + marks: HashMap::new(), + confirming: None, + outbound: Vec::new(), + } + } + + /// The one commit primitive: the user acted on `act.node` of `tree`. Every path calls it. It + /// mints one invocation, or nothing: a node that is not a command source, a disabled or busy + /// button, an input with nothing to send, or a command waiting on confirmation. + #[allow(clippy::too_many_arguments)] + pub fn activate( + &mut self, + act: Activation, + tree: &BoundTree, + drafts: &mut Drafts, + now: Timestamp, + ids: &mut dyn IdSource, + port: &mut dyn StatePort, + ledger: &mut Ledger, + ) -> Vec { + if self.confirming.is_some() { + return Vec::new(); + } + let surface = tree.resolved().document().record_key(); + let Some(located) = tree.locate(&act.node) else { return Vec::new() }; + let Some(CommandRef::Id(command)) = command_of(located.node, &act.kind) else { return Vec::new() }; + if let ActivationKind::Change(value) = &act.kind { + drafts.set(&surface, &act.node, value.clone()); + } + if matches!(located.node, Node::Button(_)) && tree.value(&act.node, Field::Enabled) == Some(&Bound::Bool(false)) { + return Vec::new(); + } + if self.busy(&surface, &act.node) { + return Vec::new(); + } + let Some(decl) = tree.resolved().document().commands.iter().find(|decl| decl.id == command.id) else { + return vec![fault(&surface, Some(&act.node), Code::UndeclaredCommand, "the command is not declared")]; + }; + let origin = Origin { + issuing: Some(act.node.clone()), + source: located.declared, + scope: located.prefixes, + items: located.items, + }; + let prepared = match self.prepare(tree, drafts, decl, origin) { + Ok(prepared) => prepared, + Err(diagnostic) => return vec![diagnostic], + }; + match &decl.confirm { + Some(text) => { + self.confirming = + Some(Confirming { surface, node: act.node, command: decl.id.clone(), text: text.clone(), prepared }); + } + None => self.mint(prepared, now, ids, port, ledger), + } + Vec::new() + } + + /// Answer the command waiting on confirmation. Accepting mints with the captures taken at the + /// user's action; rejecting drops it and draws no id. + pub fn confirm(&mut self, accept: bool, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) { + if let Some(confirming) = self.confirming.take() + && accept + { + self.mint(confirming.prepared, now, ids, port, ledger); + } + } + + pub fn confirming(&self) -> Option<&Confirming> { + self.confirming.as_ref() + } + + /// Run the command an external step named, as the invocation that asked for it: its declared + /// captures, its source and items, no issuing node (nothing is marked busy). + #[allow(clippy::too_many_arguments)] + pub fn resume( + &mut self, + resume: &Resume, + tree: &BoundTree, + drafts: &Drafts, + now: Timestamp, + ids: &mut dyn IdSource, + port: &mut dyn StatePort, + ledger: &mut Ledger, + ) -> Vec { + let surface = tree.resolved().document().record_key(); + let decl = tree.resolved().document().commands.iter().find(|decl| decl.id == resume.command); + let (Some(decl), true) = (decl, surface == resume.surface_key) else { + return vec![fault(&surface, None, Code::UndeclaredCommand, "the command to resume is not declared at the held version")]; + }; + let scope = tree.locate_source(&resume.source, &resume.items).map(|located| located.prefixes).unwrap_or_default(); + let origin = Origin { issuing: None, source: resume.source.clone(), scope, items: resume.items.clone() }; + match self.prepare(tree, drafts, decl, origin) { + Ok(prepared) => { + self.mint(prepared, now, ids, port, ledger); + Vec::new() + } + Err(diagnostic) => vec![diagnostic], + } + } + + /// The invocations minted since the last call, in order. + pub fn take_outbound(&mut self) -> Vec { + std::mem::take(&mut self.outbound) + } + + /// What render and accessibility read for `surface`. + pub fn view(&self, surface: &str) -> NodeStates { + let mut nodes: HashMap = HashMap::new(); + for ((held, node), mark) in &self.marks { + if held == surface { + nodes.entry(node.clone()).or_default().mark = Some(mark.clone()); + } + } + for live in self.live.iter().filter(|live| live.surface == surface && !live.state.is_terminal()) { + if let Some(node) = &live.issuing { + let state = nodes.entry(node.clone()).or_default(); + state.busy = true; + if let State::Pending(message) = &live.state { + state.pending = Some(message.clone()); + } + } + } + NodeStates { nodes } + } + + /// The surface is no longer shown: its invocations leave the table with their interests, its + /// marks go and a confirmation waiting on it is dropped. + pub fn forget(&mut self, surface: &str, port: &mut dyn StatePort, ledger: &mut Ledger) { + for live in self.live.iter().filter(|live| live.surface == surface && !live.state.is_terminal()) { + ledger.release(port, &live.interest); + } + self.live.retain(|live| live.surface != surface); + self.marks.retain(|(held, _), _| held != surface); + if self.confirming.as_ref().is_some_and(|confirming| confirming.surface == surface) { + self.confirming = None; + } + } + + fn busy(&self, surface: &str, node: &NodeId) -> bool { + self.live.iter().any(|live| !live.state.is_terminal() && live.surface == surface && live.issuing.as_ref() == Some(node)) + } + + fn prepare(&self, tree: &BoundTree, drafts: &Drafts, decl: &CommandDecl, origin: Origin) -> Result { + let document = tree.resolved().document(); + let surface = document.record_key(); + let captured = capture::capture(tree, drafts, &surface, &origin.scope, decl).map_err(|node| { + fault(&surface, Some(&node), Code::CaptureUnavailable, "the captured input has no value to send") + })?; + Ok(Prepared { + surface, + provider: document.provider_id.clone(), + version: document.version, + command: decl.id.clone(), + payload_schema: decl.payload_schema.clone(), + captured: captured.inputs, + laid: captured.laid, + source: origin.source, + items: origin.items, + issuing: origin.issuing, + scope: origin.scope, + }) + } + + /// The one mint: draw one id, hold the interest in its results before the host can send, and + /// queue the invocation. + fn mint(&mut self, prepared: Prepared, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) { + let invocation = CommandInvocation { + invocation_id: uuid(ids), + surface_key: prepared.surface.clone(), + surface_version: prepared.version, + command: prepared.command, + payload: RecordPayload { schema: prepared.payload_schema, bytes: EMPTY_PAYLOAD.to_vec() }, + captured: prepared.captured, + client: self.client.clone(), + issued_at: now.rfc3339(), + delegation: None, + source: prepared.source.clone(), + items: prepared.items.clone(), + }; + let interest = Interest::Prefix(Prefix { + provider: prepared.provider, + schema: SchemaId::new(CommandResult::SCHEMA_NAME), + key_prefix: result_prefix(&invocation), + }); + ledger.hold(port, &interest); + if let Some(node) = &prepared.issuing { + self.marks.remove(&(prepared.surface.clone(), node.clone())); + } + self.live.push(Live { + surface: prepared.surface, + issuing: prepared.issuing, + state: State::Issued, + highest: 0, + deadline: now.plus_ms(self.timeout_ms), + laid: prepared.laid, + scope: prepared.scope, + interest, + source: prepared.source, + items: prepared.items, + }); + self.outbound.push(invocation); + } +} diff --git a/crates/thing-core/src/command/validate.rs b/crates/thing-core/src/command/validate.rs new file mode 100644 index 0000000..fd6a9f7 --- /dev/null +++ b/crates/thing-core/src/command/validate.rs @@ -0,0 +1,58 @@ +//! What core will run for a provider's result: the closed effects, judged before any is emitted. +//! A provider decides what to ask; core decides whether it is allowed. + +use thing_contract::{CommandId, CommandRef, Effect}; + +use super::{HostEffect, Live, Resume}; +use crate::bind::BoundTree; + +/// Whether `url` is absolute with the scheme http or https (ASCII case-insensitive) and a host. +fn web_url(url: &str) -> bool { + if url.chars().any(|c| c.is_control() || c.is_whitespace()) { + return false; + } + let Some((scheme, rest)) = url.split_once("://") else { return false }; + (scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")) + && !rest.starts_with(['/', '?', '#']) + && !rest.is_empty() +} + +/// The effect as data for the host, or why core refuses it. `tree` is the invocation's surface as +/// held now: a resume names a command that surface declares. +pub(super) fn effect(effect: &Effect, tree: Option<&BoundTree>, live: &Live) -> Result { + match effect { + Effect::OpenSurface(open) => { + if open.key.starts_with("thing:surface:") { + Ok(HostEffect::OpenSurface { key: open.key.clone() }) + } else { + Err("OpenSurface names a key that is not a surface".into()) + } + } + Effect::OpenExternal(open) => { + if !web_url(&open.url) { + return Err("OpenExternal names a url that is not absolute http or https".into()); + } + let CommandRef::Id(resume) = &open.resume else { + return Err("OpenExternal resumes through a parameter".into()); + }; + let declared = tree.is_some_and(|tree| declares(tree, &resume.id)); + if !declared { + return Err("OpenExternal resumes a command the surface does not declare".into()); + } + Ok(HostEffect::OpenExternal { + url: open.url.clone(), + resume: Resume { + surface_key: live.surface.clone(), + command: resume.id.clone(), + source: live.source.clone(), + items: live.items.clone(), + }, + }) + } + } +} + +pub(super) fn declares(tree: &BoundTree, command: &CommandId) -> bool { + tree.resolved().document().commands.iter().any(|decl| &decl.id == command) +} + diff --git a/crates/thing-core/src/diagnostic.rs b/crates/thing-core/src/diagnostic.rs index b9925a8..5625d05 100644 --- a/crates/thing-core/src/diagnostic.rs +++ b/crates/thing-core/src/diagnostic.rs @@ -45,12 +45,26 @@ pub enum Code { OverlayAnchorMissing, /// A colour or text token the theme does not hold; it drew as the fallback colour. ThemeTokenUnknown, + /// A result that could not be taken: refused by decode, not a result, filed under another key than its + /// own, or carrying an effect core will not run. The invocation is Malformed. + MalformedResult, + /// A result under the result key space for an invocation core does not hold. + UnknownInvocation, + /// A result for an invocation already terminal; the state does not change. + ResultAfterTerminal, + /// An invocation with no result by its deadline; it is TimedOut. + InvocationTimedOut, + /// A capture whose input has no value to send (a bound error, absent, or a number that does not parse); + /// nothing was minted. + CaptureUnavailable, + /// A command capture naming no node, or a node that holds no input value. + CaptureUndeclared, } impl Code { /// Whether the fault leaves no tree (the whole document is refused) or only a placeholder. pub fn refuses_document(self) -> bool { - matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve) + matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve | Code::CaptureUndeclared) } } diff --git a/crates/thing-core/src/frame.rs b/crates/thing-core/src/frame.rs index b732cc0..2a8a42e 100644 --- a/crates/thing-core/src/frame.rs +++ b/crates/thing-core/src/frame.rs @@ -3,13 +3,16 @@ //! `StatePort::drain`; it reads no clock, sleeps nowhere and never awaits. Later cuts extend //! `frame` in place with their own step; there is no second entry. -use thing_contract::{DatabaseEntry, ProviderId, RecordKey, SchemaId, SurfaceDocument}; +use thing_contract::{CommandInvocation, DatabaseEntry, ProviderId, RecordKey, SchemaId, SurfaceDocument}; + +use std::collections::HashSet; use crate::bind::Binder; +use crate::command::{Activation, Commands, Confirming, HostEffect, NodeStates, Resume}; use crate::diagnostic::Diagnostic; -use crate::input::InputEvent; +use crate::input::{Drafts, InputEvent}; use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout}; -use crate::port::{Address, Change, Interest, Ledger, Lookup, StatePort}; +use crate::port::{Address, Change, IdSource, Interest, Ledger, Lookup, StatePort}; use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, render}; use crate::resolve::{Limits, Resolver}; use crate::theme::Theme; @@ -20,11 +23,17 @@ use crate::time::Timestamp; pub struct Config { pub limits: Limits, pub metrics: Metrics, + /// How long an invocation waits for a result, and for the next one after a Pending (a heartbeat). + /// A guess, to be measured (build-spec O5). + pub invocation_timeout_ms: u32, + /// The kind of host core runs in (`renderer.web`, `renderer.tui`), written to every invocation. It + /// is never a caller identity: core has no identity to write, the transport sets it. + pub client: String, } impl Config { - pub fn new(metrics: Metrics) -> Self { - Self { limits: Limits::default(), metrics } + pub fn new(metrics: Metrics, client: impl Into) -> Self { + Self { limits: Limits::default(), metrics, invocation_timeout_ms: 15_000, client: client.into() } } } @@ -33,6 +42,7 @@ impl Config { /// on that port. pub struct Ports<'a> { pub state: &'a mut dyn StatePort, + pub ids: &'a mut dyn IdSource, } /// What the host tells core each frame. `viewport` is the one writer of size: logical px @@ -55,6 +65,10 @@ pub struct FrameOutput { /// When the host should call `frame` again with nothing else to say; `None` while nothing in /// core depends on time. pub next_wake: Option, + /// The invocations minted since the last frame, in order: core's only outbound write. + pub outbound: Vec, + /// What the host runs for the results taken this frame. + pub effects: Vec, } pub struct Core { @@ -65,6 +79,8 @@ pub struct Core { ledger: Ledger, scroll: ScrollOffsets, theme: Theme, + commands: Commands, + drafts: Drafts, /// The surface `show` named, and the one whose interest and trees are held. wanted: Option
, shown: Option
, @@ -82,6 +98,8 @@ impl Core { ledger: Ledger::new(), scroll: ScrollOffsets::default(), theme: Theme::std(), + commands: Commands::new(config.client, config.invocation_timeout_ms), + drafts: Drafts::new(), wanted: None, shown: None, last: None, @@ -95,7 +113,7 @@ impl Core { pub fn frame(&mut self, input: FrameInput, ports: Ports<'_>) -> FrameOutput { // Input routes only to owners that exist; none does yet, so events change nothing. - let FrameInput { now: _, viewport, scale, events: _ } = input; + let FrameInput { now, viewport, scale, events: _ } = input; let port = ports.state; let mut changes = Vec::new(); if self.wanted != self.shown { @@ -104,23 +122,94 @@ impl Core { changes.extend(port.drain()); let mut diagnostics = Vec::new(); + let mut effects = Vec::new(); + let mut rebound = false; for change in &changes { let intake = self.resolver.apply(change, port, &mut self.ledger); diagnostics.extend(intake.diagnostics); for (key, replaced) in intake.changed { if replaced { if let Some(tree) = self.resolver.tree(&key).cloned() { - diagnostics.extend(self.binder.bind(tree, port, &mut self.ledger).diagnostics); + let bound = self.binder.bind(tree, port, &mut self.ledger); + rebound |= !bound.dirty.is_empty(); + diagnostics.extend(bound.diagnostics); } } else { self.binder.forget(&key, port, &mut self.ledger); } } - diagnostics.extend(self.binder.apply(change, port, &mut self.ledger).diagnostics); + let applied = self.binder.apply(change, port, &mut self.ledger); + rebound |= !applied.dirty.is_empty(); + diagnostics.extend(applied.diagnostics); + let binder = &self.binder; + let answered = self.commands.apply(change, now, &|key| binder.tree(key), &mut self.drafts, port, &mut self.ledger); + diagnostics.extend(answered.diagnostics); + effects.extend(answered.effects); } + if rebound { + self.retain_drafts(); + } + diagnostics.extend(self.commands.tick(now, port, &mut self.ledger)); let commands = self.draw(viewport, scale, &mut diagnostics); - FrameOutput { commands, diagnostics, next_wake: None } + FrameOutput { + commands, + diagnostics, + next_wake: self.commands.next_deadline(), + outbound: self.commands.take_outbound(), + effects, + } + } + + /// The user acted on a node of the shown surface: the one primitive every input path ends in. A + /// host or a test calls it directly until the pointer and keyboard routes (which call it from + /// `frame`) land. The invocation it mints is in the next frame's `outbound`. + pub fn activate(&mut self, act: Activation, now: Timestamp, ports: Ports<'_>) -> Vec { + let Some(tree) = self.shown.as_ref().and_then(|shown| self.binder.tree(shown.key.as_str())) else { + return Vec::new(); + }; + self.commands.activate(act, tree, &mut self.drafts, now, ports.ids, ports.state, &mut self.ledger) + } + + /// Answer the command waiting on confirmation (`confirming`). Until the confirmation dialog + /// lands after keyboard input, a host calls this from its own test or debug path. + pub fn confirm(&mut self, accept: bool, now: Timestamp, ports: Ports<'_>) { + self.commands.confirm(accept, now, ports.ids, ports.state, &mut self.ledger); + } + + pub fn confirming(&self) -> Option<&Confirming> { + self.commands.confirming() + } + + /// Run the command an `OpenExternal` effect named, once the external step has returned. The + /// host holds the `Resume` across the navigation. + pub fn resume(&mut self, resume: &Resume, now: Timestamp, ports: Ports<'_>) -> Vec { + let Some(tree) = self.binder.tree(&resume.surface_key) else { + return Vec::new(); + }; + self.commands.resume(resume, tree, &self.drafts, now, ports.ids, ports.state, &mut self.ledger) + } + + /// The busy, pending and fault state of the shown surface's nodes, for render and accessibility. + pub fn node_states(&self) -> NodeStates { + self.shown.as_ref().map(|shown| self.commands.view(shown.key.as_str())).unwrap_or_default() + } + + /// The one table of uncommitted input values. The pointer and keyboard routes write it from + /// inside `frame`; until they land a host or a test writes here. + pub fn drafts_mut(&mut self) -> &mut Drafts { + &mut self.drafts + } + + /// Drop the drafts of nodes the shown surface no longer has. + fn retain_drafts(&mut self) { + let Some(shown) = &self.shown else { return }; + let key = shown.key.as_str(); + let live: HashSet<_> = match self.binder.tree(key) { + Some(tree) => tree.index().keys().map(|id| (*id).clone()).collect(), + None => HashSet::new(), + }; + self.drafts.retain(key, &live); } /// Leave the surface shown and take the one wanted: the interest is held before the one read, @@ -129,6 +218,7 @@ impl Core { if let Some(old) = self.shown.take() { self.resolver.forget(old.key.as_str(), port, &mut self.ledger); self.binder.forget(old.key.as_str(), port, &mut self.ledger); + self.commands.forget(old.key.as_str(), port, &mut self.ledger); self.ledger.release(port, &Interest::Record(old)); self.scroll = ScrollOffsets::default(); self.last = None; diff --git a/crates/thing-core/src/input/drafts.rs b/crates/thing-core/src/input/drafts.rs new file mode 100644 index 0000000..50f6c79 --- /dev/null +++ b/crates/thing-core/src/input/drafts.rs @@ -0,0 +1,47 @@ +//! Drafts: the one owner of every input node's uncommitted value, keyed (surface key, laid node id). +//! A value enters when the user changes an input and leaves when a result clears it or a republish +//! removes its node. Nothing else in core, and no host, keeps a second copy. + +use std::collections::{HashMap, HashSet}; + +use thing_contract::{InputValue, NodeId}; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Drafts { + values: HashMap<(String, NodeId), InputValue>, +} + +impl Drafts { + pub fn new() -> Self { + Self::default() + } + + pub fn set(&mut self, surface: &str, node: &NodeId, value: InputValue) { + self.values.insert((surface.to_string(), node.clone()), value); + } + + pub fn get(&self, surface: &str, node: &NodeId) -> Option<&InputValue> { + self.values.get(&(surface.to_string(), node.clone())) + } + + /// Drop the drafts of `nodes`; a node with no draft is untouched. + pub fn clear(&mut self, surface: &str, nodes: &[NodeId]) { + for node in nodes { + self.values.remove(&(surface.to_string(), node.clone())); + } + } + + /// Keep only the drafts of `surface` whose node is in `live` (the ids of the republished tree); + /// other surfaces' drafts stay. + pub fn retain(&mut self, surface: &str, live: &HashSet) { + self.values.retain(|(held, node), _| held != surface || live.contains(node)); + } + + pub fn len(&self) -> usize { + self.values.len() + } + + pub fn is_empty(&self) -> bool { + self.values.is_empty() + } +} diff --git a/crates/thing-core/src/input/mod.rs b/crates/thing-core/src/input/mod.rs index d4f4881..c363949 100644 --- a/crates/thing-core/src/input/mod.rs +++ b/crates/thing-core/src/input/mod.rs @@ -1,5 +1,8 @@ -//! What a host tells core about its user: the closed `InputEvent` vocabulary. +//! What a host tells core about its user: the closed `InputEvent` vocabulary, and the `Drafts` +//! table that owns what the user has typed or chosen and not yet sent. +pub mod drafts; pub mod event; +pub use drafts::Drafts; pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit}; diff --git a/crates/thing-core/src/lib.rs b/crates/thing-core/src/lib.rs index 08e7210..c6eaabc 100644 --- a/crates/thing-core/src/lib.rs +++ b/crates/thing-core/src/lib.rs @@ -2,6 +2,7 @@ //! through ports; it reads no clock, spawns nothing and awaits nothing. pub mod bind; +pub mod command; pub mod diagnostic; pub mod frame; pub mod input; diff --git a/crates/thing-core/src/port/mod.rs b/crates/thing-core/src/port/mod.rs index 6c9962c..5276d39 100644 --- a/crates/thing-core/src/port/mod.rs +++ b/crates/thing-core/src/port/mod.rs @@ -111,6 +111,12 @@ pub trait StatePort { fn drain(&mut self) -> Vec; } +/// Where core gets the 16 random bytes of an invocation id. Core sets the UUID version and +/// variant bits itself, so a source need only be unpredictable; a test source is a script or a counter. +pub trait IdSource { + fn fill(&mut self, bytes: &mut [u8; 16]); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/thing-core/src/render/mod.rs b/crates/thing-core/src/render/mod.rs index 847e57b..d9e411c 100644 --- a/crates/thing-core/src/render/mod.rs +++ b/crates/thing-core/src/render/mod.rs @@ -20,7 +20,6 @@ pub use scroll::{ScrollOffsets, clamp}; use crate::bind::{Bound, BoundTree, Field}; use crate::diagnostic::{Code, Diagnostic}; use crate::layout::{ControlForm, LaidControl, LaidNode, LaidTree, MAX_DEVICE, Measure, Metrics, Rect}; -use crate::resolve::grow; use crate::theme::{Theme, fallback}; /// What a frame is drawn with. `viewport` is what layout was given (logical px or cells). @@ -52,8 +51,7 @@ pub struct Rendered { } pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut dyn Measure) -> Rendered { - let mut nodes = HashMap::new(); - index(tree, &tree.resolved().document().root, &mut nodes); + let nodes = tree.index(); let k = match input.metrics { Metrics::Pixels if input.scale.is_finite() && input.scale > 0.0 => input.scale, _ => 1.0, @@ -84,37 +82,6 @@ pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut painter.out } -/// Every node of the document by id, Repeat instances included (ids are unique after resolve). -fn index<'a>(tree: &'a BoundTree, node: &'a Node, out: &mut HashMap<&'a NodeId, &'a Node>) { - grow(|| { - let (id, children): (&NodeId, &[Node]) = match node { - Node::Box(n) => (&n.common.id, &n.children), - Node::Button(n) => (&n.common.id, &n.content), - Node::Overlay(n) => (&n.common.id, &n.children), - Node::Repeat(n) => { - for instance in tree.instances(&n.common.id) { - index(tree, &instance.root, out); - } - (&n.common.id, &[]) - } - Node::Text(n) => (&n.common.id, &[]), - Node::Image(n) => (&n.common.id, &[]), - Node::Toggle(n) => (&n.common.id, &[]), - Node::Slider(n) => (&n.common.id, &[]), - Node::TextInput(n) => (&n.common.id, &[]), - Node::Select(n) => (&n.common.id, &[]), - Node::Plot(n) => (&n.common.id, &[]), - Node::Embed(n) => (&n.common.id, &[]), - Node::Use(n) => (&n.common.id, &[]), - Node::Slot(_) => return, - }; - out.insert(id, node); - for child in children { - index(tree, child, out); - } - }) -} - struct Painter<'a> { tree: &'a BoundTree, laid: &'a LaidTree, diff --git a/crates/thing-core/src/resolve/mod.rs b/crates/thing-core/src/resolve/mod.rs index 4c0ac3d..5844f5f 100644 --- a/crates/thing-core/src/resolve/mod.rs +++ b/crates/thing-core/src/resolve/mod.rs @@ -93,7 +93,7 @@ pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits key(a).cmp(&key(b)) }); let tree = root.and_then(|root| { - diagnostics.extend(validate::check(&root, limits, &document.record_key())); + diagnostics.extend(validate::check(&root, &document.commands, limits, &document.record_key())); let refused = diagnostics.iter().any(|diagnostic| diagnostic.code.refuses_document()); // Field by field: `..document.clone()` would clone the whole input tree to discard it. (!refused).then(|| ResolvedTree { diff --git a/crates/thing-core/src/resolve/validate.rs b/crates/thing-core/src/resolve/validate.rs index 4244e42..0078b0a 100644 --- a/crates/thing-core/src/resolve/validate.rs +++ b/crates/thing-core/src/resolve/validate.rs @@ -4,7 +4,7 @@ use std::collections::HashSet; -use thing_contract::{Node, NodeId}; +use thing_contract::{CommandDecl, Node, NodeId}; use super::Limits; use crate::diagnostic::{Code, Diagnostic}; @@ -44,8 +44,8 @@ pub(super) fn size(node: &Node) -> usize { super::grow(|| 1 + children(node).iter().map(size).sum::()) } -/// Faults of the finished tree, in pre-order: duplicate ids, then depth. A tree deeper than the limit is not walked further. -pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec { +/// Faults of the finished tree, in pre-order: duplicate ids, then depth, then each command capture that is not an input node. A tree deeper than the limit is not walked further. +pub(super) fn check(root: &Node, commands: &[CommandDecl], limits: &Limits, surface: &str) -> Vec { let mut found = Vec::new(); let fault = |code, node: Option<&NodeId>, detail: String| Diagnostic { code, @@ -54,6 +54,7 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec = HashSet::new(); + let mut inputs: HashSet<&NodeId> = HashSet::new(); let mut too_deep = false; let mut stack = vec![(root, 1usize)]; while let Some((node, depth)) = stack.pop() { @@ -62,6 +63,9 @@ pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec Vec Timestamp { + Timestamp(self.0.saturating_add(i64::from(ms))) + } + + /// RFC 3339 in UTC to whole seconds (an instant inside a second is floored), as + /// `2026-01-01T00:00:00Z`. The civil date comes from days since 1970-01-01 by Hinnant's + /// `civil_from_days`, valid for every date this type holds in the proleptic Gregorian calendar. + pub fn rfc3339(self) -> String { + let seconds = self.0.div_euclid(1000); + let days = seconds.div_euclid(86_400); + let in_day = seconds.rem_euclid(86_400); + 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 / 1460 + 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 shifted_month = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * shifted_month + 2) / 5 + 1; + let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 }; + let year = year_of_era + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", + in_day / 3600, + in_day % 3600 / 60, + in_day % 60 + ) + } +} diff --git a/crates/thing-core/tests/command.rs b/crates/thing-core/tests/command.rs new file mode 100644 index 0000000..b1b4503 --- /dev/null +++ b/crates/thing-core/tests/command.rs @@ -0,0 +1,951 @@ +//! Commands: one activation mints one invocation, results are judged by core alone, and every +//! transition of the lifecycle is a row here. Time is a parameter and ordering is forced: a test +//! that depends on two results arriving in one drain queues both before the drain. + +use thing_contract::*; +use thing_core::bind::{Binder, Instance}; +use thing_core::command::{Activation, ActivationKind, Answered, Commands, HostEffect, Mark, Resume}; +use thing_core::diagnostic::{Code, Diagnostic}; +use thing_core::input::Drafts; +use thing_core::port::{Address, Change, Entry, IdSource, Interest, Ledger, Prefix, Record, Refusal, StatePort}; +use thing_core::resolve::{Limits, resolve}; +use thing_core::time::Timestamp; +use thing_core::{Config, Core, FrameInput, Ports}; +use thing_testkit::build::*; +use thing_testkit::fixture::Fixture; +use thing_testkit::ids::{ScriptedIds, SeqIds}; +use thing_testkit::measure::FixedMeasure; +use thing_testkit::mem_state::MemState; +use thing_testkit::state::{self, Item, Settings}; +use thing_testkit::store::{PINNED_CLOCK, PINNED_NOW}; + +const PROVIDER: &str = "provider.cmd"; +const FEED: &str = "provider.feed"; + +fn at(ms: i64) -> Timestamp { + Timestamp(PINNED_NOW.0 + ms) +} + +// ----- surfaces ----- + +fn decl(id: &str, captures: &[&str], confirm: Option<&str>) -> CommandDecl { + CommandDecl { + id: CommandId::new(id), + payload_schema: SchemaId::new(format!("gamecult.thing.test.{id}.v1")), + captures: captures.iter().map(|node| nid(node)).collect(), + confirm: confirm.map(Into::into), + } +} + +fn button(id: &str, cmd: &str) -> Node { + Node::Button(ButtonNode { common: common(id), content: vec![], on_activate: command(cmd), enabled: lit_bool(true) }) +} + +fn toggle(id: &str, cmd: &str, checked: BoolSource) -> Node { + Node::Toggle(ToggleNode { common: common(id), checked, on_change: command(cmd) }) +} + +fn input(id: &str, kind: InputKind, initial: &str, cmd: &str) -> Node { + Node::TextInput(TextInputNode { + common: common(id), + multiline: false, + input_kind: kind, + placeholder: lit_text(""), + initial: lit_text(initial), + submit: command(cmd), + }) +} + +fn surface(provider: &str, root: Node, commands: Vec) -> SurfaceDocument { + SurfaceDocument { provider_id: ProviderId::new(provider), label: seg("main"), version: ver(1), title: "t".into(), root, commands } +} + +fn go_surface() -> SurfaceDocument { + surface( + PROVIDER, + boxed("root", vec![input("name", InputKind::Text, "", "go"), button("go", "go"), button("other", "go"), button("after", "after")]), + vec![decl("go", &["name"], None), decl("after", &[], None)], + ) +} + +/// A Repeat of the feed's items; each row has a note and a button whose command captures the row's +/// note and the one global toggle outside the Repeat. +fn rows_surface() -> SurfaceDocument { + let row = Node::Box(BoxNode { + common: common("row"), + style: style(), + paint: plain_paint(), + role: Role::ListItem, + children: vec![input("note", InputKind::Text, "n", "save-row"), button("save", "save-row")], + }); + let rows = Node::Repeat(RepeatNode { + common: common("rows"), + collection: CollectionSource::Records(RecordsSource { + provider: Some(ProviderId::new(FEED)), + schema: SchemaId::new("gamecult.thing.test.item.v1"), + key_prefix: "item-".into(), + }), + key_member: path(&["Id"]), + template: std::boxed::Box::new(row), + }); + surface( + PROVIDER, + boxed("root", vec![toggle("global", "save-row", lit_bool(true)), rows]), + vec![decl("save-row", &["note", "global"], None), decl("after", &["note"], None)], + ) +} + +fn rows_state() -> MemState { + let mut state = MemState::new(); + for n in 1..=3 { + let id = format!("item-{n:04}"); + state.put_state(&ProviderId::new(FEED), &id, &Item { id: id.clone(), title: id.clone() }); + } + state +} + +fn row(item: &str, node: &str) -> NodeId { + NodeId::new(format!("{}{node}", Instance::scope_prefix("rows", item, false))) +} + +// ----- the rig: the stages composed by hand, as Core::frame composes them ----- + +struct Rig { + state: MemState, + ledger: Ledger, + binder: Binder, + commands: Commands, + drafts: Drafts, + ids: SeqIds, + surface: String, + provider: ProviderId, +} + +impl Rig { + fn new(mut state: MemState, document: &SurfaceDocument) -> Self { + state.put(&document.provider_id, document); + let tree = resolve(document, &state, &Limits::default()).tree.expect("resolves"); + let mut ledger = Ledger::new(); + let mut binder = Binder::new(Limits::default()); + binder.bind(tree, &mut state, &mut ledger); + Self { + state, + ledger, + binder, + commands: Commands::new("renderer.web", 15_000), + drafts: Drafts::new(), + ids: SeqIds::new(), + surface: document.record_key(), + provider: document.provider_id.clone(), + } + } + + fn act(&mut self, node: &NodeId, kind: ActivationKind, now: Timestamp, ids: &mut dyn IdSource) -> Vec { + let tree = self.binder.tree(&self.surface).expect("bound"); + let act = Activation { node: node.clone(), kind }; + self.commands.activate(act, tree, &mut self.drafts, now, ids, &mut self.state, &mut self.ledger) + } + + fn press(&mut self, node: &str, now: Timestamp, ids: &mut dyn IdSource) -> Vec { + self.act(&nid(node), ActivationKind::Press, now, ids) + } + + fn mint(&mut self, node: &str, now: Timestamp) -> CommandInvocation { + let mut ids = std::mem::take(&mut self.ids); + self.press(node, now, &mut ids); + self.ids = ids; + self.commands.take_outbound().pop().expect("minted") + } + + fn set_draft(&mut self, node: &NodeId, value: InputValue) { + self.drafts.set(&self.surface, node, value); + } + + fn draft(&self, node: &NodeId) -> Option { + self.drafts.get(&self.surface, node).cloned() + } + + /// Put the result in the port and drain it: it arrives only if core holds the interest. + fn feed(&mut self, result: &CommandResult, now: Timestamp) -> Answered { + self.state.put(&self.provider, result); + self.drain(now) + } + + fn drain(&mut self, now: Timestamp) -> Answered { + let mut answered = Answered::default(); + for change in self.state.drain() { + let one = self.apply(&change, now); + answered.effects.extend(one.effects); + answered.diagnostics.extend(one.diagnostics); + } + answered + } + + fn apply(&mut self, change: &Change, now: Timestamp) -> Answered { + let binder = &self.binder; + self.commands.apply(change, now, &|key| binder.tree(key), &mut self.drafts, &mut self.state, &mut self.ledger) + } + + fn feed_direct(&mut self, result: &CommandResult, now: Timestamp) -> Answered { + let address = self.result_address(&result.record_key()); + let change = Change::Upsert(Entry { address, record: Record::Result(result.clone()) }); + self.apply(&change, now) + } + + fn result_address(&self, key: &str) -> Address { + Address { provider: self.provider.clone(), schema: SchemaId::new(CommandResult::SCHEMA_NAME), key: RecordKey::new(key) } + } + + fn tick(&mut self, now: Timestamp) -> Vec { + self.commands.tick(now, &mut self.state, &mut self.ledger) + } + + fn readers(&self, invocation: &CommandInvocation) -> usize { + let prefix = CommandResult::pending(invocation, seq(1), "").record_key(); + let prefix = prefix[..prefix.len() - 1].to_string(); + let interest = Interest::Prefix(Prefix { + provider: self.provider.clone(), + schema: SchemaId::new(CommandResult::SCHEMA_NAME), + key_prefix: prefix, + }); + self.ledger.readers(&interest) + } + + fn state_of(&self, node: &str) -> thing_core::command::NodeState { + self.commands.view(&self.surface).get(&nid(node)) + } +} + +fn codes(diagnostics: &[Diagnostic]) -> Vec { + diagnostics.iter().map(|diagnostic| diagnostic.code).collect() +} + +fn text_value(value: &str) -> InputValue { + InputValue::Text(TextValue { value: value.into() }) +} + +fn completed(invocation: &CommandInvocation, n: i32, clear: bool, effect: Option) -> CommandResult { + CommandResult::completed(invocation, seq(n), None, clear, effect) +} + +/// A source of one fixed run of bytes. +struct Bytes([u8; 16]); + +impl IdSource for Bytes { + fn fill(&mut self, bytes: &mut [u8; 16]) { + *bytes = self.0; + } +} + +// ----- ids and time ----- + +#[test] +fn a_minted_id_is_v4_shaped_for_any_bytes() { + for bytes in [[0u8; 16], [0xff; 16], std::array::from_fn(|i| i as u8), std::array::from_fn(|i| (i * 37 + 11) as u8)] { + let mut rig = Rig::new(MemState::new(), &go_surface()); + rig.press("go", PINNED_NOW, &mut Bytes(bytes)); + let id = rig.commands.take_outbound().pop().unwrap().invocation_id; + let chars: Vec = id.chars().collect(); + assert_eq!(chars.len(), 36, "{id}"); + for dash in [8, 13, 18, 23] { + assert_eq!(chars[dash], '-', "{id}"); + } + assert_eq!(chars[14], '4', "{id}"); + assert!(matches!(chars[19], '8' | '9' | 'a' | 'b'), "{id}"); + assert!(chars.iter().enumerate().all(|(i, c)| [8, 13, 18, 23].contains(&i) || (c.is_ascii_hexdigit() && !c.is_ascii_uppercase())), "{id}"); + assert!(!id.contains('.')); + } +} + +#[test] +fn rfc3339_formats_whole_seconds_in_utc() { + assert_eq!(PINNED_NOW.rfc3339(), PINNED_CLOCK); + assert_eq!(Timestamp(0).rfc3339(), "1970-01-01T00:00:00Z"); + // A leap day, a century that is not a leap year, a leap century. + assert_eq!(Timestamp(1_709_210_096_000).rfc3339(), "2024-02-29T12:34:56Z"); + assert_eq!(Timestamp(951_782_400_000).rfc3339(), "2000-02-29T00:00:00Z"); + assert_eq!(Timestamp(4_107_542_400_000).rfc3339(), "2100-03-01T00:00:00Z"); + // Before 1970 the second is floored, never rounded toward zero. + assert_eq!(Timestamp(-1000).rfc3339(), "1969-12-31T23:59:59Z"); + assert_eq!(Timestamp(-1).rfc3339(), "1969-12-31T23:59:59Z"); + assert_eq!(Timestamp(999).rfc3339(), "1970-01-01T00:00:00Z"); + assert_eq!(Timestamp(-62_135_596_800_000).rfc3339(), "0001-01-01T00:00:00Z"); +} + +// ----- drafts ----- + +#[test] +fn drafts_are_per_surface_and_clear_or_retain_exactly_what_is_named() { + let mut drafts = Drafts::new(); + for node in ["a", "b", "c"] { + drafts.set("s1", &nid(node), text_value(node)); + } + drafts.set("s2", &nid("a"), text_value("other")); + drafts.clear("s1", &[nid("a"), nid("missing")]); + assert_eq!(drafts.get("s1", &nid("a")), None); + assert_eq!(drafts.get("s1", &nid("b")), Some(&text_value("b"))); + assert_eq!(drafts.get("s2", &nid("a")), Some(&text_value("other"))); + drafts.retain("s1", &[nid("c")].into_iter().collect()); + assert_eq!(drafts.get("s1", &nid("b")), None); + assert_eq!(drafts.get("s1", &nid("c")), Some(&text_value("c"))); + assert_eq!(drafts.get("s2", &nid("a")), Some(&text_value("other"))); + assert_eq!(drafts.len(), 2); +} + +// ----- smokes: the fixtures' invocations are the expected output ----- + +#[test] +fn f02_login_mints_the_fixture_invocation_and_runs_its_effect() { + let set = Fixture::F02LoginEffect.load(); + let login = set.surfaces[0].clone(); + let expected = set.invocations[0].clone(); + let mut rig = Rig::new(MemState::from_fixture(Fixture::F02LoginEffect), &login); + rig.set_draft(&nid("username"), text_value("ada")); + let mut ids = ScriptedIds::new([expected.invocation_id.as_str()]); + + assert!(rig.press("sign-in-button", PINNED_NOW, &mut ids).is_empty()); + let minted = rig.commands.take_outbound(); + assert_eq!(minted, vec![expected.clone()]); + assert_eq!(minted[0].payload.bytes, vec![0x90]); + assert_eq!(rig.readers(&expected), 1); + assert!(rig.state_of("sign-in-button").busy); + + // A second press while the first is waiting mints nothing and draws no id. + let mut spare = ScriptedIds::new(["00000000-0000-4000-8000-000000000000"]); + rig.press("sign-in-button", at(1), &mut spare); + assert!(rig.commands.take_outbound().is_empty()); + assert_eq!(spare.remaining(), 1); + + let answered = rig.feed(&set.results[0], at(10_000)); + assert!(answered.diagnostics.is_empty() && answered.effects.is_empty()); + let state = rig.state_of("sign-in-button"); + assert!(state.busy); + assert_eq!(state.pending.as_deref(), Some("waiting for the identity provider")); + // The heartbeat renewed the deadline from the time of the Pending, not of the mint. + assert_eq!(rig.commands.next_deadline(), Some(at(25_000))); + + let answered = rig.feed(&set.results[1], at(11_000)); + assert!(answered.diagnostics.is_empty()); + assert_eq!( + answered.effects, + vec![HostEffect::OpenExternal { + url: "https://login.example.test/authorize".into(), + resume: Resume { + surface_key: login.record_key(), + command: CommandId::new("login-resume"), + source: nid("sign-in-button"), + items: vec![], + }, + }] + ); + assert_eq!(rig.readers(&expected), 0); + assert!(!rig.state_of("sign-in-button").busy); + assert_eq!(rig.commands.next_deadline(), None); +} + +fn settings_state(enabled: bool) -> MemState { + let mut state = MemState::new(); + state.put_state(&ProviderId::new("provider.settings"), "current", &Settings { enabled, volume: 0.75, theme: "dark".into() }); + state +} + +#[test] +fn f04_form_captures_in_declared_order_and_clears_exactly_those_drafts() { + let set = Fixture::F04Form.load(); + let form = set.surfaces[0].clone(); + let expected = set.invocations[0].clone(); + let mut rig = Rig::new(settings_state(false), &form); + let mut ids = ScriptedIds::new([expected.invocation_id.as_str()]); + + rig.act(&nid("enabled"), ActivationKind::Change(InputValue::Bool(BoolValue { value: true })), PINNED_NOW, &mut ids); + assert_eq!(rig.commands.take_outbound(), vec![expected.clone()]); + // The change was written to Drafts before the command fired. + assert_eq!(rig.draft(&nid("enabled")), Some(InputValue::Bool(BoolValue { value: true }))); + for (node, value) in [ + ("volume", InputValue::Number(NumberValue { value: 0.75 })), + ("theme", InputValue::Choice(ChoiceValue { value: "dark".into() })), + ("port", text_value("8080")), + ] { + rig.set_draft(&nid(node), value); + } + rig.set_draft(&nid("root"), text_value("not captured")); + + rig.feed(&set.results[0], at(1)); + for node in ["enabled", "volume", "theme", "port"] { + assert_eq!(rig.draft(&nid(node)), None, "{node}"); + } + assert_eq!(rig.draft(&nid("root")), Some(text_value("not captured"))); +} + +#[test] +fn clear_drafts_false_clears_none() { + let set = Fixture::F04Form.load(); + let mut rig = Rig::new(settings_state(false), &set.surfaces[0]); + let invocation = rig.mint_change_enabled(); + rig.set_draft(&nid("volume"), InputValue::Number(NumberValue { value: 0.5 })); + rig.feed(&completed(&invocation, 1, false, None), at(1)); + assert!(rig.draft(&nid("enabled")).is_some() && rig.draft(&nid("volume")).is_some()); +} + +impl Rig { + fn mint_change_enabled(&mut self) -> CommandInvocation { + self.act(&nid("enabled"), ActivationKind::Change(InputValue::Bool(BoolValue { value: true })), PINNED_NOW, &mut SeqIds::new()); + self.commands.take_outbound().pop().expect("minted") + } +} + +// ----- gates ----- + +#[test] +fn nothing_mints_for_a_mismatch_a_disabled_button_or_a_double_press() { + let mut disabled = go_surface(); + let Node::Box(root) = &mut disabled.root else { unreachable!() }; + root.children.push(Node::Button(ButtonNode { common: common("off"), content: vec![], on_activate: command("go"), enabled: lit_bool(false) })); + root.children.push(toggle("flag", "go", lit_bool(false))); + let mut rig = Rig::new(MemState::new(), &disabled); + let mut ids = SeqIds::new(); + + rig.press("off", PINNED_NOW, &mut ids); + // A kind the node does not take, a value of the wrong kind, an unknown node: caller bugs that mint + // nothing and write no draft. + rig.act(&nid("go"), ActivationKind::Submit, PINNED_NOW, &mut ids); + rig.act(&nid("flag"), ActivationKind::Press, PINNED_NOW, &mut ids); + rig.act(&nid("flag"), ActivationKind::Change(text_value("x")), PINNED_NOW, &mut ids); + rig.press("no-such-node", PINNED_NOW, &mut ids); + assert!(rig.commands.take_outbound().is_empty()); + assert_eq!(rig.draft(&nid("flag")), None); + + // One press mints; the same button is busy; a different button of the same command is not. + rig.press("go", PINNED_NOW, &mut ids); + rig.press("go", at(5), &mut ids); + assert_eq!(rig.commands.take_outbound().len(), 1); + rig.press("other", at(6), &mut ids); + assert_eq!(rig.commands.take_outbound().len(), 1); +} + +#[test] +fn a_button_is_free_again_once_its_invocation_is_terminal() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let first = rig.mint("go", PINNED_NOW); + assert!(rig.state_of("go").busy); + rig.feed(&CommandResult::failed(&first, seq(1), "no"), at(1)); + assert!(!rig.state_of("go").busy); + assert_eq!(rig.state_of("go").mark, Some(Mark::Failed { reason: "no".into() })); + // Minting again clears the mark. + let mut ids = ScriptedIds::new(["11111111-1111-4111-8111-111111111111"]); + rig.press("go", at(2), &mut ids); + assert_eq!(rig.commands.take_outbound().len(), 1); + assert_eq!(rig.state_of("go").mark, None); +} + +// ----- confirm ----- + +#[test] +fn confirm_holds_the_activation_time_captures_and_a_reject_draws_no_id() { + let mut document = go_surface(); + document.commands[0] = decl("go", &["name"], Some("Send it?")); + let mut rig = Rig::new(MemState::new(), &document); + let mut ids = ScriptedIds::new(["22222222-2222-4222-8222-222222222222"]); + rig.set_draft(&nid("name"), text_value("first")); + + rig.press("go", PINNED_NOW, &mut ids); + assert!(rig.commands.take_outbound().is_empty()); + let confirming = rig.commands.confirming().expect("waiting").clone(); + assert_eq!(confirming.text, "Send it?"); + assert_eq!(confirming.node, nid("go")); + assert_eq!(confirming.captured()[0].value, text_value("first")); + + // The draft moves on and a second activation arrives: neither changes what is confirmed or mints. + rig.set_draft(&nid("name"), text_value("second")); + rig.press("other", at(1), &mut ids); + assert_eq!(rig.commands.confirming(), Some(&confirming)); + + rig.commands.confirm(false, at(2), &mut ids, &mut rig.state, &mut rig.ledger); + assert!(rig.commands.confirming().is_none() && rig.commands.take_outbound().is_empty()); + assert_eq!(ids.remaining(), 1); + + rig.press("go", at(3), &mut ids); + rig.set_draft(&nid("name"), text_value("third")); + rig.commands.confirm(true, at(4), &mut ids, &mut rig.state, &mut rig.ledger); + let minted = rig.commands.take_outbound(); + assert_eq!(minted.len(), 1); + assert_eq!(minted[0].captured[0].value, text_value("second")); + assert_eq!(minted[0].issued_at, at(4).rfc3339()); + assert_eq!(ids.remaining(), 0); + // With nothing waiting, confirming again does nothing. + rig.commands.confirm(true, at(5), &mut ids, &mut rig.state, &mut rig.ledger); + assert!(rig.commands.take_outbound().is_empty()); +} + +#[test] +fn f01_restart_waits_for_confirmation() { + let set = Fixture::F01SwarmDashboard.load(); + let mut state = MemState::from_fixture(Fixture::F01SwarmDashboard); + state::script(Fixture::F01SwarmDashboard, &mut state); + let mut rig = Rig::new(state, &set.surfaces[0]); + rig.press("restart", PINNED_NOW, &mut SeqIds::new()); + assert!(rig.commands.take_outbound().is_empty()); + assert_eq!(rig.commands.confirming().unwrap().text, "Restart the swarm?"); +} + +// ----- the lifecycle table ----- + +#[test] +fn a_result_after_terminal_is_a_diagnostic_and_changes_nothing() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + // Both results are queued before either is delivered: the second arrives after the first was + // terminal, whatever order the host's frames fall in. + rig.state.put(&rig.provider.clone(), &completed(&invocation, 1, false, None)); + rig.state.put(&rig.provider.clone(), &CommandResult::pending(&invocation, seq(2), "late")); + let answered = rig.drain(at(1)); + assert_eq!(codes(&answered.diagnostics), vec![Code::ResultAfterTerminal]); + assert!(!rig.state_of("go").busy); + assert_eq!(rig.state_of("go").pending, None); + assert_eq!(rig.readers(&invocation), 0); + + // Failed then Completed likewise. + let second = rig.mint("other", at(2)); + rig.state.put(&rig.provider.clone(), &CommandResult::failed(&second, seq(1), "x")); + rig.state.put(&rig.provider.clone(), &completed(&second, 2, true, None)); + assert_eq!(codes(&rig.drain(at(3)).diagnostics), vec![Code::ResultAfterTerminal]); + assert_eq!(rig.state_of("other").mark, Some(Mark::Failed { reason: "x".into() })); +} + +#[test] +fn a_regressed_seq_is_ignored_silently() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + rig.feed(&CommandResult::pending(&invocation, seq(2), "newer"), at(1)); + let answered = rig.feed(&CommandResult::pending(&invocation, seq(1), "older"), at(5_000)); + assert_eq!(answered, Answered::default()); + assert_eq!(rig.state_of("go").pending.as_deref(), Some("newer")); + // Not renewed by the stale one. + assert_eq!(rig.commands.next_deadline(), Some(at(15_001))); + // The same seq again is a re-delivery. + assert_eq!(rig.feed_direct(&CommandResult::pending(&invocation, seq(2), "newer"), at(6_000)), Answered::default()); +} + +#[test] +fn a_result_that_is_not_what_its_key_says_is_malformed() { + let cases: Vec<(&str, Box Change>)> = vec![ + // A body naming another invocation at this invocation's key. + ("another invocation's body", Box::new(|rig, mine| { + let theirs = CommandResult::pending(&stranger(), seq(1), "x"); + Change::Upsert(Entry { address: rig.result_address(&CommandResult::pending(mine, seq(1), "").record_key()), record: Record::Result(theirs) }) + })), + // A seq that is not the key's. + ("another seq", Box::new(|rig, mine| { + let body = CommandResult::pending(mine, seq(1), "x"); + Change::Upsert(Entry { address: rig.result_address(&CommandResult::pending(mine, seq(2), "").record_key()), record: Record::Result(body) }) + })), + ("a record that is not a result", Box::new(|rig, mine| { + let address = rig.result_address(&CommandResult::pending(mine, seq(1), "").record_key()); + Change::Upsert(Entry { address, record: Record::Surface(go_surface()) }) + })), + ("refused at decode", Box::new(|rig, mine| { + let address = rig.result_address(&CommandResult::pending(mine, seq(1), "").record_key()); + Change::Refused(Refusal { kind: SchemaId::new(CommandResult::SCHEMA_NAME), address, detail: "extra field".into() }) + })), + ]; + for (name, make) in cases { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + let change = make(&mut rig, &invocation); + let answered = rig.apply(&change, at(1)); + assert_eq!(codes(&answered.diagnostics), vec![Code::MalformedResult], "{name}"); + assert_eq!(answered.effects, vec![], "{name}"); + assert_eq!(rig.state_of("go").mark, Some(Mark::Malformed), "{name}"); + assert!(!rig.state_of("go").busy, "{name}"); + assert_eq!(rig.readers(&invocation), 0, "{name}"); + // Malformed is final. + let late = rig.feed_direct(&completed(&invocation, 3, false, None), at(2)); + assert_eq!(codes(&late.diagnostics), vec![Code::ResultAfterTerminal], "{name}"); + } +} + +#[test] +fn a_delete_is_ignored_and_an_unknown_invocation_is_logged() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + let address = rig.result_address(&CommandResult::pending(&invocation, seq(1), "").record_key()); + assert_eq!(rig.apply(&Change::Delete(address), at(1)), Answered::default()); + assert!(rig.state_of("go").busy); + + let mut stranger = invocation.clone(); + stranger.invocation_id = "44444444-4444-4444-8444-444444444444".into(); + let answered = rig.feed_direct(&CommandResult::pending(&stranger, seq(1), "x"), at(2)); + assert_eq!(codes(&answered.diagnostics), vec![Code::UnknownInvocation]); + assert!(rig.state_of("go").busy); + // An address that is not a command result is not this module's. + let elsewhere = Address { provider: rig.provider.clone(), schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), key: RecordKey::new("x") }; + assert_eq!(rig.apply(&Change::Delete(elsewhere), at(3)), Answered::default()); +} + +// ----- timeouts ----- + +#[test] +fn an_invocation_times_out_at_exactly_issued_plus_the_timeout() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let invocation = rig.mint("go", PINNED_NOW); + assert_eq!(rig.commands.next_deadline(), Some(at(15_000))); + assert!(rig.tick(at(14_999)).is_empty()); + assert!(rig.state_of("go").busy); + let fired = rig.tick(at(15_000)); + assert_eq!(codes(&fired), vec![Code::InvocationTimedOut]); + assert_eq!(fired[0].node, Some(nid("go"))); + assert_eq!(rig.state_of("go").mark, Some(Mark::TimedOut)); + assert!(!rig.state_of("go").busy); + assert_eq!(rig.readers(&invocation), 0); + assert_eq!(rig.commands.next_deadline(), None); + assert!(rig.tick(at(99_000)).is_empty()); + // A result after the timeout is judged, not taken. + let late = rig.feed_direct(&completed(&invocation, 1, false, None), at(16_000)); + assert_eq!(codes(&late.diagnostics), vec![Code::ResultAfterTerminal]); + assert_eq!(rig.state_of("go").mark, Some(Mark::TimedOut)); +} + +#[test] +fn a_pending_result_renews_the_deadline_and_the_earliest_deadline_wins() { + let mut rig = Rig::new(MemState::new(), &go_surface()); + let first = rig.mint("go", PINNED_NOW); + let _second = rig.mint("other", at(5_000)); + assert_eq!(rig.commands.next_deadline(), Some(at(15_000))); + rig.feed(&CommandResult::pending(&first, seq(1), "working"), at(10_000)); + // The first moved to +25 000; the second, at +20 000, is now the earliest. + assert_eq!(rig.commands.next_deadline(), Some(at(20_000))); + assert!(rig.tick(at(19_999)).is_empty()); + let fired = rig.tick(at(20_000)); + assert_eq!(fired.len(), 1); + assert_eq!(fired[0].node, Some(nid("other"))); + assert!(rig.state_of("go").busy); + assert_eq!(rig.commands.next_deadline(), Some(at(25_000))); + // A clock that went backward fires nothing early. + assert!(rig.tick(at(1)).is_empty()); +} + +// ----- effects ----- + +fn effect_outcome(effect: Effect) -> (Rig, CommandInvocation, Answered) { + let mut rig = Rig::new(MemState::new(), &go_surface()); + rig.set_draft(&nid("name"), text_value("keep me")); + let invocation = rig.mint("go", PINNED_NOW); + let answered = rig.feed(&completed(&invocation, 1, true, Some(effect)), at(1)); + (rig, invocation, answered) +} + +fn open_external(url: &str, resume: CommandRef) -> Effect { + Effect::OpenExternal(OpenExternalEffect { url: url.into(), resume }) +} + +#[test] +fn an_effect_core_will_not_run_makes_the_result_malformed_and_clears_nothing() { + let refused = [ + open_external("javascript:alert(1)", command("after")), + open_external("data:text/html,x", command("after")), + open_external("/relative/path", command("after")), + open_external("file:///etc/passwd", command("after")), + open_external("https://", command("after")), + open_external("https://ok.test/\nx", command("after")), + open_external("https://ok.test/", CommandRef::Param(param("p"))), + open_external("https://ok.test/", command("undeclared")), + Effect::OpenSurface(OpenSurfaceEffect { key: "thing:asset_catalog:x.y".into() }), + Effect::OpenSurface(OpenSurfaceEffect { key: "javascript:1".into() }), + ]; + for effect in refused { + let (rig, invocation, answered) = effect_outcome(effect.clone()); + assert_eq!(codes(&answered.diagnostics), vec![Code::MalformedResult], "{effect:?}"); + assert_eq!(answered.effects, vec![], "{effect:?}"); + assert_eq!(rig.draft(&nid("name")), Some(text_value("keep me")), "{effect:?}"); + assert_eq!(rig.state_of("go").mark, Some(Mark::Malformed), "{effect:?}"); + assert_eq!(rig.readers(&invocation), 0); + } +} + +#[test] +fn a_valid_effect_is_emitted_once_with_the_invocations_source_and_items() { + let (rig, _, answered) = effect_outcome(open_external("HTTPS://Example.test/a?b=c", command("after"))); + assert!(answered.diagnostics.is_empty()); + assert_eq!(answered.effects.len(), 1); + let HostEffect::OpenExternal { url, resume } = &answered.effects[0] else { panic!("{:?}", answered.effects) }; + assert_eq!(url, "HTTPS://Example.test/a?b=c"); + assert_eq!((resume.command.as_str(), resume.source.as_str(), resume.items.len()), ("after", "go", 0)); + // clear_drafts cleared the captured draft. + assert_eq!(rig.draft(&nid("name")), None); + + let (_, _, answered) = effect_outcome(Effect::OpenSurface(OpenSurfaceEffect { key: "thing:surface:provider.x.main".into() })); + assert_eq!(answered.effects, vec![HostEffect::OpenSurface { key: "thing:surface:provider.x.main".into() }]); +} + +#[test] +fn a_resume_mints_the_declared_command_for_the_same_row_and_only_when_declared() { + let mut rig = Rig::new(rows_state(), &rows_surface()); + rig.set_draft(&row("item-0002", "note"), text_value("two")); + rig.set_draft(&row("item-0001", "note"), text_value("one")); + let mut ids = SeqIds::new(); + let resume = Resume { + surface_key: rig.surface.clone(), + command: CommandId::new("after"), + source: nid("save"), + items: vec!["item-0002".into()], + }; + let tree = rig.binder.tree(&rig.surface.clone()).unwrap(); + let diagnostics = rig.commands.resume(&resume, tree, &rig.drafts, PINNED_NOW, &mut ids, &mut rig.state, &mut rig.ledger); + assert!(diagnostics.is_empty()); + let minted = rig.commands.take_outbound(); + assert_eq!(minted.len(), 1); + assert_eq!((minted[0].source.as_str(), minted[0].items.clone()), ("save", vec!["item-0002".to_string()])); + assert_eq!(minted[0].captured[0].value, text_value("two")); + // No issuing node, so nothing is busy. + assert!(!rig.state_of(row("item-0002", "save").as_str()).busy); + + let undeclared = Resume { command: CommandId::new("gone"), ..resume.clone() }; + let tree = rig.binder.tree(&rig.surface.clone()).unwrap(); + let diagnostics = rig.commands.resume(&undeclared, tree, &rig.drafts, PINNED_NOW, &mut ids, &mut rig.state, &mut rig.ledger); + assert_eq!(codes(&diagnostics), vec![Code::UndeclaredCommand]); + assert!(rig.commands.take_outbound().is_empty()); +} + +// ----- captures ----- + +#[test] +fn a_button_in_a_row_captures_its_own_rows_input_and_names_its_row() { + let mut rig = Rig::new(rows_state(), &rows_surface()); + rig.set_draft(&row("item-0001", "note"), text_value("one")); + rig.set_draft(&row("item-0002", "note"), text_value("two")); + rig.set_draft(&nid("global"), InputValue::Bool(BoolValue { value: false })); + let mut ids = SeqIds::new(); + rig.act(&row("item-0002", "save"), ActivationKind::Press, PINNED_NOW, &mut ids); + let minted = rig.commands.take_outbound().pop().unwrap(); + // The declared ids, the row's value for the row's input, the top-level one for the id outside any row. + assert_eq!( + minted.captured, + vec![ + CapturedInput { node: nid("note"), value: text_value("two") }, + CapturedInput { node: nid("global"), value: InputValue::Bool(BoolValue { value: false }) }, + ] + ); + assert_eq!((minted.source.clone(), minted.items.clone()), (nid("save"), vec!["item-0002".to_string()])); + // A row with no draft sends what its input is bound to. + rig.act(&row("item-0003", "save"), ActivationKind::Press, PINNED_NOW, &mut ids); + let third = rig.commands.take_outbound().pop().unwrap(); + assert_eq!(third.captured[0].value, text_value("n")); + assert_eq!(third.items, vec!["item-0003".to_string()]); + assert_eq!(third.captured[1].value, InputValue::Bool(BoolValue { value: false })); + // Completed clears the row's draft and no other row's. + let answered = rig.feed(&completed(&minted, 1, true, None), at(1)); + assert!(answered.diagnostics.is_empty()); + assert_eq!(rig.draft(&row("item-0002", "note")), None); + assert_eq!(rig.draft(&row("item-0001", "note")), Some(text_value("one"))); +} + +#[test] +fn a_capture_with_nothing_to_send_mints_nothing() { + let settings_ref = |member: &str| Bind { + source: StateSource::Record(StateRef { + provider: Some(ProviderId::new("provider.settings")), + schema: SchemaId::new("gamecult.thing.test.settings.v1"), + key: RecordKey::new("current"), + }), + member: path(&[member]), + format: None, + }; + let broken: [(&str, Node); 4] = [ + ("a bound error", toggle("c", "go", BoolSource::Bound(settings_ref("Nope")))), + ("an absent record", toggle("c", "go", BoolSource::Bound(record_bind(path(&["Enabled"]), None)))), + ("an unparseable number", input("c", InputKind::Number, "abc", "go")), + ("a number that is not finite", input("c", InputKind::Number, "NaN", "go")), + ]; + for (name, node) in broken { + let document = surface(PROVIDER, boxed("root", vec![node, button("go", "go")]), vec![decl("go", &["c"], None)]); + let mut rig = Rig::new(settings_state(true), &document); + let diagnostics = rig.press("go", PINNED_NOW, &mut SeqIds::new()); + assert_eq!(codes(&diagnostics), vec![Code::CaptureUnavailable], "{name}"); + assert_eq!(diagnostics[0].node, Some(nid("c")), "{name}"); + assert!(rig.commands.take_outbound().is_empty(), "{name}"); + assert!(!rig.state_of("go").busy, "{name}"); + } + // A Number input reads its Text draft; one that does not parse is the same fault. + let document = surface(PROVIDER, boxed("root", vec![input("n", InputKind::Number, "1", "go"), button("go", "go")]), vec![decl("go", &["n"], None)]); + let mut rig = Rig::new(MemState::new(), &document); + rig.set_draft(&nid("n"), text_value("12x")); + assert_eq!(codes(&rig.press("go", PINNED_NOW, &mut SeqIds::new())), vec![Code::CaptureUnavailable]); + rig.set_draft(&nid("n"), text_value(" 12.5 ")); + rig.press("go", PINNED_NOW, &mut SeqIds::new()); + assert_eq!(rig.commands.take_outbound()[0].captured[0].value, InputValue::Number(NumberValue { value: 12.5 })); +} + +#[test] +fn a_capture_naming_no_input_refuses_the_document() { + for (name, commands) in [ + ("a missing id", vec![decl("go", &["nowhere"], None)]), + ("a node that holds no input", vec![decl("go", &["label"], None)]), + ] { + let document = surface(PROVIDER, boxed("root", vec![text("label", "hi"), button("go", "go")]), commands); + let resolution = resolve(&document, &MemState::new(), &Limits::default()); + assert!(resolution.tree.is_none(), "{name}"); + let faults: Vec<_> = resolution.diagnostics.iter().filter(|d| d.code == Code::CaptureUndeclared).collect(); + assert_eq!(faults.len(), 1, "{name}"); + assert!(Code::CaptureUndeclared.refuses_document()); + } + // A template's ids count, so the rows surface resolves. + assert!(resolve(&rows_surface(), &rows_state(), &Limits::default()).tree.is_some()); +} + +// ----- denied ----- + +fn denied_surface() -> SurfaceDocument { + surface( + PROVIDER, + boxed("root", vec![button("go", "go"), input("field", InputKind::Text, "", "go")]), + vec![decl("go", &[], None)], + ) +} + +#[test] +fn denied_marks_the_named_node_only_and_the_issuing_node_when_none_or_unknown() { + // Some(node): that node is marked, the issuing one is not. + let mut rig = Rig::new(MemState::new(), &denied_surface()); + let invocation = rig.mint("go", PINNED_NOW); + let answered = rig.feed(&CommandResult::denied(&invocation, seq(1), "no", Some(nid("field"))), at(1)); + assert!(answered.diagnostics.is_empty()); + assert_eq!(rig.state_of("field").mark, Some(Mark::Denied { reason: "no".into() })); + assert_eq!(rig.state_of("go").mark, None); + assert!(!rig.state_of("go").busy); + + // None: the issuing node. + let mut rig = Rig::new(MemState::new(), &denied_surface()); + let invocation = rig.mint("go", PINNED_NOW); + rig.feed(&CommandResult::denied(&invocation, seq(1), "nope", None), at(1)); + assert_eq!(rig.state_of("go").mark, Some(Mark::Denied { reason: "nope".into() })); + assert_eq!(rig.state_of("field").mark, None); + + // A node the surface does not have: the issuing node, and a diagnostic. + let mut rig = Rig::new(MemState::new(), &denied_surface()); + let invocation = rig.mint("go", PINNED_NOW); + let answered = rig.feed(&CommandResult::denied(&invocation, seq(1), "huh", Some(nid("ghost"))), at(1)); + assert_eq!(codes(&answered.diagnostics), vec![Code::MalformedResult]); + assert_eq!(answered.diagnostics[0].detail, "denied node not in the surface"); + assert_eq!(rig.state_of("go").mark, Some(Mark::Denied { reason: "huh".into() })); + assert_eq!(rig.state_of("ghost").mark, None); +} + +#[test] +fn denied_in_a_row_marks_that_rows_node() { + let mut rig = Rig::new(rows_state(), &rows_surface()); + rig.act(&row("item-0003", "save"), ActivationKind::Press, PINNED_NOW, &mut SeqIds::new()); + let invocation = rig.commands.take_outbound().pop().unwrap(); + rig.feed(&CommandResult::denied(&invocation, seq(1), "bad note", Some(nid("note"))), at(1)); + assert_eq!(rig.state_of(row("item-0003", "note").as_str()).mark, Some(Mark::Denied { reason: "bad note".into() })); + assert_eq!(rig.state_of(row("item-0001", "note").as_str()).mark, None); +} + +// ----- the frame ----- + +fn core() -> Core { + Core::new(Config::new(thing_core::layout::Metrics::Cells, "renderer.web"), Box::new(FixedMeasure::cells())) +} + +fn frame_at(core: &mut Core, state: &mut MemState, now: Timestamp) -> thing_core::FrameOutput { + let input = FrameInput { now, viewport: (80.0, 24.0), scale: 1.0, events: vec![] }; + core.frame(input, Ports { state, ids: &mut SeqIds::new() }) +} + +#[test] +fn f02_through_the_frame() { + let set = Fixture::F02LoginEffect.load(); + let login = set.surfaces[0].clone(); + let expected = set.invocations[0].clone(); + let mut state = MemState::from_fixture(Fixture::F02LoginEffect); + let mut core = core(); + core.show(login.provider_id.clone(), RecordKey::new(login.record_key())); + let first = frame_at(&mut core, &mut state, PINNED_NOW); + assert!(first.outbound.is_empty() && first.effects.is_empty() && first.next_wake.is_none()); + + core.drafts_mut().set(&login.record_key(), &nid("username"), text_value("ada")); + let mut ids = ScriptedIds::new([expected.invocation_id.as_str()]); + let act = Activation { node: nid("sign-in-button"), kind: ActivationKind::Press }; + assert!(core.activate(act, PINNED_NOW, Ports { state: &mut state, ids: &mut ids }).is_empty()); + + let minted = frame_at(&mut core, &mut state, at(1)); + assert_eq!(minted.outbound, vec![expected.clone()]); + assert_eq!(minted.next_wake, Some(at(15_000))); + assert!(core.node_states().get(&nid("sign-in-button")).busy); + // The invocation left once. + assert!(frame_at(&mut core, &mut state, at(2)).outbound.is_empty()); + + // The results reach Commands::apply through the frame's drain; Pending renews the deadline. + state.put(&login.provider_id, &set.results[0]); + let pending = frame_at(&mut core, &mut state, at(1_000)); + assert_eq!(pending.next_wake, Some(at(16_000))); + assert!(pending.effects.is_empty()); + state.put(&login.provider_id, &set.results[1]); + let done = frame_at(&mut core, &mut state, at(2_000)); + assert_eq!(done.effects.len(), 1); + assert_eq!(done.next_wake, None); + assert!(!core.node_states().get(&nid("sign-in-button")).busy); + + // The host runs the effect, the session survives or not, and the resume comes back through Core. + let HostEffect::OpenExternal { resume, .. } = &done.effects[0] else { panic!() }; + let mut ids = ScriptedIds::new(["55555555-5555-4555-8555-555555555555"]); + assert!(core.resume(resume, at(3_000), Ports { state: &mut state, ids: &mut ids }).is_empty()); + let resumed = frame_at(&mut core, &mut state, at(3_001)); + assert_eq!(resumed.outbound.len(), 1); + assert_eq!(resumed.outbound[0].command, CommandId::new("login-resume")); + assert_eq!(resumed.outbound[0].source, nid("sign-in-button")); +} + +#[test] +fn the_frame_fires_a_timeout_once_and_leaving_the_surface_forgets_its_invocations() { + let set = Fixture::F02LoginEffect.load(); + let login = set.surfaces[0].clone(); + let mut state = MemState::from_fixture(Fixture::F02LoginEffect); + let mut core = core(); + core.show(login.provider_id.clone(), RecordKey::new(login.record_key())); + frame_at(&mut core, &mut state, PINNED_NOW); + core.drafts_mut().set(&login.record_key(), &nid("username"), text_value("ada")); + let act = Activation { node: nid("sign-in-button"), kind: ActivationKind::Press }; + core.activate(act, PINNED_NOW, Ports { state: &mut state, ids: &mut SeqIds::new() }); + frame_at(&mut core, &mut state, at(1)); + + assert!(frame_at(&mut core, &mut state, at(14_999)).diagnostics.is_empty()); + let late = frame_at(&mut core, &mut state, at(15_000)); + assert_eq!(codes(&late.diagnostics), vec![Code::InvocationTimedOut]); + assert_eq!(late.next_wake, None); + assert_eq!(core.node_states().get(&nid("sign-in-button")).mark, Some(Mark::TimedOut)); + assert!(frame_at(&mut core, &mut state, at(16_000)).diagnostics.is_empty()); + + // Showing nothing forgets the surface's marks. + core.show(login.provider_id.clone(), RecordKey::new("thing:surface:provider.login.none")); + frame_at(&mut core, &mut state, at(17_000)); + core.show(login.provider_id.clone(), RecordKey::new(login.record_key())); + frame_at(&mut core, &mut state, at(18_000)); + assert_eq!(core.node_states().get(&nid("sign-in-button")).mark, None); +} + +#[test] +fn a_republish_drops_the_drafts_of_the_nodes_it_removed() { + let provider = ProviderId::new(PROVIDER); + let two_inputs = surface(PROVIDER, boxed("root", vec![input("a", InputKind::Text, "", "go"), input("b", InputKind::Text, "", "go")]), vec![decl("go", &[], None)]); + let mut one_input = surface(PROVIDER, boxed("root", vec![input("a", InputKind::Text, "", "go")]), vec![decl("go", &[], None)]); + one_input.version = ver(2); + let mut state = MemState::new(); + state.put(&provider, &two_inputs); + let mut core = core(); + core.show(provider.clone(), RecordKey::new(two_inputs.record_key())); + frame_at(&mut core, &mut state, PINNED_NOW); + let key = two_inputs.record_key(); + core.drafts_mut().set(&key, &nid("a"), text_value("kept")); + core.drafts_mut().set(&key, &nid("b"), text_value("gone")); + state.put(&provider, &one_input); + frame_at(&mut core, &mut state, at(1)); + assert_eq!(core.drafts_mut().get(&key, &nid("a")), Some(&text_value("kept"))); + assert_eq!(core.drafts_mut().get(&key, &nid("b")), None); +} + +/// An invocation core never issued. +fn stranger() -> CommandInvocation { + let mut invocation = invocation(); + invocation.invocation_id = "33333333-3333-4333-8333-333333333333".into(); + invocation +} diff --git a/crates/thing-core/tests/frame.rs b/crates/thing-core/tests/frame.rs index 573c78d..c35559b 100644 --- a/crates/thing-core/tests/frame.rs +++ b/crates/thing-core/tests/frame.rs @@ -14,6 +14,7 @@ use thing_core::time::Timestamp; use thing_core::{Config, Core, FrameInput, FrameOutput, Ports}; use thing_testkit::build::*; use thing_testkit::fixture::Fixture; +use thing_testkit::ids::SeqIds; use thing_testkit::measure::FixedMeasure; use thing_testkit::mem_state::{Call, MemState}; use thing_testkit::state::{self, Swarm}; @@ -28,7 +29,7 @@ fn measure(metrics: Metrics) -> FixedMeasure { } fn fresh(metrics: Metrics) -> Core { - Core::new(Config::new(metrics), Box::new(measure(metrics))) + Core::new(Config::new(metrics, "renderer.test"), Box::new(measure(metrics))) } fn input(viewport: (f32, f32), scale: f32) -> FrameInput { @@ -36,7 +37,7 @@ fn input(viewport: (f32, f32), scale: f32) -> FrameInput { } fn run(core: &mut Core, state: &mut MemState, input: FrameInput) -> FrameOutput { - core.frame(input, Ports { state }) + core.frame(input, Ports { state, ids: &mut SeqIds::new() }) } fn show(core: &mut Core, document: &SurfaceDocument) { diff --git a/crates/thing-testkit/src/ids.rs b/crates/thing-testkit/src/ids.rs new file mode 100644 index 0000000..be63c1b --- /dev/null +++ b/crates/thing-testkit/src/ids.rs @@ -0,0 +1,58 @@ +//! Id sources for tests: a script of the UUIDs a fixture holds, and a counter. + +use thing_core::port::IdSource; + +/// Gives the UUIDs it was built with, in order, as the 16 bytes they spell. A fixture id is +/// already v4, so core's version and variant bits leave it as it was. Panics when exhausted. +#[derive(Debug)] +pub struct ScriptedIds { + left: std::vec::IntoIter<[u8; 16]>, +} + +impl ScriptedIds { + pub fn new>(uuids: impl IntoIterator) -> Self { + let decoded: Vec<[u8; 16]> = uuids + .into_iter() + .map(|uuid| { + let digits: Vec = uuid.as_ref().bytes().filter(|byte| *byte != b'-').collect(); + assert_eq!(digits.len(), 32, "{} is not a UUID", uuid.as_ref()); + let mut bytes = [0u8; 16]; + for (byte, pair) in bytes.iter_mut().zip(digits.chunks(2)) { + *byte = u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).expect("hex digits"); + } + bytes + }) + .collect(); + Self { left: decoded.into_iter() } + } + + /// How many ids have not been drawn. + pub fn remaining(&self) -> usize { + self.left.len() + } +} + +impl IdSource for ScriptedIds { + fn fill(&mut self, bytes: &mut [u8; 16]) { + *bytes = self.left.next().expect("ScriptedIds ran out of ids"); + } +} + +/// Counts: the first id spells 1, the next 2. +#[derive(Debug, Default)] +pub struct SeqIds { + next: u128, +} + +impl SeqIds { + pub fn new() -> Self { + Self::default() + } +} + +impl IdSource for SeqIds { + fn fill(&mut self, bytes: &mut [u8; 16]) { + self.next += 1; + *bytes = self.next.to_be_bytes(); + } +} diff --git a/crates/thing-testkit/src/lib.rs b/crates/thing-testkit/src/lib.rs index dc4511d..b4601b3 100644 --- a/crates/thing-testkit/src/lib.rs +++ b/crates/thing-testkit/src/lib.rs @@ -4,6 +4,7 @@ pub mod build; pub mod fixture; pub mod golden; +pub mod ids; pub mod measure; pub mod mem_state; pub mod state; diff --git a/crates/thing-testkit/src/mem_state.rs b/crates/thing-testkit/src/mem_state.rs index 2d254ba..39e603f 100644 --- a/crates/thing-testkit/src/mem_state.rs +++ b/crates/thing-testkit/src/mem_state.rs @@ -146,7 +146,10 @@ impl MemState { } } - /// A state holding every document of a fixture, each under the provider that publishes it. + /// A state holding every document of a fixture, each under the provider that publishes it. Invocations + /// and results are skipped: they are timeline data, not initial state. A test takes them from + /// `Fixture::load` and puts each result with `put` at its scripted step, after core minted its + /// invocation, and compares that invocation with the fixture's (the fixture is the expected output). pub fn from_fixture(fixture: crate::fixture::Fixture) -> Self { let set = fixture.load(); let mut state = Self::new(); diff --git a/crates/thing-testkit/src/store.rs b/crates/thing-testkit/src/store.rs index 919a24b..005d499 100644 --- a/crates/thing-testkit/src/store.rs +++ b/crates/thing-testkit/src/store.rs @@ -8,6 +8,9 @@ use thing_contract::ThingContract; pub const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z"; +/// `PINNED_CLOCK` as core is told time: Unix milliseconds. +pub const PINNED_NOW: thing_core::time::Timestamp = thing_core::time::Timestamp(1_767_225_600_000); + /// A cache with the contract registered and no backing store. pub fn memory() -> CultCache { let mut cache = CultCache::new();