Skip to main content

tilo_actions/
entry.rs

1//! What a committed action did, as data.
2//!
3//! Every change an action commits carries a history entry
4//! ([`crate::ActionContext`]): who acted, for whom, on which item and what
5//! they did. "What they did" is a [`Did`]: a field edit with its path and,
6//! for scalars, the value before and after; a verb with its [`ActionKey`]
7//! and scalar arguments; a group of those; or a history step (undo, redo,
8//! restore, checkpoint). No sentence is stored. Readers render one in their
9//! own language (`tilo-history`), and agents, scripts and logs read the data.
10
11use std::collections::BTreeMap;
12
13use serde::{Deserialize, Serialize};
14
15use crate::key::ActionKey;
16
17/// Longest text kept for one scalar value, in characters.
18pub const MAX_SCALAR_CHARS: usize = 80;
19/// Most arguments kept for one verb.
20pub const MAX_VERB_ARGS: usize = 8;
21/// Most members of a group kept by value; [`GroupOf::count`] keeps the total.
22pub const MAX_GROUP_MEMBERS: usize = 8;
23
24/// What an action did.
25#[derive(Debug, PartialEq, Eq, Serialize)]
26#[serde(remote = "Self", tag = "did", rename_all = "kebab-case")]
27pub enum Did {
28    Edit(FieldEdit),
29    Verb(VerbCall),
30    Group(GroupOf),
31    History(HistoryStep),
32}
33
34// Written through its JSON text: the derived writer is compiled once, for
35// JSON bytes, and every serializer an entry goes to (bytes, a value, a size
36// count) takes that text as it is, rather than holding a copy of the derived
37// writer of its own. The bytes are the derive's, tag first. Like its reading,
38// this is for JSON only (see `read_through_json_value!`).
39impl serde::Serialize for Did {
40    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
41        self.to_json_text()
42            .map_err(serde::ser::Error::custom)?
43            .serialize(serializer)
44    }
45}
46
47impl<'de> serde::Deserialize<'de> for Did {
48    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
49        let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
50        Self::from_json_value(value).map_err(serde::de::Error::custom)
51    }
52}
53
54impl Did {
55    /// Its JSON text, as the derived writer writes it.
56    #[inline(never)]
57    fn to_json_text(&self) -> Result<Box<serde_json::value::RawValue>, serde_json::Error> {
58        /// The derived writer, as a value to serialize.
59        struct Derived<'a>(&'a Did);
60        impl serde::Serialize for Derived<'_> {
61            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
62                Did::serialize(self.0, serializer)
63            }
64        }
65        serde_json::value::to_raw_value(&Derived(self))
66    }
67
68    /// Read by its `did` tag, each variant's fields straight from the
69    /// object: no buffered copy of the entry.
70    #[inline(never)]
71    fn from_json_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
72        use serde::de::Error;
73        let serde_json::Value::Object(mut fields) = value else {
74            return Err(serde_json::Error::custom("an entry is an object"));
75        };
76        let tag = match fields.remove("did") {
77            Some(serde_json::Value::String(tag)) => tag,
78            Some(_) => return Err(serde_json::Error::custom("`did` is a string")),
79            None => return Err(serde_json::Error::missing_field("did")),
80        };
81        let fields = serde_json::Value::Object(fields);
82        match tag.as_str() {
83            "edit" => serde_json::from_value(fields).map(Self::Edit),
84            "verb" => serde_json::from_value(fields).map(Self::Verb),
85            "group" => serde_json::from_value(fields).map(Self::Group),
86            "history" => serde_json::from_value(fields).map(Self::History),
87            other => Err(serde_json::Error::unknown_variant(
88                other,
89                &["edit", "verb", "group", "history"],
90            )),
91        }
92    }
93}
94
95// Written out rather than derived: a derived clone is inlined into every
96// crate that clones an entry, and entries are cloned throughout the toolkit.
97impl Clone for Did {
98    fn clone(&self) -> Self {
99        match self {
100            Self::Edit(edit) => Self::Edit(edit.clone()),
101            Self::Verb(verb) => Self::Verb(verb.clone()),
102            Self::Group(group) => Self::Group(group.clone()),
103            Self::History(step) => Self::History(step.clone()),
104        }
105    }
106}
107
108impl Did {
109    /// A verb with its arguments bounded to plain values.
110    pub fn verb(action: ActionKey, args: impl IntoIterator<Item = (String, Scalar)>) -> Self {
111        Self::Verb(VerbCall::new(action, args))
112    }
113
114    /// A group of `members`, keeping at most [`MAX_GROUP_MEMBERS`] by value
115    /// and every distinct action among them without its values.
116    pub fn group(members: impl IntoIterator<Item = Did>) -> Self {
117        let mut count = 0u32;
118        let mut kept = Vec::new();
119        let mut distinct: Vec<Did> = Vec::new();
120        for member in members {
121            count = count.saturating_add(1);
122            let mut action = member.clone();
123            action.forget_values();
124            if !distinct.contains(&action) {
125                distinct.push(action);
126            }
127            if kept.len() < MAX_GROUP_MEMBERS {
128                kept.push(member);
129            }
130        }
131        Self::Group(GroupOf {
132            members: kept,
133            count,
134            distinct,
135        })
136    }
137
138    /// Drop every value, keeping only which action ran where.
139    fn forget_values(&mut self) {
140        self.forget_args();
141        match self {
142            Self::Edit(edit) => edit.args.clear(),
143            Self::Group(group) => {
144                group.members.iter_mut().for_each(Self::forget_values);
145                group.distinct.iter_mut().for_each(Self::forget_values);
146            }
147            Self::Verb(_) | Self::History(_) => {}
148        }
149    }
150
151    /// Drop every verb argument and field value, keeping what was done and
152    /// where: the form a public audit keeps.
153    pub fn forget_args(&mut self) {
154        match self {
155            Self::Edit(edit) => {
156                edit.old = None;
157                edit.new = None;
158            }
159            Self::Verb(verb) => verb.args.clear(),
160            Self::Group(group) => group.members.iter_mut().for_each(Self::forget_args),
161            Self::History(step) => {
162                if let Some(of) = &mut step.of {
163                    of.what.forget_args();
164                }
165            }
166        }
167    }
168
169    pub fn history(op: HistoryOp, steps: u32, of: Option<Described>) -> Self {
170        Self::History(HistoryStep {
171            op,
172            steps,
173            of: of.map(Box::new),
174            undoes: None,
175            verb: String::new(),
176        })
177    }
178}
179
180#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
181pub struct FieldEdit {
182    /// The model type that owns the field, kebab-case (`snippet`).
183    pub ty: String,
184    /// The field's storage key (`favorite`).
185    pub field: String,
186    /// Where the field is, from the resource's root.
187    #[serde(default, skip_serializing_if = "Vec::is_empty")]
188    pub path: Vec<PathStep>,
189    pub op: EditOp,
190    /// The value before, for a scalar field.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub old: Option<Scalar>,
193    /// The value after, for a scalar field.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub new: Option<Scalar>,
196    /// Plain facts of an edit the field's own type describes (a rich-text
197    /// edit's mark, the words it covered), by name.
198    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
199    pub args: BTreeMap<String, Scalar>,
200}
201
202/// One step of a path from a resource's root to a field.
203#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
204#[serde(rename_all = "kebab-case")]
205pub enum PathStep {
206    Field(String),
207    Item(String),
208    Key(String),
209    Cell(String, String),
210}
211
212/// The operation of a field edit.
213#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
214#[serde(rename_all = "kebab-case")]
215pub enum EditOp {
216    Set,
217    Splice,
218    Replace,
219    Add,
220    Insert,
221    Remove,
222    MoveTo,
223    Mark,
224    SetCell,
225    InsertRow,
226    InsertColumn,
227    RemoveRow,
228    RemoveColumn,
229    /// The owning device recorded how an outbox entry settled (`$state`:
230    /// `done` or `failed`, with `$reason`).
231    Settle,
232    /// A settled outbox entry was forgotten.
233    Forget,
234    /// The actor reacted with an emoji (`new`).
235    React,
236    /// The actor took back their reaction with an emoji (`new`).
237    Unreact,
238}
239
240impl EditOp {
241    /// The name readers pass to messages as `$op`.
242    pub const fn as_str(&self) -> &'static str {
243        match self {
244            Self::Set => "set",
245            Self::Splice => "splice",
246            Self::Replace => "replace",
247            Self::Add => "add",
248            Self::Insert => "insert",
249            Self::Remove => "remove",
250            Self::MoveTo => "move-to",
251            Self::Mark => "mark",
252            Self::SetCell => "set-cell",
253            Self::InsertRow => "insert-row",
254            Self::InsertColumn => "insert-column",
255            Self::RemoveRow => "remove-row",
256            Self::RemoveColumn => "remove-column",
257            Self::Settle => "settle",
258            Self::Forget => "forget",
259            Self::React => "react",
260            Self::Unreact => "unreact",
261        }
262    }
263}
264
265/// A verb and its plain arguments by parameter name.
266#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
267pub struct VerbCall {
268    pub action: ActionKey,
269    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
270    pub args: BTreeMap<String, Scalar>,
271}
272
273impl VerbCall {
274    /// Keeps at most [`MAX_VERB_ARGS`] arguments.
275    pub fn new(action: ActionKey, args: impl IntoIterator<Item = (String, Scalar)>) -> Self {
276        Self {
277            action,
278            args: args.into_iter().take(MAX_VERB_ARGS).collect(),
279        }
280    }
281}
282
283/// Several actions committed as one change.
284#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
285pub struct GroupOf {
286    /// The first [`MAX_GROUP_MEMBERS`] members.
287    pub members: Vec<Did>,
288    pub count: u32,
289    /// Every distinct action among the members, without values, however
290    /// many members there were: what a receiver decides the change by.
291    #[serde(default, skip_serializing_if = "Vec::is_empty")]
292    pub distinct: Vec<Did>,
293}
294
295impl GroupOf {
296    /// The one thing every member did, when they all did the same.
297    pub fn shared(&self) -> Option<&Did> {
298        let first = self.members.first()?;
299        (self.count as usize == self.members.len() && self.members.iter().all(|m| m == first))
300            .then_some(first)
301    }
302}
303
304/// A step through history itself.
305#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
306pub struct HistoryStep {
307    pub op: HistoryOp,
308    /// How many steps it took back or brought back.
309    #[serde(default)]
310    pub steps: u32,
311    /// What it took back or brought back, when it was one step.
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub of: Option<Box<Described>>,
314    /// The invocation it took back or brought back, when it moved one: each change of an undo
315    /// moves one invocation, so whoever admits it reads one invocation per change.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub undoes: Option<String>,
318    /// The verb of that invocation, as it was invoked.
319    #[serde(default, skip_serializing_if = "String::is_empty")]
320    pub verb: String,
321}
322
323#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
324#[serde(rename_all = "kebab-case")]
325pub enum HistoryOp {
326    Undo,
327    Redo,
328    Restore,
329    Checkpoint {
330        name: String,
331    },
332    /// The document was brought to the storage version `to`: the step every holder derives
333    /// alike, or, with `rewrite`, the app's own rewrite of its content for that version, which
334    /// follows the step and is decided as any write of the record's.
335    Migrate {
336        to: u32,
337        #[serde(default)]
338        rewrite: bool,
339    },
340}
341
342/// The item an action addressed, with its label at the time: one line that
343/// names it ([`Described::on`]), never its text.
344#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
345pub struct ActionItem {
346    pub id: String,
347    pub label: String,
348}
349
350/// What an action says about itself before it applies: what it does and to
351/// which item ([`crate::Action::describe`]).
352#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
353pub struct Described {
354    pub what: Did,
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub item: Option<ActionItem>,
357}
358
359impl Described {
360    pub fn new(what: Did) -> Self {
361        Self { what, item: None }
362    }
363
364    /// About the item `id`, named by `label` as one line people read
365    /// ([`one_line`](crate::context::one_line), at most
366    /// [`MAX_LABEL_CHARS`](crate::context::MAX_LABEL_CHARS) characters): an
367    /// entry names its item, it never carries what the item reads. A message
368    /// is labelled by its text, so a label kept whole put the whole reply so
369    /// far into every change that grew it. An item with no name of its own
370    /// is called by its id, which stays whole: a reader takes a label that
371    /// repeats the id for no name.
372    ///
373    /// Only an entry being written passes here. A kept entry is read back as
374    /// it was written, so a change from before this rule keeps its bytes, and
375    /// is verified and undone under them ([`crate::verify_change`]).
376    #[must_use]
377    pub fn on(mut self, id: impl Into<String>, label: impl Into<String>) -> Self {
378        let (id, label) = (id.into(), label.into());
379        let label = if label == id {
380            label
381        } else {
382            crate::context::one_line(&label, crate::context::MAX_LABEL_CHARS).unwrap_or_default()
383        };
384        self.item = Some(ActionItem { id, label });
385        self
386    }
387
388    /// The published action `key` invoked with `encoded`: the verb with the
389    /// plain arguments the encoded value carries. An empty `key.app` is
390    /// filled by the executor from the entry's app.
391    pub fn of_published(encoded: &crate::EncodedAction, key: ActionKey) -> Option<Self> {
392        let value = without_lists(&encoded.payload)?;
393        let args = variant_of(&value).and_then(|(_, fields)| fields);
394        Some(Self::new(Did::verb(key, plain_args(args))))
395    }
396
397    /// What an encoded action says about itself when its type describes
398    /// nothing: the verb its serde variant names, with its plain arguments.
399    /// `app` names the publishing app; without one the action type's stem
400    /// (`notes` of `notes.action`) stands in.
401    pub fn from_encoded(encoded: &crate::EncodedAction, app: Option<&str>) -> Option<Self> {
402        let value = without_lists(&encoded.payload)?;
403        Self::from_value(&encoded.type_id, &value, app)
404    }
405
406    /// [`Self::from_encoded`] for an action value already in JSON.
407    pub fn from_value(type_id: &str, value: &serde_json::Value, app: Option<&str>) -> Option<Self> {
408        let (variant, fields) = variant_of(value)?;
409        let app = app
410            .filter(|app| !app.trim().is_empty())
411            .map_or_else(|| type_stem(type_id), str::to_owned);
412        Some(Self::new(Did::verb(
413            ActionKey::new(app, type_id, kebab(variant)),
414            plain_args(fields),
415        )))
416    }
417}
418
419/// The plain arguments of a variant's fields (an adjacently tagged value's
420/// `args`, else the fields beside an internal `action` tag): its plain
421/// values by name, then the plain values of its nested records as
422/// `record.field`. Text arguments are kept whole ([`Scalar::argument`]):
423/// what a person, a script or an agent passed is what the change says it
424/// did, and a reader that recalls it (a calculation put back, a formula
425/// opened) gets all of it.
426fn plain_args(
427    fields: Option<&serde_json::Map<String, serde_json::Value>>,
428) -> impl Iterator<Item = (String, Scalar)> + '_ {
429    let tagged = fields.is_some_and(|fields| fields.contains_key("action"));
430    let fields = match fields.and_then(|fields| fields.get("args")) {
431        Some(serde_json::Value::Object(args)) if tagged => Some(args),
432        _ => fields,
433    };
434    let own = move || {
435        fields
436            .into_iter()
437            .flat_map(serde_json::Map::iter)
438            .filter(move |(name, _)| !(tagged && name.as_str() == "action"))
439    };
440    let plain = own().filter_map(|(name, value)| Some((name.clone(), Scalar::argument(value)?)));
441    let nested = own().flat_map(|(name, value)| {
442        value
443            .as_object()
444            .into_iter()
445            .flat_map(serde_json::Map::iter)
446            .filter_map(move |(field, value)| {
447                Some((format!("{name}.{field}"), Scalar::argument(value)?))
448            })
449    });
450    plain.chain(nested)
451}
452
453/// The JSON value of `payload` with every list in it read as empty: what an
454/// action is described by, as no list is a plain argument, read without
455/// building the lists an action carries in bulk (the issues of a long list
456/// made in one call).
457fn without_lists(payload: &[u8]) -> Option<serde_json::Value> {
458    use serde::de::{IgnoredAny, MapAccess, SeqAccess, Visitor};
459
460    struct Shallow(serde_json::Value);
461
462    impl<'de> Deserialize<'de> for Shallow {
463        fn deserialize<D: serde::Deserializer<'de>>(from: D) -> Result<Self, D::Error> {
464            from.deserialize_any(ShallowVisitor)
465        }
466    }
467
468    struct ShallowVisitor;
469
470    impl<'de> Visitor<'de> for ShallowVisitor {
471        type Value = Shallow;
472
473        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
474            formatter.write_str("a JSON value")
475        }
476
477        fn visit_bool<E>(self, value: bool) -> Result<Shallow, E> {
478            Ok(Shallow(value.into()))
479        }
480
481        fn visit_i64<E>(self, value: i64) -> Result<Shallow, E> {
482            Ok(Shallow(value.into()))
483        }
484
485        fn visit_u64<E>(self, value: u64) -> Result<Shallow, E> {
486            Ok(Shallow(value.into()))
487        }
488
489        fn visit_f64<E>(self, value: f64) -> Result<Shallow, E> {
490            Ok(Shallow(value.into()))
491        }
492
493        fn visit_str<E>(self, value: &str) -> Result<Shallow, E> {
494            Ok(Shallow(value.into()))
495        }
496
497        fn visit_string<E>(self, value: String) -> Result<Shallow, E> {
498            Ok(Shallow(value.into()))
499        }
500
501        fn visit_unit<E>(self) -> Result<Shallow, E> {
502            Ok(Shallow(serde_json::Value::Null))
503        }
504
505        fn visit_none<E>(self) -> Result<Shallow, E> {
506            Ok(Shallow(serde_json::Value::Null))
507        }
508
509        fn visit_seq<A: SeqAccess<'de>>(self, mut items: A) -> Result<Shallow, A::Error> {
510            while items.next_element::<IgnoredAny>()?.is_some() {}
511            Ok(Shallow(serde_json::Value::Array(Vec::new())))
512        }
513
514        fn visit_map<A: MapAccess<'de>>(self, mut entries: A) -> Result<Shallow, A::Error> {
515            let mut fields = serde_json::Map::new();
516            while let Some((name, Shallow(value))) = entries.next_entry::<String, Shallow>()? {
517                fields.insert(name, value);
518            }
519            Ok(Shallow(serde_json::Value::Object(fields)))
520        }
521    }
522
523    serde_json::from_slice::<Shallow>(payload)
524        .ok()
525        .map(|Shallow(value)| value)
526}
527
528/// The variant name and fields of an externally, adjacently or internally
529/// tagged action value, looking through a stamped `{op, at}` envelope.
530fn variant_of(
531    value: &serde_json::Value,
532) -> Option<(&str, Option<&serde_json::Map<String, serde_json::Value>>)> {
533    match value {
534        serde_json::Value::String(variant) => Some((variant, None)),
535        serde_json::Value::Object(fields) => {
536            if let (Some(op), Some(_)) = (fields.get("op"), fields.get("at"))
537                && fields.len() == 2
538            {
539                return variant_of(op);
540            }
541            if let Some(serde_json::Value::String(variant)) = fields.get("action") {
542                return Some((variant, Some(fields)));
543            }
544            if fields.len() == 1 {
545                let (variant, inner) = fields.iter().next()?;
546                return Some((variant, inner.as_object()));
547            }
548            None
549        }
550        _ => None,
551    }
552}
553
554fn type_stem(type_id: &str) -> String {
555    type_id.split('.').next().unwrap_or(type_id).to_owned()
556}
557
558/// `RemoveMarks`, `remove_marks` and `remove-marks` all become `remove-marks`.
559pub fn kebab(name: &str) -> String {
560    let mut out = String::with_capacity(name.len().saturating_add(4));
561    let mut previous_lower_or_digit = false;
562    for ch in name.chars() {
563        if ch == '_' || ch == '-' || ch == ' ' {
564            if !out.is_empty() && !out.ends_with('-') {
565                out.push('-');
566            }
567            previous_lower_or_digit = false;
568            continue;
569        }
570        if ch.is_uppercase() && previous_lower_or_digit {
571            out.push('-');
572        }
573        previous_lower_or_digit = ch.is_lowercase() || ch.is_ascii_digit();
574        out.extend(ch.to_lowercase());
575    }
576    out
577}
578
579/// One plain value in an entry: a boolean, a number, a short text or an
580/// enum variant. Nested values are never stored.
581#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
582#[serde(transparent)]
583pub struct Scalar(serde_json::Value);
584
585impl Scalar {
586    /// A plain JSON value, text cut to [`MAX_SCALAR_CHARS`]. `None` for
587    /// arrays and objects, and for null.
588    pub fn from_json(value: &serde_json::Value) -> Option<Self> {
589        match value {
590            serde_json::Value::Bool(_) | serde_json::Value::Number(_) => Some(Self(value.clone())),
591            serde_json::Value::String(text) => Some(Self::text(text)),
592            _ => None,
593        }
594    }
595
596    /// A verb's argument as passed: a plain JSON value, text kept whole
597    /// ([`Self::whole_text`]). `None` for arrays and objects, and for null.
598    pub fn argument(value: &serde_json::Value) -> Option<Self> {
599        match value {
600            serde_json::Value::String(text) => Some(Self::whole_text(text)),
601            _ => Self::from_json(value),
602        }
603    }
604
605    /// Text cut to [`MAX_SCALAR_CHARS`], without control characters.
606    pub fn text(text: &str) -> Self {
607        let mut chars = text.chars().filter(|ch| !ch.is_control());
608        let cut: String = chars.by_ref().take(MAX_SCALAR_CHARS).collect();
609        if chars.next().is_some() {
610            Self(serde_json::Value::String(cut + "…"))
611        } else {
612            Self(serde_json::Value::String(cut))
613        }
614    }
615
616    /// A text an edit wrote whole (a formula, a title), kept whole without
617    /// control characters: the change carries the text anyway, and a reader
618    /// elides it where it draws it. Other text is cut ([`Self::text`]).
619    pub fn whole_text(text: &str) -> Self {
620        Self(serde_json::Value::String(
621            text.chars().filter(|ch| !ch.is_control()).collect(),
622        ))
623    }
624
625    /// Any serializable plain value (a bool, a number, a unit enum, a
626    /// string). `None` when it serializes to anything else.
627    pub fn of<T: Serialize + ?Sized>(value: &T) -> Option<Self> {
628        Self::from_json(&serde_json::to_value(value).ok()?)
629    }
630
631    pub fn as_json(&self) -> &serde_json::Value {
632        &self.0
633    }
634
635    pub fn as_bool(&self) -> Option<bool> {
636        self.0.as_bool()
637    }
638
639    pub fn as_str(&self) -> Option<&str> {
640        self.0.as_str()
641    }
642
643    pub fn as_f64(&self) -> Option<f64> {
644        self.0.as_f64()
645    }
646}
647
648impl From<bool> for Scalar {
649    fn from(value: bool) -> Self {
650        Self(serde_json::Value::Bool(value))
651    }
652}
653
654impl From<i64> for Scalar {
655    fn from(value: i64) -> Self {
656        Self(value.into())
657    }
658}
659
660impl From<&str> for Scalar {
661    fn from(value: &str) -> Self {
662        Self::text(value)
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669
670    tilo_test_env::scenario! {
671        fn an_entry_describes_what_an_action_did;
672
673        phase encoded_actions_describe_themselves_as_verbs;
674        {
675            let encoded = crate::EncodedAction {
676                type_id: "notes.action".into(),
677                payload: br#"{"RenameNote":{"id":"n1","title":"Groceries","tags":["a"]}}"#.to_vec(),
678            };
679            let described = Described::from_encoded(&encoded, None).unwrap();
680            let Did::Verb(verb) = &described.what else {
681                panic!("a verb: {described:?}");
682            };
683            assert_eq!(
684                verb.action,
685                ActionKey::new("notes", "notes.action", "rename-note")
686            );
687            assert_eq!(verb.args.get("title"), Some(&Scalar::from("Groceries")));
688            assert!(
689                !verb.args.contains_key("tags"),
690                "nested values are left out"
691            );
692
693            let tagged = crate::EncodedAction {
694                type_id: "canvas.action".into(),
695                payload: br#"{"op":{"action":"draw","args":{"size":3}},"at":17}"#.to_vec(),
696            };
697            let Did::Verb(verb) = Described::from_encoded(&tagged, Some("canvas"))
698                .unwrap()
699                .what
700            else {
701                panic!("a verb");
702            };
703            assert_eq!(verb.action.action, "draw");
704            assert_eq!(verb.args.get("size"), Some(&Scalar::from(3)));
705            assert!(
706                Described::from_encoded(
707                    &crate::EncodedAction {
708                        type_id: "x".into(),
709                        payload: b"7".to_vec()
710                    },
711                    None
712                )
713                .is_none()
714            );
715        }
716
717        phase a_verbs_text_arguments_are_kept_whole;
718        // A long text argument reaches the entry whole, as passed: a formula
719        // an agent added, a calculation the palette committed.
720        {
721            let formula = ["x"; 60].join("+");
722            let tagged = crate::EncodedAction {
723                type_id: "calculator.action".into(),
724                payload: serde_json::to_vec(&serde_json::json!({
725                    "action": "commit-history",
726                    "args": {"expr": formula, "result": "1", "nested": {"note": formula}},
727                }))
728                .unwrap(),
729            };
730            let Did::Verb(verb) = Described::from_encoded(&tagged, Some("calculator"))
731                .unwrap()
732                .what
733            else {
734                panic!("a verb");
735            };
736            assert_eq!(verb.args.get("expr"), Some(&Scalar::whole_text(&formula)));
737            assert_eq!(
738                verb.args.get("nested.note"),
739                Some(&Scalar::whole_text(&formula))
740            );
741        }
742
743        phase values_are_bounded;
744        {
745            let long = "x".repeat(MAX_SCALAR_CHARS * 2);
746            assert_eq!(
747                Scalar::text(&long).as_str().unwrap().chars().count(),
748                MAX_SCALAR_CHARS + 1
749            );
750            assert!(Scalar::from_json(&serde_json::json!({"a": 1})).is_none());
751            assert!(Scalar::from_json(&serde_json::Value::Null).is_none());
752            let args = (0..20).map(|n| (format!("a{n}"), Scalar::from(i64::from(n))));
753            let Did::Verb(verb) = Did::verb(ActionKey::default(), args) else {
754                unreachable!()
755            };
756            assert_eq!(verb.args.len(), MAX_VERB_ARGS);
757            let Did::Group(group) = Did::group((0..20).map(|_| Did::verb(ActionKey::default(), [])))
758            else {
759                unreachable!()
760            };
761            assert_eq!((group.members.len(), group.count), (MAX_GROUP_MEMBERS, 20));
762            assert_eq!(group.distinct.len(), 1, "every member ran the same action");
763            assert!(
764                group.shared().is_none(),
765                "a cut group does not claim one shared step"
766            );
767        }
768
769        phase every_kind_of_entry_reads_back_from_its_json;
770        {
771            let edit = Did::Edit(FieldEdit {
772                ty: "snippet".into(),
773                field: "title".into(),
774                path: vec![
775                    PathStep::Item("s1".into()),
776                    PathStep::Cell("r1".into(), "c2".into()),
777                ],
778                op: EditOp::Set,
779                old: Some(Scalar::text("a")),
780                new: Some(Scalar::text("b")),
781                args: BTreeMap::from([("mark".to_owned(), Scalar::from(true))]),
782            });
783            let verb = Did::verb(ActionKey::default(), [("size".to_owned(), Scalar::from(3))]);
784            let group = Did::group([edit.clone(), verb.clone()]);
785            let history = Did::history(
786                HistoryOp::Checkpoint {
787                    name: "draft".into(),
788                },
789                1,
790                Some(Described::new(group.clone()).on("s1", "First")),
791            );
792            for did in [edit, verb, group, history] {
793                let json = serde_json::to_string(&did).unwrap();
794                assert!(json.starts_with(r#"{"did":"#), "the tag leads: {json}");
795                let read: Did = serde_json::from_str(&json).unwrap();
796                assert_eq!(read, did);
797                assert_eq!(serde_json::to_string(&read).unwrap(), json);
798                let from_value: Did =
799                    serde_json::from_value(serde_json::to_value(&did).unwrap()).unwrap();
800                assert_eq!(from_value, did);
801            }
802            for bad in [r#"{"did":"wave"}"#, r#"{"ty":"x"}"#, r#"{"did":3}"#, "[]"] {
803                assert!(serde_json::from_str::<Did>(bad).is_err(), "{bad}");
804            }
805        }
806
807        phase kebab_names;
808        {
809            assert_eq!(kebab("RemoveMarks"), "remove-marks");
810            assert_eq!(kebab("remove_marks"), "remove-marks");
811            assert_eq!(kebab("Set2Up"), "set2-up");
812        }
813    }
814}