tilo_actions/stamp.rs
1//! What a resource store's change names in its message: the action that made it, which every
2//! holder judges the change against, and which history and undo group it by.
3
4use serde::{Deserialize, Serialize};
5
6/// The action a change was made by, and the membership its author saw: what a holder judges
7/// the change against. It travels in the change itself.
8#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
9pub struct Stamp {
10 /// The verb invoked.
11 pub verb: String,
12 /// The action invoked, where [`Self::verb`] ran as a step of it: the action at the top of
13 /// the calls the invocation made (Chat's report, whose message its `send` writes). A trigger
14 /// naming the action invoked fires on what its steps wrote. Empty where the verb is the
15 /// action invoked; a change written before it was kept reads as empty.
16 #[serde(default, skip_serializing_if = "String::is_empty")]
17 pub invoked: String,
18 /// Who invoked it: a person, or an agent acting for one, as [`Stamp::by`] writes the actor.
19 /// History names the change's author by it, so it is the actor every reader parses back
20 /// ([`Stamp::invoked_by`]), never a bare id.
21 pub invoker: String,
22 /// The person the invoker acted for, when someone acted for a person and the invoker is not
23 /// one (an agent): the records it makes are that person's, so a record under
24 /// `readers: author` is read by them and their devices, as one made by them directly is.
25 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub acted_for: Option<String>,
27 /// The invocation: every change it made, in every document, names it, so history and undo
28 /// take them as one step.
29 pub invocation: String,
30 /// The heads of the membership the author saw when it wrote the change, as the membership
31 /// names them: who may do what is judged as of there, not as of the receiver's now.
32 pub membership: Vec<String>,
33 /// The invocation this one takes back, when it is an undo: it names that invocation's verb.
34 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub undoes: Option<String>,
36 /// When it was invoked, ISO-8601 UTC, recorded like an argument so every holder reads the
37 /// same; empty where the invoker named no time.
38 #[serde(default, skip_serializing_if = "String::is_empty")]
39 pub at: String,
40 /// The resource the invocation was made from, when it was made from one (a task made from a
41 /// message): what the resources it made read as made from, on every holder.
42 #[serde(default, skip_serializing_if = "Option::is_none")]
43 pub from: Option<Origin>,
44 /// The work the invocation is one step of, when it is one of several taken together (an
45 /// agent's session): what a review of that work lists, and what reading its changes groups.
46 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub group: Option<Group>,
48 /// Who proposed the invocation, when the invoker accepted someone's suggestion: the change
49 /// is the invoker's, and it says who proposed it.
50 #[serde(default, skip_serializing_if = "String::is_empty")]
51 pub suggested_by: String,
52 /// The arguments the action was invoked with, in the order it declares them, as the runtime
53 /// recorded them: what a program following the change reads as the verb's arguments. Empty
54 /// where the change names no arguments of its own (an edit, an undo).
55 #[serde(default, skip_serializing_if = "Vec::is_empty")]
56 pub args: Vec<serde_json::Value>,
57 /// When the writer wrote it, by its clock, as a number that orders: the order a resource's
58 /// versions read in across the documents it is kept in, and what tells two writes of one
59 /// invocation apart. Zero where the writer kept none.
60 #[serde(default, skip_serializing_if = "is_zero")]
61 pub moment: u64,
62 /// The invocation as its caller signed it, when a host ran the action for someone who asked
63 /// it under their own key: the device that wrote the change signs it as its own, and this
64 /// says who asked, for what, with what arguments. A holder checks it against the person's
65 /// root ([`crate::remote::SignedCall`]); the host never makes one up.
66 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub signed: Option<Box<crate::remote::SignedCall>>,
68 /// The device that wrote the change, its key in hex: where a resource the change made live
69 /// is live (`tilo_resource_store::Store::live`). Empty where the writer named none.
70 #[serde(default, skip_serializing_if = "String::is_empty")]
71 pub device: String,
72 /// What that device calls itself ("Framework", "Phone"), as its certificate names it: a row
73 /// live on it says where it plays. Empty where the writer named none.
74 #[serde(default, skip_serializing_if = "String::is_empty")]
75 pub device_name: String,
76 /// What the change did, as history tells it: the item it addressed, the field it edited, the
77 /// gesture it is one keystroke of, the purpose its invoker gave. `None` where the writer said
78 /// no more than the verb.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub context: Option<Box<crate::ActionContext>>,
81}
82
83#[allow(
84 clippy::trivially_copy_pass_by_ref,
85 reason = "serde passes the field by reference"
86)]
87const fn is_zero(moment: &u64) -> bool {
88 *moment == 0
89}
90
91/// A resource an invocation was made from: its kind and id.
92#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
93pub struct Origin {
94 pub kind: String,
95 pub id: String,
96}
97
98/// Several invocations taken together, as one piece of work: its id, and what it was called
99/// when it ran.
100#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
101pub struct Group {
102 pub id: String,
103 #[serde(default, skip_serializing_if = "String::is_empty")]
104 pub label: String,
105}
106
107/// The form a change's label was written in ([`Stamp::read`]).
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub enum Label {
110 /// An action's entry, written whole.
111 Entry,
112 /// One keystroke of a gesture, written as what changed since its writer's last whole entry.
113 Continuation,
114 /// A change the framework wrote rather than an app's action.
115 Framework(crate::FrameworkChange),
116 /// A resource store's stamp.
117 Stamp,
118}
119
120impl Label {
121 /// The form `message` was written in, told by how it starts, without reading what it says:
122 /// what a reader that only sorts changes by form asks. `None` for a message in no form a
123 /// label is written in; a stamp's is not checked here ([`Stamp::read`] reads it).
124 #[must_use]
125 pub fn of(message: &str) -> Option<Self> {
126 if message.starts_with(crate::context::CHANGE_MESSAGE_PREFIX) {
127 return Some(Self::Entry);
128 }
129 if message.starts_with(crate::context::CONTINUATION_PREFIX) {
130 return Some(Self::Continuation);
131 }
132 if let Some(change) = crate::FrameworkChange::from_change_message(message) {
133 return Some(Self::Framework(change));
134 }
135 message.starts_with('{').then_some(Self::Stamp)
136 }
137}
138
139/// The verb a change whose entry says it did `what` names: its action's, the content edit
140/// ([`Stamp::TYPE_VERB`]) for an edit or a change that names nothing finer, the one verb every
141/// member of a group shares, and a history step's. Empty where no single declared verb names it.
142fn verb_of(what: Option<&crate::Did>) -> String {
143 use crate::{Did, HistoryOp};
144 match what {
145 None | Some(Did::Edit(_)) => Stamp::TYPE_VERB.to_owned(),
146 Some(Did::Verb(verb)) => verb.action.action.clone(),
147 Some(Did::Group(group)) => {
148 let members = if group.distinct.is_empty() {
149 &group.members
150 } else {
151 &group.distinct
152 };
153 let mut verbs = members.iter().map(|member| verb_of(Some(member)));
154 let first = verbs.next().unwrap_or_default();
155 if verbs.all(|verb| verb == first) {
156 first
157 } else {
158 String::new()
159 }
160 }
161 Some(Did::History(step)) => match step.op {
162 HistoryOp::Checkpoint { .. } => Stamp::CHECKPOINT_VERB.to_owned(),
163 HistoryOp::Migrate { .. } => Stamp::MIGRATE_VERB.to_owned(),
164 HistoryOp::Undo | HistoryOp::Redo | HistoryOp::Restore => String::new(),
165 },
166 }
167}
168
169impl Stamp {
170 /// The verb of a change an app's outside origin wrote (`$origin`): what its service said,
171 /// taken into the resources of the types it keeps. A store keeps no facets, so a change
172 /// stamped with it is how a received message reaches a trigger.
173 pub const ORIGIN_VERB: &str = "$origin";
174
175 /// The verb of a change that names the version it stands at, with the name as its one
176 /// argument: a change with no operations every schema declares.
177 pub const CHECKPOINT_VERB: &str = "checkpoint";
178
179 /// The text a stamp names `actor` by as its invoker.
180 #[must_use]
181 pub fn by(actor: &tilo_action_policy::Actor) -> String {
182 serde_json::to_string(actor).unwrap_or_default()
183 }
184
185 /// The message a change carries it as.
186 #[must_use]
187 pub fn message(&self) -> String {
188 serde_json::to_string(self).unwrap_or_default()
189 }
190
191 /// The verb of a change that edits a record's content with no finer action naming it (a
192 /// window's typing, a group of field edits): each kind whose content is written so declares
193 /// it on its surface.
194 pub const TYPE_VERB: &str = "type";
195
196 /// The verb of a change that brings a record to a storage version of its model: the step its
197 /// kind and id derive, or the app's rewrite that follows it. Every store has it, and no
198 /// surface declares it.
199 pub const MIGRATE_VERB: &str = "migrate";
200
201 /// The verb of a change that founds a record in a branch of its workspace: the fork's
202 /// founding step on the history the branch copies, under the verb every store has and no app
203 /// declares.
204 pub const BRANCH_VERB: &str = "branch";
205
206 /// The verb of a change that takes back a step (`$undo`), and of one that brings a version
207 /// back (`$restore`): the platform's own writes through history, under verbs whose `$` no
208 /// app declares.
209 pub const UNDO_VERB: &str = "$undo";
210 pub const RESTORE_VERB: &str = "$restore";
211
212 /// The verbs the platform writes under, which no app declares: a call a device carries out
213 /// (`$invocation`), a block that settles one (`$settle-block`), and a step taken back or
214 /// brought back ([`Self::UNDO_VERB`], [`Self::RESTORE_VERB`]). A store's schema declares them,
215 /// and under them a change may write any field or content of a declared kind, so a surface an
216 /// app ships may declare none of them.
217 pub const PLATFORM_VERBS: [&str; 4] = [
218 "$invocation",
219 "$settle-block",
220 Self::UNDO_VERB,
221 Self::RESTORE_VERB,
222 ];
223
224 /// The verbs no surface an app ships may declare, whether or not a schema admits them yet:
225 /// the platform's own ([`Self::PLATFORM_VERBS`]), which take a step back or bring a version
226 /// back too ([`Self::UNDO_VERB`], [`Self::RESTORE_VERB`]), and the migration
227 /// ([`Self::MIGRATE_VERB`]), which a store admits by its derived step or by who may write the
228 /// record, never by an app's write set. The `$` names are the platform's, so an app's own
229 /// `undo` or `restore` action is a different verb, judged by its own surface's write set.
230 pub const RESERVED_VERBS: [&str; 5] = [
231 "$invocation",
232 "$settle-block",
233 Self::UNDO_VERB,
234 Self::RESTORE_VERB,
235 Self::MIGRATE_VERB,
236 ];
237
238 /// The stamp a change's message `message` names; `None` for one that names none.
239 #[must_use]
240 pub fn of_message(message: &str) -> Option<Self> {
241 Self::read(message).map(|(_, stamp)| stamp)
242 }
243
244 /// The one reader of a change's label: what `message` names, in whichever form it was
245 /// written ([`Label`]), as a stamp. An action's entry names its context, and its verb is the
246 /// action's; a framework change and a continuation name their verb alone. A verb no
247 /// declared one could name (a group of several actions, a step through history) reads as
248 /// empty, which no surface declares.
249 #[must_use]
250 pub fn read(message: &str) -> Option<(Label, Self)> {
251 if let Some(context) = crate::context::entry_of_message(message) {
252 return Some((Label::Entry, Self::of_context(context)));
253 }
254 Self::read_unentered(message)
255 }
256
257 /// [`Self::read`], of an entry only what it says of who made the change and in which step
258 /// ([`crate::ActionContext::head_of_change_message`]).
259 #[must_use]
260 pub fn read_head(message: &str) -> Option<(Label, Self)> {
261 if let Some(context) = crate::context::entry_head_of_message(message) {
262 return Some((Label::Entry, Self::of_context(context)));
263 }
264 Self::read_unentered(message)
265 }
266
267 /// What a message that carries no whole entry names.
268 fn read_unentered(message: &str) -> Option<(Label, Self)> {
269 use crate::context::ContinuedAction;
270 if let Some(continued) = ContinuedAction::of_message(message) {
271 let verb = match continued {
272 ContinuedAction::Edit { .. } => Self::TYPE_VERB.to_owned(),
273 ContinuedAction::Verb { action, .. } => action.action,
274 };
275 let invoker = ContinuedAction::invoker_of_message(message);
276 return Some((
277 Label::Continuation,
278 Self {
279 verb,
280 invoker: invoker
281 .as_ref()
282 .map(|acting| Self::by(&acting.by))
283 .unwrap_or_default(),
284 ..Self::default()
285 },
286 ));
287 }
288 if let Some(change) = crate::FrameworkChange::from_change_message(message) {
289 let verb = match change {
290 crate::FrameworkChange::Native => Self::TYPE_VERB,
291 crate::FrameworkChange::Run => Self::CHECKPOINT_VERB,
292 crate::FrameworkChange::Migrate => Self::MIGRATE_VERB,
293 crate::FrameworkChange::Genesis
294 | crate::FrameworkChange::Structure
295 | crate::FrameworkChange::Transfer
296 | crate::FrameworkChange::Upgrade => "",
297 };
298 return Some((
299 Label::Framework(change),
300 Self {
301 verb: verb.to_owned(),
302 ..Self::default()
303 },
304 ));
305 }
306 serde_json::from_str(message)
307 .ok()
308 .map(|stamp| (Label::Stamp, stamp))
309 }
310
311 /// The stamp an action's entry `context` stands for: the action's verb, who invoked it and
312 /// for whom, its invocation, and the context whole.
313 fn of_context(context: crate::ActionContext) -> Self {
314 let acting = context.invoker.as_ref().map(|invoker| &invoker.acting);
315 Self {
316 verb: verb_of(context.what.as_ref()),
317 invoker: acting
318 .map(|acting| Self::by(&acting.by))
319 .unwrap_or_default(),
320 acted_for: acting
321 .and_then(|acting| acting.acted_for.first())
322 .and_then(|person| match &person.by {
323 tilo_action_policy::Actor::Member(member) => member.person_id(),
324 _ => None,
325 })
326 .map(str::to_owned),
327 invocation: context
328 .source_invocation
329 .as_ref()
330 .map(ToString::to_string)
331 .unwrap_or_default(),
332 signed: context.signed.clone(),
333 context: Some(Box::new(context)),
334 ..Self::default()
335 }
336 }
337
338 /// Who invoked it: the actor the writer named, or the person the workspace's resource route
339 /// stamped on a person's own write (their person id alone). Nobody for a stamp naming
340 /// neither.
341 #[must_use]
342 pub fn invoked_by(&self) -> Option<tilo_action_policy::Actor> {
343 // An empty invoker names nobody: it must not read as a person with no id.
344 if self.invoker.is_empty() {
345 return None;
346 }
347 if let Ok(actor) = tilo_failure::ignored!(
348 "a stamp the route wrote holds a person id, which is read next",
349 serde_json::from_str::<tilo_action_policy::Actor>(&self.invoker)
350 ) {
351 return Some(actor);
352 }
353 tilo_failure::ignored!(
354 "a stamp naming neither an actor nor a person names nobody",
355 tilo_action_policy::PersonId::parse(&self.invoker)
356 )
357 .ok()
358 .map(|person| {
359 tilo_action_policy::Actor::Member(tilo_action_policy::MemberId::person(person))
360 })
361 }
362
363 /// What the change did, as history reads it: the context its writer gave, with who invoked
364 /// it, the work it is a step of, its invocation and, for a step through history itself (an
365 /// undo, a checkpoint), that step, from the stamp where the context left them out.
366 #[must_use]
367 pub fn action_context(&self) -> crate::ActionContext {
368 let mut context = self.context.as_deref().cloned().unwrap_or_default();
369 if context.invoker.is_none()
370 && let Some(by) = self.invoked_by()
371 {
372 // How an agent acted (handed its session by its person's device, or under a key of its
373 // own) is what its writer recorded in the context: a stamp that records none names an
374 // agent with a key of its own, which shows the call it signed.
375 let acting = tilo_action_policy::Acting {
376 by,
377 app: None,
378 agent_session: None,
379 cause: None,
380 foreign_device: false,
381 handed: false,
382 acted_for: self
383 .acted_for
384 .iter()
385 .filter_map(|person| tilo_action_policy::PersonId::parse(person).ok())
386 .map(tilo_action_policy::Acting::person)
387 .collect(),
388 };
389 context.invoker = Some(crate::ActionInvoker::admitted(&acting));
390 }
391 if context.group.is_none()
392 && let Some(group) = &self.group
393 {
394 context.group = Some(crate::WorkGroup {
395 id: group.id.clone(),
396 label: (!group.label.is_empty()).then(|| group.label.clone()),
397 kind: crate::context::AGENT_SESSION_GROUP.to_owned(),
398 declared_id: None,
399 session: None,
400 });
401 }
402 if context.source_invocation.is_none() {
403 context.source_invocation = self.invocation.parse().ok();
404 }
405 // A store write keeps the call its caller signed in its stamp: the change's history
406 // entry names it, so every holder checks that caller asked for it, and with which key.
407 if context.signed.is_none() {
408 context.signed.clone_from(&self.signed);
409 }
410 if context.what.is_none() {
411 let op = match (self.verb.as_str(), &self.undoes) {
412 (Self::CHECKPOINT_VERB, _) => Some(crate::HistoryOp::Checkpoint {
413 name: self
414 .args
415 .first()
416 .and_then(serde_json::Value::as_str)
417 .unwrap_or_default()
418 .to_owned(),
419 }),
420 (_, Some(_)) => Some(crate::HistoryOp::Undo),
421 _ => None,
422 };
423 context.what = op.map(|op| {
424 crate::Did::History(crate::entry::HistoryStep {
425 op,
426 steps: 1,
427 of: None,
428 undoes: self.undoes.clone(),
429 verb: if self.undoes.is_some() {
430 self.verb.clone()
431 } else {
432 String::new()
433 },
434 })
435 });
436 }
437 context
438 }
439
440 /// The version a migration change brings its record to, and whether it is a rewrite by
441 /// one who may write the record rather than the step every holder derives alike; `None`
442 /// for any other change.
443 #[must_use]
444 pub fn migration(&self) -> Option<(u32, bool)> {
445 match &self.context.as_deref()?.what {
446 Some(crate::Did::History(step)) => match step.op {
447 crate::HistoryOp::Migrate { to, rewrite } => Some((to, rewrite)),
448 _ => None,
449 },
450 _ => None,
451 }
452 }
453
454 /// The stamp `change` carries; `None` for a change that carries none.
455 #[must_use]
456 pub fn of(change: &automerge::Change) -> Option<Self> {
457 Self::of_message(change.message()?)
458 }
459}