Skip to main content

tilo_resource/
group.rs

1//! Several actions applied as one: one change, one version in history, one
2//! undo step, one permission decision.
3//!
4//! One action is one undo step, and that is the right default: a control, a
5//! palette entry or an agent call is one thing the user did. A *gesture* can
6//! be several — splitting a linked video and audio clip, deleting a
7//! selection, a paste — and the user expects one Ctrl+Z to take all of it
8//! back. [`ActionGroup`] carries such a gesture as one replayable action; the
9//! framework's `Dispatcher::group` and [`Invoke::group`](crate::Invoke::group)
10//! build it from ordinary invocations.
11
12use std::cell::Cell;
13
14use serde::{Deserialize, Serialize};
15use tilo_actions::{ActionError, ActionRegistry, ExecutionLocus, RiskLevel};
16
17use crate::model::Doc;
18use crate::resource::Resource;
19use crate::vocabulary::{Built, Vocabulary, vocabulary};
20
21/// The id of the action every resource publishes that applies several of its
22/// actions, in order, as one.
23pub const GROUP: &str = "group";
24/// The parameter of [`GROUP`]: an array of `{ "action": id, "args": {..} }`
25/// invocations of the resource's other actions.
26pub const GROUP_PARAM: &str = "actions";
27
28/// Several actions of one resource, applied in order as one change.
29///
30/// Replay is exact: members apply inside one transaction, and the ids a
31/// member mints from its [`ActionCx`](crate::ActionCx) are seeded by the
32/// group and the member's position, so every replica mints the same ones.
33/// A member that refuses refuses the whole group, and nothing is applied.
34/// Its payload is the list of its members; [`tilo_actions::group_form`]
35/// writes what they share once when it is encoded and restores it when it
36/// is read, on the encoded payload, so a group adds no serde code of its own
37/// per action type.
38#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
39#[serde(transparent)]
40pub struct ActionGroup<A> {
41    pub actions: Vec<A>,
42}
43
44thread_local! {
45    /// The seed and position of the group member being applied, if any.
46    static MEMBER: Cell<Option<([u8; 32], u64)>> = const { Cell::new(None) };
47}
48
49/// Inside a group member's `apply`: the group's seed and the member's
50/// position. [`ActionCx::for_apply`](crate::ActionCx::for_apply) uses it in
51/// place of the document's heads, which a member cannot read without
52/// committing its predecessors' changes separately.
53pub(crate) fn current_member() -> Option<([u8; 32], u64)> {
54    MEMBER.with(Cell::get)
55}
56
57type DeferredCheck = Box<dyn Fn(&Doc) -> Result<(), crate::Refusal>>;
58
59thread_local! {
60    /// The record checks deferred to the end of the group applying on this
61    /// thread, by what they check; `None` outside a group.
62    static DEFERRED: std::cell::RefCell<Option<Vec<(String, DeferredCheck)>>> =
63        const { std::cell::RefCell::new(None) };
64}
65
66/// Run a record's `#[model(check)]` now, or, inside a group, once at its
67/// end: a group valid as a whole may pass through a state that is not (two
68/// dangling references cleared one after the other). `key` names what is
69/// checked, so it runs once however many members touched it.
70#[doc(hidden)]
71pub fn check_or_defer(
72    key: String,
73    doc: &Doc,
74    check: impl Fn(&Doc) -> Result<(), crate::Refusal> + 'static,
75) -> Result<(), crate::Refusal> {
76    let grouping = DEFERRED.with(|deferred| deferred.borrow().is_some());
77    if !grouping {
78        return check(doc);
79    }
80    DEFERRED.with(|deferred| {
81        if let Some(checks) = deferred.borrow_mut().as_mut()
82            && !checks.iter().any(|(existing, _)| *existing == key)
83        {
84            checks.push((key, Box::new(check)));
85        }
86    });
87    Ok(())
88}
89
90/// Whether a group is applying on this thread: record checks wait for its
91/// end.
92pub(crate) fn grouping() -> bool {
93    DEFERRED.with(|deferred| deferred.borrow().is_some())
94}
95
96/// Runs the checks deferred in a group when the outermost group ends.
97struct Deferring(bool);
98
99impl Deferring {
100    fn begin() -> Self {
101        let outermost = DEFERRED.with(|deferred| {
102            let mut deferred = deferred.borrow_mut();
103            if deferred.is_some() {
104                return false;
105            }
106            *deferred = Some(Vec::new());
107            true
108        });
109        if outermost {
110            crate::action::hold_records();
111        }
112        Self(outermost)
113    }
114
115    /// The records the group held, written once, then the deferred checks, run once on the
116    /// group's result.
117    fn finish(&self, doc: &mut Doc) -> Result<(), ActionError> {
118        if !self.0 {
119            return Ok(());
120        }
121        crate::action::write_held(doc)?;
122        let checks = DEFERRED.with(|deferred| deferred.borrow_mut().take().unwrap_or_default());
123        for (_, check) in checks {
124            check(doc).map_err(ActionError::from)?;
125        }
126        Ok(())
127    }
128}
129
130impl Drop for Deferring {
131    fn drop(&mut self) {
132        if self.0 {
133            DEFERRED.with(|deferred| deferred.borrow_mut().take());
134            crate::action::drop_held();
135        }
136    }
137}
138
139/// Restores the enclosing member (for a group applied inside a group) even
140/// when a member unwinds.
141struct MemberScope(Option<([u8; 32], u64)>);
142
143impl Drop for MemberScope {
144    fn drop(&mut self) {
145        MEMBER.with(|member| member.set(self.0));
146    }
147}
148
149impl<A> ActionGroup<A>
150where
151    A: tilo_actions::Action,
152{
153    /// The members, of whichever type.
154    fn members(&self) -> Vec<&dyn tilo_actions::Action> {
155        let mut members: Vec<&dyn tilo_actions::Action> = Vec::with_capacity(self.actions.len());
156        for action in &self.actions {
157            members.push(action);
158        }
159        members
160    }
161}
162
163impl<A> tilo_actions::Action for ActionGroup<A>
164where
165    A: tilo_actions::Action + Serialize + serde::de::DeserializeOwned,
166{
167    fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
168        let payload = serde_json::to_vec(&self.actions).map_err(ActionError::Encode)?;
169        // A member that names another's item is decoded as it applies; one
170        // that does not is applied as it was built, as every bulk call's
171        // members are.
172        if !payload.windows(6).any(|window| window == b"$made:") {
173            return apply_prepared(doc, &payload, &self.members());
174        }
175        apply_encoded(doc, &payload, &|doc, member| {
176            serde_json::from_value::<A>(member)
177                .map_err(ActionError::Encode)?
178                .apply(doc)
179        })
180    }
181
182    /// A group is as consequential as its most consequential member: one
183    /// deletion in a gesture makes the gesture ask for confirmation.
184    fn risk(&self) -> RiskLevel {
185        group_risk(self.members().into_iter().map(tilo_actions::Action::risk))
186    }
187
188    /// A gesture records each of its members, and the item they share.
189    fn describe(&self, doc: &Doc) -> Option<tilo_actions::Described> {
190        describe_members(doc, &self.members(), &|index| {
191            crate::__private::json_via_bytes(self.actions.get(index)?).ok()
192        })
193    }
194
195    /// The first item a member made, which the members' descriptions read
196    /// before they applied could not name.
197    fn made(&self, doc: &Doc) -> Option<tilo_actions::ActionItem> {
198        self.members()
199            .into_iter()
200            .find_map(|member| member.made(doc))
201    }
202
203    fn locus(&self) -> ExecutionLocus {
204        self.actions
205            .first()
206            .map_or(ExecutionLocus::ClientLocal, tilo_actions::Action::locus)
207    }
208
209    /// A gesture is someone's step when any member is: one content change
210    /// makes it content. Otherwise it is external when any member is, and
211    /// housekeeping when every member is.
212    fn change_kind(&self) -> tilo_actions::ChangeKind {
213        group_change_kind(&self.members())
214    }
215
216    /// A gesture that records a received message among others still
217    /// records one.
218    fn incoming_message(&self) -> bool {
219        self.actions
220            .iter()
221            .any(tilo_actions::Action::incoming_message)
222    }
223
224    /// Undo cannot take a gesture back when it cannot take back a member.
225    fn irreversible(&self) -> bool {
226        self.actions.iter().any(tilo_actions::Action::irreversible)
227    }
228}
229
230/// Apply `members`, a group encoded as `payload`, in order as one: every
231/// member as it was built, with no reference to fill.
232fn apply_prepared(
233    doc: &mut Doc,
234    payload: &[u8],
235    members: &[&dyn tilo_actions::Action],
236) -> Result<(), ActionError> {
237    let seed = crate::action::seed(doc, b"tilo-resource/group-seed/v1", payload);
238    if current_member().is_none() {
239        crate::action::start_minting();
240    }
241    let deferring = Deferring::begin();
242    {
243        let _restore = MemberScope(current_member());
244        let mut position = 0_u64;
245        for action in members {
246            MEMBER.with(|member| member.set(Some((seed, position))));
247            action.apply(doc)?;
248            position = position.saturating_add(1);
249        }
250    }
251    deferring.finish(doc)
252}
253
254/// Apply the members `payload` encodes, in order as one, each filled with the
255/// ids the members before it made: a member names an item an earlier one
256/// creates with a [`MADE`](tilo_actions::params::MADE) reference, and that
257/// member's id is known only as the group applies. The payload keeps the
258/// reference, so a replica fills it with the same id.
259fn apply_encoded(
260    doc: &mut Doc,
261    payload: &[u8],
262    apply_member: &dyn Fn(&mut Doc, serde_json::Value) -> Result<(), ActionError>,
263) -> Result<(), ActionError> {
264    let members: Vec<serde_json::Value> =
265        serde_json::from_slice(payload).map_err(ActionError::Encode)?;
266    let seed = crate::action::seed(doc, b"tilo-resource/group-seed/v1", payload);
267    if current_member().is_none() {
268        crate::action::start_minting();
269    }
270    let deferring = Deferring::begin();
271    let mut made: Vec<Vec<String>> = Vec::with_capacity(members.len());
272    {
273        let _restore = MemberScope(current_member());
274        for (position, member) in members.into_iter().enumerate() {
275            let position = u64::try_from(position).unwrap_or(u64::MAX);
276            MEMBER.with(|member| member.set(Some((seed, position))));
277            let mut member = member;
278            fill_made(&mut member, &made)?;
279            apply_member(doc, member)?;
280            made.push(crate::action::take_minted());
281        }
282    }
283    deferring.finish(doc)?;
284    // What the members minted together, in the order they were made, put down
285    // again: the one who invoked the group learns every item it made, as from
286    // one action.
287    for member in &made {
288        for id in member {
289            crate::action::note_minted(id);
290        }
291    }
292    Ok(())
293}
294
295/// Fill each [`MADE`](tilo_actions::params::MADE) marker in `member` with the
296/// id it names among those `made` minted, in order.
297fn fill_made(value: &mut serde_json::Value, made: &[Vec<String>]) -> Result<(), ActionError> {
298    match value {
299        serde_json::Value::String(text) => {
300            if let Some((member, item)) = tilo_actions::params::made_of_marker(text) {
301                let id = made
302                    .get(member)
303                    .and_then(|made| made.get(item))
304                    .ok_or_else(|| {
305                        ActionError::Refused(format!(
306                            "the group has made no item {item} at member {member} to name"
307                        ))
308                    })?;
309                text.clone_from(id);
310            }
311            Ok(())
312        }
313        serde_json::Value::Array(items) => {
314            for item in items {
315                fill_made(item, made)?;
316            }
317            Ok(())
318        }
319        serde_json::Value::Object(fields) => {
320            for field in fields.values_mut() {
321                fill_made(field, made)?;
322            }
323            Ok(())
324        }
325        _ => Ok(()),
326    }
327}
328
329/// What a group of `members` did: each member's description, or its JSON
330/// form (`value(index)`) where it has none, and the item they share.
331fn describe_members(
332    doc: &Doc,
333    members: &[&dyn tilo_actions::Action],
334    value: &dyn Fn(usize) -> Option<serde_json::Value>,
335) -> Option<tilo_actions::Described> {
336    let mut described: Vec<tilo_actions::Described> = Vec::with_capacity(members.len());
337    for (index, action) in members.iter().enumerate() {
338        let member = match action.describe(doc) {
339            Some(member) => member,
340            None => tilo_actions::Described::from_value("", &value(index)?, None)?,
341        };
342        described.push(member);
343    }
344    let item = described.first().and_then(|first| first.item.clone());
345    let shared = described.iter().all(|member| member.item == item);
346    Some(tilo_actions::Described {
347        what: tilo_actions::Did::group(described.into_iter().map(|member| member.what)),
348        item: if shared { item } else { None },
349    })
350}
351
352fn group_change_kind(members: &[&dyn tilo_actions::Action]) -> tilo_actions::ChangeKind {
353    use tilo_actions::ChangeKind;
354    let mut kinds = members.iter().map(|member| member.change_kind());
355    let Some(first) = kinds.next() else {
356        return ChangeKind::Content;
357    };
358    kinds.fold(first, |group, member| match (group, member) {
359        (ChangeKind::Content, _) | (_, ChangeKind::Content) => ChangeKind::Content,
360        (ChangeKind::External, _) | (_, ChangeKind::External) => ChangeKind::External,
361        (ChangeKind::Housekeeping, ChangeKind::Housekeeping) => ChangeKind::Housekeeping,
362    })
363}
364
365/// How consequential a group of actions as consequential as `risks` is: as
366/// its most consequential member. One deletion in a gesture makes the
367/// gesture ask for confirmation.
368pub(crate) fn group_risk(risks: impl IntoIterator<Item = RiskLevel>) -> RiskLevel {
369    let mut risk = RiskLevel::None;
370    for member in risks {
371        match member {
372            consequential if consequential.requires_confirmation() => return consequential,
373            RiskLevel::Low => risk = RiskLevel::Low,
374            _ => {}
375        }
376    }
377    risk
378}
379
380/// The registry type id groups of `R`'s actions are replayed under.
381pub fn group_type<R: Resource>() -> String {
382    group_type_of(R::ACTION_TYPE)
383}
384
385/// The registry type id groups of the actions of the type `action_type`
386/// are replayed under.
387pub(crate) fn group_type_of(action_type: &str) -> String {
388    format!("{action_type}{}", tilo_actions::group_form::GROUP_SUFFIX)
389}
390
391/// Register everything a replica of `R` replays: the resource's own actions
392/// ([`Resource::register`]) and groups of them.
393pub fn register<R: Resource>(registry: &mut ActionRegistry) {
394    R::register(registry);
395    registry.register::<ActionGroup<R::Action>>(group_type::<R>());
396}
397
398/// Build the group [`GROUP`] invocations describe: each member is built from
399/// its own declaration exactly as if it were invoked alone.
400pub fn build_group<R: Resource>(
401    arguments: &serde_json::Map<String, serde_json::Value>,
402    now_ms: i64,
403) -> Result<ActionGroup<R::Action>, String> {
404    let members = build_members(vocabulary::<R>(), arguments, now_ms)?;
405    let mut actions = Vec::with_capacity(members.len());
406    for member in members {
407        match member.into_action::<R>() {
408            Some(action) => actions.push(action),
409            None => return Err(format!("not an action of a {}", R::LABEL)),
410        }
411    }
412    Ok(ActionGroup { actions })
413}
414
415pub(crate) fn build_members(
416    vocabulary: &Vocabulary,
417    arguments: &serde_json::Map<String, serde_json::Value>,
418    now_ms: i64,
419) -> Result<Vec<Built>, String> {
420    let Some(serde_json::Value::Array(members)) = arguments.get(GROUP_PARAM) else {
421        return Err(format!("`{GROUP_PARAM}` must be an array of invocations"));
422    };
423    let mut built = Vec::with_capacity(members.len());
424    for (index, member) in members.iter().enumerate() {
425        let Some(id) = member.get("action").and_then(serde_json::Value::as_str) else {
426            return Err(format!("member {index} names no `action`"));
427        };
428        if id == GROUP {
429            return Err(format!("member {index}: a group member cannot be a group"));
430        }
431        let args = match member.get("args") {
432            None | Some(serde_json::Value::Null) => serde_json::Map::new(),
433            Some(serde_json::Value::Object(args)) => args.clone(),
434            Some(_) => {
435                return Err(format!(
436                    "member {index}: the arguments of `{id}` must be an object"
437                ));
438            }
439        };
440        match crate::resource::build_action_of(vocabulary, id, &args, now_ms) {
441            Ok(action) => built.push(action),
442            Err(reason) => return Err(format!("member {index} ({id}): {reason}")),
443        }
444    }
445    Ok(built)
446}