tilo-resource 0.5.0

The Tilo resource layer: typed, hierarchical app resources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Several actions applied as one: one change, one version in history, one
//! undo step, one permission decision.
//!
//! One action is one undo step, and that is the right default: a control, a
//! palette entry or an agent call is one thing the user did. A *gesture* can
//! be several — splitting a linked video and audio clip, deleting a
//! selection, a paste — and the user expects one Ctrl+Z to take all of it
//! back. [`ActionGroup`] carries such a gesture as one replayable action; the
//! framework's `Dispatcher::group` and [`Invoke::group`](crate::Invoke::group)
//! build it from ordinary invocations.

use std::cell::Cell;

use serde::{Deserialize, Serialize};
use tilo_actions::{ActionError, ActionRegistry, ExecutionLocus, RiskLevel};

use crate::model::Doc;
use crate::resource::Resource;
use crate::vocabulary::{Built, Vocabulary, vocabulary};

/// The id of the action every resource publishes that applies several of its
/// actions, in order, as one.
pub const GROUP: &str = "group";
/// The parameter of [`GROUP`]: an array of `{ "action": id, "args": {..} }`
/// invocations of the resource's other actions.
pub const GROUP_PARAM: &str = "actions";

/// Several actions of one resource, applied in order as one change.
///
/// Replay is exact: members apply inside one transaction, and the ids a
/// member mints from its [`ActionCx`](crate::ActionCx) are seeded by the
/// group and the member's position, so every replica mints the same ones.
/// A member that refuses refuses the whole group, and nothing is applied.
/// Its payload is the list of its members; [`tilo_actions::group_form`]
/// writes what they share once when it is encoded and restores it when it
/// is read, on the encoded payload, so a group adds no serde code of its own
/// per action type.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(transparent)]
pub struct ActionGroup<A> {
    pub actions: Vec<A>,
}

thread_local! {
    /// The seed and position of the group member being applied, if any.
    static MEMBER: Cell<Option<([u8; 32], u64)>> = const { Cell::new(None) };
}

/// Inside a group member's `apply`: the group's seed and the member's
/// position. [`ActionCx::for_apply`](crate::ActionCx::for_apply) uses it in
/// place of the document's heads, which a member cannot read without
/// committing its predecessors' changes separately.
pub(crate) fn current_member() -> Option<([u8; 32], u64)> {
    MEMBER.with(Cell::get)
}

type DeferredCheck = Box<dyn Fn(&Doc) -> Result<(), crate::Refusal>>;

thread_local! {
    /// The record checks deferred to the end of the group applying on this
    /// thread, by what they check; `None` outside a group.
    static DEFERRED: std::cell::RefCell<Option<Vec<(String, DeferredCheck)>>> =
        const { std::cell::RefCell::new(None) };
}

/// Run a record's `#[model(check)]` now, or, inside a group, once at its
/// end: a group valid as a whole may pass through a state that is not (two
/// dangling references cleared one after the other). `key` names what is
/// checked, so it runs once however many members touched it.
#[doc(hidden)]
pub fn check_or_defer(
    key: String,
    doc: &Doc,
    check: impl Fn(&Doc) -> Result<(), crate::Refusal> + 'static,
) -> Result<(), crate::Refusal> {
    let grouping = DEFERRED.with(|deferred| deferred.borrow().is_some());
    if !grouping {
        return check(doc);
    }
    DEFERRED.with(|deferred| {
        if let Some(checks) = deferred.borrow_mut().as_mut()
            && !checks.iter().any(|(existing, _)| *existing == key)
        {
            checks.push((key, Box::new(check)));
        }
    });
    Ok(())
}

/// Whether a group is applying on this thread: record checks wait for its
/// end.
pub(crate) fn grouping() -> bool {
    DEFERRED.with(|deferred| deferred.borrow().is_some())
}

/// Runs the checks deferred in a group when the outermost group ends.
struct Deferring(bool);

