Skip to main content

tilo_actions/
schema.rs

1//! Presence-independent catalogue schema.
2//!
3//! A multi-presence app (Writer) builds a different resource tree for each
4//! presence's caret, selection and Find hits. What it publishes to the
5//! broker, and what grants are checked against, must not be one caret's
6//! snapshot: that would churn the publication revision on every caret move
7//! and would hide operations that another presence could use.
8//!
9//! Instead an app publishes its catalogue schema: stable addresses whose
10//! context-dependent preconditions are declared as flags
11//! ([`ContextRequirement`], carried in [`ActionContract::tags`]). At invoke
12//! time the host rebuilds the invoker's own tree; an operation whose
13//! precondition is not met there is refused with
14//! [`ContextRequirement::refusal`].
15//!
16//! [`catalogue_schema`] reduces a surveyed catalogue to entries keyed by
17//! resource kind rather than resource id, so volatile, document-derived ids
18//! (a search hit, a selection range) never change the schema.
19
20use serde::{Deserialize, Serialize};
21
22use crate::{
23    ActionContract, ActionDescriptor, ActionParam, ActionSpec, ApiError, ExecutionLocus,
24    OperationKind,
25};
26
27/// Prefix of the contract tags that declare a context precondition.
28pub const REQUIRES_TAG_PREFIX: &str = "tilo.requires.";
29
30/// Contract tag of a View operation that changes only the invoking
31/// presence's own view (its caret, selection or Find state). Only such an
32/// operation may be invoked by a remote presence: every other View
33/// operation moves the local person's private view and stays refused.
34pub const PRESENCE_VIEW_TAG: &str = "tilo.presence-view";
35
36/// A precondition on the invoking presence's view. Declared on the
37/// published schema as an availability flag; checked against the invoker's
38/// own view at invoke time.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
40#[serde(rename_all = "kebab-case")]
41pub enum ContextRequirement {
42    /// The presence has a caret in an editable region.
43    Caret,
44    /// The presence has a non-empty selection.
45    Selection,
46    /// The presence has live Find results.
47    FindHits,
48}
49
50impl ContextRequirement {
51    pub const ALL: [Self; 3] = [Self::Caret, Self::Selection, Self::FindHits];
52
53    /// The contract tag declaring this requirement.
54    pub const fn tag(self) -> &'static str {
55        match self {
56            Self::Caret => "tilo.requires.caret",
57            Self::Selection => "tilo.requires.selection",
58            Self::FindHits => "tilo.requires.find-hits",
59        }
60    }
61
62    /// Stable refusal code, e.g. `needs-selection`.
63    pub const fn refusal_code(self) -> &'static str {
64        match self {
65            Self::Caret => "needs-caret",
66            Self::Selection => "needs-selection",
67            Self::FindHits => "needs-find-hits",
68        }
69    }
70
71    /// The refusal for an invocation whose invoker's view does not meet
72    /// this requirement.
73    pub fn refusal(self) -> ApiError {
74        let reason = match self {
75            Self::Caret => "Place the caret in the document first",
76            Self::Selection => "Select some text first",
77            Self::FindHits => "Find something first",
78        };
79        ApiError::Unavailable {
80            code: self.refusal_code().into(),
81            reason: reason.into(),
82        }
83    }
84
85    fn from_tag(tag: &str) -> Option<Self> {
86        Self::ALL
87            .into_iter()
88            .find(|requirement| requirement.tag() == tag)
89    }
90}
91
92impl ActionContract {
93    /// The context preconditions declared on this contract, in order.
94    pub fn requirements(&self) -> Vec<ContextRequirement> {
95        let mut requirements: Vec<_> = self
96            .tags
97            .iter()
98            .filter_map(|tag| ContextRequirement::from_tag(tag))
99            .collect();
100        requirements.sort_unstable();
101        requirements.dedup();
102        requirements
103    }
104
105    /// Whether this View contract changes only the invoking presence's
106    /// view ([`PRESENCE_VIEW_TAG`]).
107    pub fn is_presence_view(&self) -> bool {
108        self.tags.iter().any(|tag| tag == PRESENCE_VIEW_TAG)
109    }
110
111    fn add_tag(&mut self, tag: &str) {
112        if !self.tags.iter().any(|existing| existing == tag) {
113            self.tags.push(tag.to_owned());
114        }
115    }
116}
117
118impl ActionSpec {
119    /// Declare a precondition on the invoker's view. The operation stays at
120    /// its stable address in every presence's tree and in the published
121    /// schema; the invoker's tree refuses it when the precondition fails.
122    #[must_use]
123    pub fn requires(mut self, requirement: ContextRequirement) -> Self {
124        self.type_mut().contract.add_tag(requirement.tag());
125        self
126    }
127
128    /// Declare that this View operation changes only the invoking
129    /// presence's own view, so a remote presence may invoke it.
130    #[must_use]
131    pub fn presence_view(mut self) -> Self {
132        self.type_mut().contract.add_tag(PRESENCE_VIEW_TAG);
133        self
134    }
135}
136
137/// One presence-independent catalogue entry. Keyed by resource kind and
138/// action id, never by the (possibly document- or view-derived) resource id.
139#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
140pub struct CatalogueSchemaEntry {
141    pub resource_kind: String,
142    pub action: String,
143    pub kind: OperationKind,
144    pub locus: ExecutionLocus,
145    pub contract: ActionContract,
146    pub params: Vec<ActionParam>,
147}
148
149impl CatalogueSchemaEntry {
150    pub fn of(descriptor: &ActionDescriptor) -> Self {
151        Self {
152            resource_kind: descriptor.resource_kind.clone(),
153            action: descriptor.address.action.clone(),
154            kind: descriptor.kind,
155            locus: descriptor.locus,
156            contract: descriptor.contract.clone(),
157            params: descriptor.params.clone(),
158        }
159    }
160
161    fn sort_key(&self) -> (String, String, String) {
162        (
163            self.resource_kind.clone(),
164            self.action.clone(),
165            serde_json::to_string(self).unwrap_or_default(),
166        )
167    }
168}
169
170/// Reduce a surveyed catalogue to its presence-independent schema:
171/// entries keyed by resource kind, sorted, duplicates removed. Two
172/// catalogues that differ only in volatile resource ids, labels or order
173/// have the same schema.
174pub fn catalogue_schema(descriptors: &[ActionDescriptor]) -> Vec<CatalogueSchemaEntry> {
175    let mut entries: Vec<_> = descriptors
176        .iter()
177        .map(CatalogueSchemaEntry::of)
178        .map(|entry| (entry.sort_key(), entry))
179        .collect();
180    entries.sort_by(|a, b| a.0.cmp(&b.0));
181    entries.dedup_by(|a, b| a.0 == b.0);
182    entries.into_iter().map(|(_, entry)| entry).collect()
183}
184
185/// Canonical bytes of a schema, for a host to digest into a stable
186/// publication revision or a frozen grant schema digest.
187pub fn catalogue_schema_bytes(entries: &[CatalogueSchemaEntry]) -> Vec<u8> {
188    serde_json::to_vec(entries).unwrap_or_default()
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::{EncodedAction, ResourceSpec, api};
195
196    fn encoded(tag: &str) -> EncodedAction {
197        EncodedAction {
198            type_id: "fixture.action".into(),
199            payload: tag.as_bytes().to_vec(),
200        }
201    }
202
203    /// Minimal multi-presence provider: each presence has its own
204    /// caret block and optional selection.
205    struct TwoViews {
206        views: std::collections::HashMap<String, (String, bool)>,
207        own: (String, bool),
208    }
209
210    fn tree(caret: &str, selected: bool, schema: bool) -> Vec<ResourceSpec> {
211        let mut root = ResourceSpec::new("doc", "fixture.document", "Document").with_action(
212            ActionSpec::immediate_encoded(
213                "type-text",
214                "Type",
215                ExecutionLocus::ClientLocal,
216                encoded(&format!("type@{caret}")),
217            )
218            .requires(ContextRequirement::Caret),
219        );
220        if schema || selected {
221            root = root.with_action(
222                ActionSpec::immediate_encoded(
223                    "toggle-mark",
224                    "Bold",
225                    ExecutionLocus::ClientLocal,
226                    encoded(&format!("bold@{caret}")),
227                )
228                .requires(ContextRequirement::Selection),
229            );
230        }
231        if !schema {
232            // Volatile, view-derived resource ids never enter the schema.
233            root = root.with_child(
234                ResourceSpec::new(format!("doc.caret:{caret}"), "fixture.caret", "Caret")
235                    .with_action(ActionSpec::immediate_encoded(
236                        "go-to",
237                        "Go to",
238                        ExecutionLocus::ClientLocal,
239                        encoded(caret),
240                    )),
241            );
242        }
243        vec![root]
244    }
245
246    impl TwoViews {
247        /// The tree `presence` sees; `None` is the local window's.
248        fn resources_for(&self, presence: Option<&crate::PresenceId>) -> Vec<ResourceSpec> {
249            let Some(presence) = presence else {
250                return tree(&self.own.0, self.own.1, false);
251            };
252            self.views
253                .get(presence.as_str())
254                .map_or_else(Vec::new, |(caret, selected)| tree(caret, *selected, false))
255        }
256    }
257
258    /// The presence-independent schema every view publishes.
259    fn schema_tree() -> Vec<ResourceSpec> {
260        let mut schema = tree("", false, true);
261        schema.push(
262            ResourceSpec::new("doc.caret", "fixture.caret", "Caret").with_action(
263                ActionSpec::immediate_encoded(
264                    "go-to",
265                    "Go to",
266                    ExecutionLocus::ClientLocal,
267                    encoded(""),
268                ),
269            ),
270        );
271        schema
272    }
273
274    fn provider(agent_caret: &str, agent_selected: bool) -> TwoViews {
275        TwoViews {
276            views: [(
277                "window:t".to_string(),
278                (agent_caret.to_string(), agent_selected),
279            )]
280            .into(),
281            own: ("b1".into(), false),
282        }
283    }
284
285    tilo_test_env::scenario! {
286        fn a_schema_is_stable_and_per_invoker;
287
288        phase requirement_flags_round_trip_through_contract_tags;
289        {
290            let spec =
291                ActionSpec::immediate_encoded("x", "X", ExecutionLocus::ClientLocal, encoded("x"))
292                    .requires(ContextRequirement::Selection)
293                    .requires(ContextRequirement::Selection)
294                    .requires(ContextRequirement::Caret)
295                    .presence_view();
296            assert_eq!(
297                spec.contract.requirements(),
298                vec![ContextRequirement::Caret, ContextRequirement::Selection]
299            );
300            assert!(spec.contract.is_presence_view());
301            assert_eq!(spec.contract.tags.len(), 3, "tags are not duplicated");
302            assert!(matches!(
303                ContextRequirement::Selection.refusal(),
304                ApiError::Unavailable { ref code, .. } if code == "needs-selection"
305            ));
306            let json = serde_json::to_value(&spec.contract).unwrap();
307            let back: ActionContract = serde_json::from_value(json).unwrap();
308            assert_eq!(back.requirements(), spec.contract.requirements());
309        }
310
311        phase schema_is_stable_across_caret_moves_and_selection;
312        {
313            let before = provider("b1", false);
314            let after = provider("b7", true);
315            let presence = crate::PresenceId::new("window:t").unwrap();
316            // The presence's own trees differ (caret-derived ids, selection).
317            assert_ne!(
318                api::survey(&before.resources_for(Some(&presence))).len(),
319                api::survey(&after.resources_for(Some(&presence))).len()
320            );
321            let schema = catalogue_schema(&api::survey(&schema_tree()));
322            // Every operation a presence can reach has an entry in the schema,
323            // whatever its caret: grants checked against the schema cover it.
324            for provider in [&before, &after] {
325                for entry in
326                    catalogue_schema(&api::survey(&provider.resources_for(Some(&presence))))
327                {
328                    assert!(
329                        schema
330                            .iter()
331                            .any(|schema| schema.resource_kind == entry.resource_kind
332                                && schema.action == entry.action
333                                && schema.contract == entry.contract),
334                        "{} {} missing from schema",
335                        entry.resource_kind,
336                        entry.action
337                    );
338                }
339            }
340        }
341
342        phase schema_ignores_volatile_ids_labels_and_order;
343        {
344            let a = api::survey(&tree("b1", false, false));
345            let mut b = api::survey(&tree("b99", false, false));
346            b.reverse();
347            for descriptor in &mut b {
348                descriptor.resource_label = "Renamed".into();
349            }
350            assert_eq!(catalogue_schema(&a), catalogue_schema(&b));
351        }
352
353        phase resolution_is_per_invoker;
354        {
355            let provider = provider("b7", true);
356            let agent = crate::PresenceId::new("window:t").unwrap();
357            let address = api::ActionAddress::new("doc", "type-text");
358            let agent_tree = provider.resources_for(Some(&agent));
359            let own_tree = provider.resources_for(None);
360            assert_eq!(
361                api::encode(&agent_tree, &address, None).unwrap().payload,
362                b"type@b7".to_vec()
363            );
364            assert_eq!(
365                api::encode(&own_tree, &address, None).unwrap().payload,
366                b"type@b1".to_vec()
367            );
368            // Selection-scoped ops exist only in the tree of the presence
369            // that has a selection.
370            let bold = api::ActionAddress::new("doc", "toggle-mark");
371            assert!(api::resolve(&agent_tree, &bold).is_some());
372            assert!(api::resolve(&own_tree, &bold).is_none());
373            // An unknown presence gets no tree at all, not the default view.
374            let stranger = crate::PresenceId::new("window:other").unwrap();
375            assert!(provider.resources_for(Some(&stranger)).is_empty());
376        }
377    }
378}