impl Deferring {
    fn begin() -> Self {
        let outermost = DEFERRED.with(|deferred| {
            let mut deferred = deferred.borrow_mut();
            if deferred.is_some() {
                return false;
            }
            *deferred = Some(Vec::new());
            true
        });
        if outermost {
            crate::action::hold_records();
        }
        Self(outermost)
    }

    /// The records the group held, written once, then the deferred checks, run once on the
    /// group's result.
    fn finish(&self, doc: &mut Doc) -> Result<(), ActionError> {
        if !self.0 {
            return Ok(());
        }
        crate::action::write_held(doc)?;
        let checks = DEFERRED.with(|deferred| deferred.borrow_mut().take().unwrap_or_default());
        for (_, check) in checks {
            check(doc).map_err(ActionError::from)?;
        }
        Ok(())
    }
}

impl Drop for Deferring {
    fn drop(&mut self) {
        if self.0 {
            DEFERRED.with(|deferred| deferred.borrow_mut().take());
            crate::action::drop_held();
        }
    }
}

/// Restores the enclosing member (for a group applied inside a group) even
/// when a member unwinds.
struct MemberScope(Option<([u8; 32], u64)>);

impl Drop for MemberScope {
    fn drop(&mut self) {
        MEMBER.with(|member| member.set(self.0));
    }
}

impl<A> ActionGroup<A>
where
    A: tilo_actions::Action,
{
    /// The members, of whichever type.
    fn members(&self) -> Vec<&dyn tilo_actions::Action> {
        let mut members: Vec<&dyn tilo_actions::Action> = Vec::with_capacity(self.actions.len());
        for action in &self.actions {
            members.push(action);
        }
        members
    }
}

impl<A> tilo_actions::Action for ActionGroup<A>
where
    A: tilo_actions::Action + Serialize + serde::de::DeserializeOwned,
{
    fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
        let payload = serde_json::to_vec(&self.actions).map_err(ActionError::Encode)?;
        // A member that names another's item is decoded as it applies; one
        // that does not is applied as it was built, as every bulk call's
        // members are.
        if !payload.windows(6).any(|window| window == b"$made:") {
            return apply_prepared(doc, &payload, &self.members());
        }
        apply_encoded(doc, &payload, &|doc, member| {
            serde_json::from_value::<A>(member)
                .map_err(ActionError::Encode)?
                .apply(doc)
        })
    }

    /// A group is as consequential as its most consequential member: one
    /// deletion in a gesture makes the gesture ask for confirmation.
    fn risk(&self) -> RiskLevel {
        group_risk(self.members().into_iter().map(tilo_actions::Action::risk))
    }

    /// A gesture records each of its members, and the item they share.
    fn describe(&self, doc: &Doc) -> Option<tilo_actions::Described> {
        describe_members(doc, &self.members(), &|index| {
            crate::__private::json_via_bytes(self.actions.get(index)?).ok()
        })
    }

    /// The first item a member made, which the members' descriptions read
    /// before they applied could not name.
    fn made(&self, doc: &Doc) -> Option<tilo_actions::ActionItem> {
        self.members()
            .into_iter()
            .find_map(|member| member.made(doc))
    }

    fn locus(&self) -> ExecutionLocus {
        self.actions
            .first()
            .map_or(ExecutionLocus::ClientLocal, tilo_actions::Action::locus)
    }

    /// A gesture is someone's step when any member is: one content change
    /// makes it content. Otherwise it is external when any member is, and
    /// housekeeping when every member is.
    fn change_kind(&self) -> tilo_actions::ChangeKind {
        group_change_kind(&self.members())
    }

    /// A gesture that records a received message among others still
    /// records one.
    fn incoming_message(&self) -> bool {
        self.actions
            .iter()
            .any(tilo_actions::Action::incoming_message)
    }

    /// Undo cannot take a gesture back when it cannot take back a member.
    fn irreversible(&self) -> bool {
        self.actions.iter().any(tilo_actions::Action::irreversible)
    }
}

/// Apply `members`, a group encoded as `payload`, in order as one: every
/// member as it was built, with no reference to fill.
fn apply_prepared(
    doc: &mut Doc,
    payload: &[u8],
    members: &[&dyn tilo_actions::Action],
) -> Result<(), ActionError> {
    let seed = crate::action::seed(doc, b"tilo-resource/group-seed/v1", payload);
    if current_member().is_none() {
        crate::action::start_minting();
    }
    let deferring = Deferring::begin();
    {
        let _restore = MemberScope(current_member());
        let mut position = 0_u64;
        for action in members {
            MEMBER.with(|member| member.set(Some((seed, position))));
            action.apply(doc)?;
            position = position.saturating_add(1);
        }
    }
    deferring.finish(doc)
}

/// Apply the members `payload` encodes, in order as one, each filled with the
/// ids the members before it made: a member names an item an earlier one
/// creates with a [`MADE`](tilo_actions::params::MADE) reference, and that
/// member's id is known only as the group applies. The payload keeps the
/// reference, so a replica fills it with the same id.
fn apply_encoded(
    doc: &mut Doc,
    payload: &[u8],
    apply_member: &dyn Fn(&mut Doc, serde_json::Value) -> Result<(), ActionError>,
) -> Result<(), ActionError> {
    let members: Vec<serde_json::Value> =
        serde_json::from_slice(payload).map_err(ActionError::Encode)?;
    let seed = crate::action::seed(doc, b"tilo-resource/group-seed/v1", payload);
    if current_member().is_none() {
        crate::action::start_minting();
    }
    let deferring = Deferring::begin();
    let mut made: Vec<Vec<String>> = Vec::with_capacity(members.len());
    {
        let _restore = MemberScope(current_member());
        for (position, member) in members.into_iter().enumerate() {
            let position = u64::try_from(position).unwrap_or(u64::MAX);
            MEMBER.with(|member| member.set(Some((seed, position))));
            let mut member = member;
            fill_made(&mut member, &made)?;
            apply_member(doc, member)?;
            made.push(crate::action::take_minted());
        }
    }
    deferring.finish(doc)?;
    // What the members minted together, in the order they were made, put down
    // again: the one who invoked the group learns every item it made, as from
    // one action.
    for member in &made {
        for id in member {
            crate::action::note_minted(id);
        }
    }
    Ok(())
}

/// Fill each [`MADE`](tilo_actions::params::MADE) marker in `member` with the
/// id it names among those `made` minted, in order.
fn fill_made(value: &mut serde_json::Value, made: &[Vec<String>]) -> Result<(), ActionError> {
    match value {
        serde_json::Value::String(text) => {
            if let Some((member, item)) = tilo_actions::params::made_of_marker(text) {
                let id = made
                    .get(member)
                    .and_then(|made| made.get(item))
                    .ok_or_else(|| {
                        ActionError::Refused(format!(
                            "the group has made no item {item} at member {member} to name"
                        ))
                    })?;
                text.clone_from(id);
            }
            Ok(())
        }
        serde_json::Value::Array(items) => {
            for item in items {
                fill_made(item, made)?;
            }
            Ok(())
        }
        serde_json::Value::Object(fields) => {
            for field in fields.values_mut() {
                fill_made(field, made)?;
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

/// What a group of `members` did: each member's description, or its JSON
/// form (`value(index)`) where it has none, and the item they share.
fn describe_members(
    doc: &Doc,
    members: &[&dyn tilo_actions::Action],
    value: &dyn Fn(usize) -> Option<serde_json::Value>,
) -> Option<tilo_actions::Described> {
    let mut described: Vec<tilo_actions::Described> = Vec::with_capacity(members.len());
    for (index, action) in members.iter().enumerate() {
        let member = match action.describe(doc) {
            Some(member) => member,
            None => tilo_actions::Described::from_value("", &value(index)?, None)?,
        };
        described.push(member);
    }
    let item = described.first().and_then(|first| first.item.clone());
    let shared = described.iter().all(|member| member.item == item);
    Some(tilo_actions::Described {
        what: tilo_actions::Did::group(described.into_iter().map(|member| member.what)),
        item: if shared { item } else { None },
    })
}

fn group_change_kind(members: &[&dyn tilo_actions::Action]) -> tilo_actions::ChangeKind {
    use tilo_actions::ChangeKind;
    let mut kinds = members.iter().map(|member| member.change_kind());
    let Some(first) = kinds.next() else {
        return ChangeKind::Content;
    };
    kinds.fold(first, |group, member| match (group, member) {
        (ChangeKind::Content, _) | (_, ChangeKind::Content) => ChangeKind::Content,
        (ChangeKind::External, _) | (_, ChangeKind::External) => ChangeKind::External,
        (ChangeKind::Housekeeping, ChangeKind::Housekeeping) => ChangeKind::Housekeeping,
    })
}

/// How consequential a group of actions as consequential as `risks` is: as
/// its most consequential member. One deletion in a gesture makes the
/// gesture ask for confirmation.
pub(crate) fn group_risk(risks: impl IntoIterator<Item = RiskLevel>) -> RiskLevel {
    let mut risk = RiskLevel::None;
    for member in risks {
        match member {
            consequential if consequential.requires_confirmation() => return consequential,
            RiskLevel::Low => risk = RiskLevel::Low,
            _ => {}
        }
    }
    risk
}

/// The registry type id groups of `R`'s actions are replayed under.
pub fn group_type<R: Resource>() -> String {
    group_type_of(R::ACTION_TYPE)
}

/// The registry type id groups of the actions of the type `action_type`
/// are replayed under.
pub(crate) fn group_type_of(action_type: &str) -> String {
    format!("{action_type}{}", tilo_actions::group_form::GROUP_SUFFIX)
}

/// Register everything a replica of `R` replays: the resource's own actions
/// ([`Resource::register`]) and groups of them.
pub fn register<R: Resource>(registry: &mut ActionRegistry) {
    R::register(registry);
    registry.register::<ActionGroup<R::Action>>(group_type::<R>());
}

/// Build the group [`GROUP`] invocations describe: each member is built from
/// its own declaration exactly as if it were invoked alone.
pub fn build_group<R: Resource>(
    arguments: &serde_json::Map<String, serde_json::Value>,
    now_ms: i64,
) -> Result<ActionGroup<R::Action>, String> {
    let members = build_members(vocabulary::<R>(), arguments, now_ms)?;
    let mut actions = Vec::with_capacity(members.len());
    for member in members {
        match member.into_action::<R>() {
            Some(action) => actions.push(action),
            None => return Err(format!("not an action of a {}", R::LABEL)),
        }
    }
    Ok(ActionGroup { actions })
}

pub(crate) fn build_members(
    vocabulary: &Vocabulary,
    arguments: &serde_json::Map<String, serde_json::Value>,
    now_ms: i64,
) -> Result<Vec<Built>, String> {
    let Some(serde_json::Value::Array(members)) = arguments.get(GROUP_PARAM) else {
        return Err(format!("`{GROUP_PARAM}` must be an array of invocations"));
    };
    let mut built = Vec::with_capacity(members.len());
    for (index, member) in members.iter().enumerate() {
        let Some(id) = member.get("action").and_then(serde_json::Value::as_str) else {
            return Err(format!("member {index} names no `action`"));
        };
        if id == GROUP {
            return Err(format!("member {index}: a group member cannot be a group"));
        }
        let args = match member.get("args") {
            None | Some(serde_json::Value::Null) => serde_json::Map::new(),
            Some(serde_json::Value::Object(args)) => args.clone(),
            Some(_) => {
                return Err(format!(
                    "member {index}: the arguments of `{id}` must be an object"
                ));
            }
        };
        match crate::resource::build_action_of(vocabulary, id, &args, now_ms) {
            Ok(action) => built.push(action),
            Err(reason) => return Err(format!("member {index} ({id}): {reason}")),
        }
    }
    Ok(built)
}