1use automerge::ActorId;
18use automerge::transaction::{CommitOptions, Transactable};
19
20use crate::action::{Action, ActionError, ActionId, Doc, EncodedAction, ExecutionLocus};
21use crate::context::{ActionContext, CONTINUATION_PREFIX, ChangeKind};
22use crate::entry::{Described, Did};
23use crate::envelope::ActionEnvelope;
24use crate::registry::ActionRegistry;
25
26thread_local! {
27 static REPLAYING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
28 static INVOKING: std::cell::RefCell<Option<ActionContext>> = const { std::cell::RefCell::new(None) };
29 static OPEN_STEP: std::cell::Cell<Option<ActionId>> = const { std::cell::Cell::new(None) };
30}
31
32pub fn is_replaying() -> bool {
36 REPLAYING.with(std::cell::Cell::get)
37}
38
39struct ReplayScope(bool);
40
41impl ReplayScope {
42 fn enter() -> Self {
43 Self(REPLAYING.with(|replaying| replaying.replace(true)))
44 }
45}
46
47impl Drop for ReplayScope {
48 fn drop(&mut self) {
49 REPLAYING.with(|replaying| replaying.set(self.0));
50 }
51}
52
53pub fn replaying_as<T>(replaying: bool, work: impl FnOnce() -> T) -> T {
57 let outer = REPLAYING.with(|current| current.replace(replaying));
58 let _restore = ReplayScope(outer);
59 work()
60}
61
62pub fn open_step(step: Option<ActionId>) {
68 OPEN_STEP.with(|open| open.set(step));
69}
70
71pub fn current_step() -> Option<ActionId> {
73 OPEN_STEP.with(std::cell::Cell::get)
74}
75
76pub const UNDONE_KEY: &str = "tilo:undone:";
81
82thread_local! {
83 static COMPENSATING: std::cell::RefCell<Option<(Vec<String>, bool)>> =
86 const { std::cell::RefCell::new(None) };
87}
88
89pub struct CompensatingScope(Option<(Vec<String>, bool)>);
95
96impl CompensatingScope {
97 #[must_use]
98 pub fn enter(marks: Vec<String>) -> Self {
99 Self(COMPENSATING.with(|current| current.replace(Some((marks, false)))))
100 }
101
102 #[must_use]
105 pub fn awaited(&self) -> bool {
106 COMPENSATING.with(|current| {
107 current
108 .borrow()
109 .as_ref()
110 .is_some_and(|(_, awaited)| *awaited)
111 })
112 }
113}
114
115impl Drop for CompensatingScope {
116 fn drop(&mut self) {
117 COMPENSATING.with(|current| *current.borrow_mut() = self.0.take());
118 }
119}
120
121#[must_use]
124pub fn await_compensation() -> Vec<String> {
125 COMPENSATING.with(|current| {
126 current
127 .borrow_mut()
128 .as_mut()
129 .map(|(marks, awaited)| {
130 *awaited = true;
131 marks.clone()
132 })
133 .unwrap_or_default()
134 })
135}
136
137pub fn await_settlement(doc: &mut Doc, hash: &str, redo: bool) -> Result<(), ActionError> {
142 use automerge::ReadDoc as _;
143 let key = format!("{UNDONE_KEY}{hash}");
144 let before = doc
145 .get(automerge::ROOT, &key)?
146 .and_then(|(value, _)| value.as_i64())
147 .filter(|attempt| (*attempt > 0) == redo && *attempt != 0)
148 .unwrap_or(0);
149 let attempt = if redo {
150 before.checked_add(1)
151 } else {
152 before.checked_sub(1)
153 }
154 .ok_or_else(|| ActionError::Refused("settlement attempts exceed the budget".into()))?;
155 doc.put(automerge::ROOT, key, attempt)?;
156 Ok(())
157}
158
159pub fn settle_compensation(doc: &mut Doc, hash: &str) -> Result<(), ActionError> {
162 use automerge::ReadDoc as _;
163 let key = format!("{UNDONE_KEY}{hash}");
164 let pending = doc
165 .get(automerge::ROOT, &key)?
166 .and_then(|(value, _)| value.as_i64())
167 .filter(|attempt| *attempt != 0)
168 .ok_or_else(|| ActionError::Refused("history compensation is not pending".into()))?;
169 if pending < 0 {
170 doc.put(automerge::ROOT, key, true)?;
171 } else {
172 doc.delete(automerge::ROOT, key)?;
173 }
174 Ok(())
175}
176
177pub fn invoking_context() -> Option<ActionContext> {
186 INVOKING.with(|current| current.borrow().clone())
187}
188
189pub fn reading_invoking_context<T>(read: impl FnOnce(Option<&ActionContext>) -> T) -> T {
192 INVOKING.with(|current| read(current.borrow().as_ref()))
193}
194
195pub fn with_invoking_context<T>(context: Option<ActionContext>, work: impl FnOnce() -> T) -> T {
199 let _invoking = InvokingScope::enter(context);
200 work()
201}
202
203struct InvokingScope(Option<ActionContext>);
205
206impl InvokingScope {
207 fn enter(context: Option<ActionContext>) -> Self {
208 Self(INVOKING.with(|current| current.replace(context)))
209 }
210}
211
212impl Drop for InvokingScope {
213 fn drop(&mut self) {
214 let outer = self.0.take();
215 INVOKING.with(|current| *current.borrow_mut() = outer);
216 }
217}
218
219enum Before {
221 Doc,
224 Written(Option<Box<Described>>),
228}
229
230fn envelope_for(
234 doc: &mut Doc,
235 action: &dyn Action,
236 encoded: EncodedAction,
237 actor: Option<&[u8]>,
238 context: Option<ActionContext>,
239 before: Before,
240) -> Result<ActionEnvelope, ActionError> {
241 let pinned = (ActionId::new(), tilo_clock::unix_now_i64());
242 envelope_pinned(doc, action, encoded, actor, context, before, pinned)
243}
244
245pub fn envelope_at(
255 doc: &mut Doc,
256 action: &dyn Action,
257 encoded: EncodedAction,
258 (actor, context): (&[u8], ActionContext),
259 pinned: (ActionId, i64),
260) -> Result<ActionEnvelope, ActionError> {
261 envelope_pinned(
262 doc,
263 action,
264 encoded,
265 Some(actor),
266 Some(context),
267 Before::Doc,
268 pinned,
269 )
270}
271
272fn envelope_pinned(
273 doc: &mut Doc,
274 action: &dyn Action,
275 encoded: EncodedAction,
276 actor: Option<&[u8]>,
277 context: Option<ActionContext>,
278 before: Before,
279 (id, timestamp): (ActionId, i64),
280) -> Result<ActionEnvelope, ActionError> {
281 let base = match before {
282 Before::Doc => doc.get_heads(),
283 Before::Written(_) => doc.committed_heads(),
284 };
285 let change = action.change_kind();
288 let mut context = context.unwrap_or_default();
289 if change != ChangeKind::Content {
290 context.change = change;
291 }
292 context.kind = Some(action.action_kind());
293 if action.incoming_message()
294 && !context
295 .facets
296 .iter()
297 .any(|facet| facet.key == crate::INCOMING_MESSAGE_FACET)
298 {
299 context.facets.push(crate::ActionFacet::new(
300 crate::INCOMING_MESSAGE_FACET,
301 "true",
302 ));
303 }
304 if let Some(readers) = action.readers() {
305 context
306 .facets
307 .retain(|facet| facet.key != crate::READERS_FACET);
308 context.facets.push(crate::ActionFacet::new(
309 crate::READERS_FACET,
310 crate::contract::readers_facet(&readers),
311 ));
312 }
313 if context.gesture.is_none() {
314 context.gesture = current_step();
315 }
316 let app = context.app.as_ref().map(|app| app.id.clone());
320 let (own, written) = match before {
322 Before::Doc => {
323 let _invoking = InvokingScope::enter(Some(context.clone()));
324 (action.describe(doc), false)
325 }
326 Before::Written(described) => (described.map(|described| *described), true),
327 };
328 let described = own
329 .or_else(|| context.described())
330 .or_else(|| Described::from_encoded(&encoded, app.as_deref()));
331 if let Some(mut described) = described {
332 if let Some(app) = app {
333 name_app(&mut described.what, &app);
334 }
335 context = context.with_described(described);
336 }
337 let actor = actor.filter(|a| !a.is_empty()).map(<[u8]>::to_vec);
342 let committing = actor
343 .clone()
344 .map_or_else(|| ActorId::from(id.actor_bytes().to_vec()), ActorId::from);
345 let compensation = if written {
346 None
347 } else {
348 inverse_as(doc, action, committing)
349 };
350 if compensation.is_none()
354 && let Some(actor) = actor.as_deref()
355 && let Some(gesture) = crate::run::continued_gesture(doc, actor, &context, timestamp)
356 {
357 context.gesture = Some(gesture);
358 }
359 if let Some(compensation) = &compensation
362 && serde_json::to_vec(compensation)
363 .map_err(ActionError::Encode)?
364 .len()
365 > crate::context::COMPENSATION_BUDGET
366 {
367 return Err(ActionError::Refused(
368 "document compensation exceeds the history budget".into(),
369 ));
370 }
371 context.action = Some(recorded_form(&encoded)?);
372 context.compensation = compensation;
373 let context = Some(context);
374 Ok(ActionEnvelope {
375 id,
376 action: encoded,
377 base_heads: base.iter().map(|h| h.0).collect(),
378 timestamp,
379 locus: action.locus(),
380 actor,
381 context,
382 })
383}
384
385pub fn inverse_as(doc: &mut Doc, action: &dyn Action, actor: ActorId) -> Option<EncodedAction> {
389 let previous = doc.get_actor().clone();
390 doc.set_actor(actor);
391 let inverse = action.inverse_encoded(doc);
392 doc.set_actor(previous);
393 inverse
394}
395
396fn name_app(what: &mut Did, app: &str) {
398 match what {
399 Did::Verb(verb) if verb.action.app.is_empty() => app.clone_into(&mut verb.action.app),
400 Did::Group(group) => {
401 for member in &mut group.members {
402 name_app(member, app);
403 }
404 }
405 _ => {}
406 }
407}
408
409fn apply_under_envelope(
439 doc: &mut Doc,
440 action: &dyn Action,
441 env: &ActionEnvelope,
442 content: Option<&tilo_content::ContentStore>,
443) -> Result<Option<crate::entry::ActionItem>, ActionError> {
444 let prev_actor = doc.get_actor().clone();
445 doc.set_actor(env.actor());
449 let applied = {
450 let _invoking = InvokingScope::enter(env.context.clone());
451 action.apply(doc)
452 };
453 if let Err(e) = applied {
454 abort_pinned_change(doc, prev_actor);
455 return Err(e);
456 }
457 let mut made = None;
458 if doc.pending_ops() > 0 {
459 made = env
468 .context
469 .as_ref()
470 .filter(|context| !is_replaying() && context.what.is_some() && context.item.is_none())
471 .and_then(|_| action.made(doc));
472 commit_pinned(doc, env, made.as_ref());
473 doc.set_actor(prev_actor);
474 crate::content::keep(env, content);
475 } else {
476 abort_pinned_change(doc, prev_actor);
480 }
481 Ok(made)
482}
483
484fn commit_pinned(doc: &mut Doc, env: &ActionEnvelope, made: Option<&crate::entry::ActionItem>) {
488 let named = made.and_then(|item| {
489 let context = env.context.as_ref()?;
490 Some(
491 context
492 .clone()
493 .with_described(context.described()?.on(item.id.clone(), item.label.clone())),
494 )
495 });
496 let context = named.as_ref().or(env.context.as_ref());
497 let mut options = CommitOptions::default().with_time(env.timestamp);
498 if let Some(message) = context.and_then(|context| entry_message(doc, &env.actor(), context)) {
499 options = options.with_message(message);
500 }
501 doc.commit_with(options);
502}
503
504fn named(mut env: ActionEnvelope, made: Option<crate::entry::ActionItem>) -> ActionEnvelope {
508 if let Some(item) = made
509 && let Some(context) = env.context.as_ref()
510 && let Some(described) = context.described()
511 {
512 env.context = Some(
513 context
514 .clone()
515 .with_described(described.on(item.id, item.label)),
516 );
517 }
518 env
519}
520
521#[must_use]
527pub fn entry_message(doc: &Doc, actor: &ActorId, context: &ActionContext) -> Option<String> {
528 if context.gesture.is_some() && context.compensation.is_none() {
529 let document = doc.committed_document();
530 let continuation = document
531 .hash_of_actor_seq(actor, document.applied_seq(actor))
532 .and_then(|last| context.continuation_of(&opening_entry(document, last)?));
533 if continuation.is_some() {
534 return continuation;
535 }
536 }
537 context.change_message()
538}
539
540const MAX_CONTINUATIONS: usize = 256;
544
545const CONTINUATIONS_KEPT: usize = 8;
547
548thread_local! {
549 static CONTINUATIONS: std::cell::RefCell<std::collections::VecDeque<(automerge::ChangeHash, ActionContext, usize)>> =
556 const { std::cell::RefCell::new(std::collections::VecDeque::new()) };
557}
558
559#[cfg(test)]
560thread_local! {
561 static STEPS_BACK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
563}
564
565#[must_use]
569pub fn entry_of(doc: &automerge::Automerge, hash: automerge::ChangeHash) -> Option<ActionContext> {
570 let entry = opening_entry(doc, hash)?;
571 match doc.get_change_meta_by_hash(&hash)?.message.as_deref() {
572 Some(message) if message.starts_with(CONTINUATION_PREFIX) => {
573 ActionContext::continued(message, &entry)
574 }
575 _ => Some(entry),
576 }
577}
578
579fn opening_entry(doc: &automerge::Automerge, hash: automerge::ChangeHash) -> Option<ActionContext> {
583 let meta = doc.get_change_meta_by_hash(&hash)?;
584 let message = meta.message.as_deref()?;
585 if let Some(entry) = ActionContext::from_change_message(message) {
586 return Some(entry);
587 }
588 if !message.starts_with(CONTINUATION_PREFIX) {
589 return None;
590 }
591 let (first, depth) = first_entry(doc, &meta)?;
592 CONTINUATIONS.with_borrow_mut(|kept| {
593 if !kept.iter().any(|(kept, ..)| *kept == hash) {
594 if kept.len() >= CONTINUATIONS_KEPT {
595 kept.pop_front();
596 }
597 kept.push_back((hash, first.clone(), depth));
598 }
599 });
600 Some(first)
601}
602
603fn first_entry(
607 doc: &automerge::Automerge,
608 meta: &automerge::ChangeMetadata<'_>,
609) -> Option<(ActionContext, usize)> {
610 for depth in 1..=MAX_CONTINUATIONS {
611 #[cfg(test)]
612 STEPS_BACK.with(|steps| steps.set(steps.get().saturating_add(1)));
613 let seq = meta.seq.checked_sub(u64::try_from(depth).ok()?)?;
614 let earlier = doc.get_change_meta_by_hash(&doc.hash_of_actor_seq(&meta.actor, seq)?)?;
615 let text = earlier.message.as_deref()?;
616 if let Some(first) = ActionContext::from_change_message(text) {
617 return Some((first, depth));
618 }
619 if !text.starts_with(CONTINUATION_PREFIX) {
620 return None;
621 }
622 let kept = CONTINUATIONS.with_borrow(|kept| {
623 kept.iter()
624 .find(|(hash, ..)| *hash == earlier.hash)
625 .map(|(_, first, back)| (first.clone(), *back))
626 });
627 if let Some((first, back)) = kept {
628 let depth = depth.checked_add(back)?;
629 return (depth <= MAX_CONTINUATIONS).then_some((first, depth));
630 }
631 }
632 None
633}
634
635#[cfg(test)]
636#[path = "executor_entry_tests.rs"]
637mod entry_tests;
638
639#[derive(Default)]
642pub struct EntryReader {
643 firsts: std::collections::HashMap<ActorId, ActionContext>,
644}
645
646impl EntryReader {
647 pub fn read(&mut self, actor: &ActorId, message: Option<&str>) -> Option<ActionContext> {
650 let message = message?;
651 if let Some(entry) = ActionContext::from_change_message(message) {
652 self.firsts.insert(actor.clone(), entry.clone());
653 return Some(entry);
654 }
655 ActionContext::continued(message, self.firsts.get(actor)?)
656 }
657}
658
659fn abort_pinned_change(doc: &mut Doc, prev_actor: ActorId) {
681 doc.rollback();
682 doc.reset_diff_cursor();
683 doc.set_actor(prev_actor);
684}
685
686pub fn apply_local(
696 doc: &mut Doc,
697 action: &dyn Action,
698 encoded: EncodedAction,
699) -> Result<ActionEnvelope, ActionError> {
700 apply_local_by(doc, action, encoded, None)
701}
702
703pub fn apply_local_by(
712 doc: &mut Doc,
713 action: &dyn Action,
714 encoded: EncodedAction,
715 actor: Option<&[u8]>,
716) -> Result<ActionEnvelope, ActionError> {
717 apply_steps(doc, action, encoded, (actor, None), &mut |_| {})
718}
719
720fn apply_steps(
725 doc: &mut Doc,
726 action: &dyn Action,
727 encoded: EncodedAction,
728 (actor, context): (Option<&[u8]>, Option<ActionContext>),
729 each: &mut dyn FnMut(&ActionEnvelope),
730) -> Result<ActionEnvelope, ActionError> {
731 let steps = {
734 let _invoking = InvokingScope::enter(context.clone());
735 action.steps(doc).filter(|steps| !steps.is_empty())
736 };
737 let Some(steps) = steps else {
738 let env = envelope_for(doc, action, encoded, actor, context, Before::Doc)?;
739 let made = apply_under_envelope(doc, action, &env, None)?;
740 let env = named(env, made);
741 each(&env);
742 return Ok(env);
743 };
744 let mut context = context.unwrap_or_default();
747 let asked = {
748 let _invoking = InvokingScope::enter(Some(context.clone()));
749 action.describe(doc)
750 };
751 let op = match asked.map(|asked| asked.what) {
752 Some(Did::History(step)) => step.op,
753 _ => crate::HistoryOp::Undo,
754 };
755 let gesture = *context.gesture.get_or_insert_with(ActionId::new);
756 context.group.get_or_insert_with(|| crate::WorkGroup {
757 id: gesture.0.to_string(),
758 label: None,
759 kind: crate::context::history_group(&op),
760 declared_id: None,
761 session: None,
762 });
763 let context = Some(context);
764 let mut last = None;
765 for (step, payload) in steps {
766 let encoded = EncodedAction {
767 type_id: encoded.type_id.clone(),
768 payload,
769 };
770 let env = envelope_for(
771 doc,
772 step.as_ref(),
773 encoded,
774 actor,
775 context.clone(),
776 Before::Doc,
777 )?;
778 let made = apply_under_envelope(doc, step.as_ref(), &env, None)?;
779 let env = named(env, made);
780 each(&env);
781 last = Some(env);
782 }
783 last.ok_or_else(|| ActionError::Refused("no step to apply".into()))
784}
785
786pub fn apply_local_with_context(
794 doc: &mut Doc,
795 action: &dyn Action,
796 encoded: EncodedAction,
797 actor: Option<&[u8]>,
798 context: ActionContext,
799) -> Result<ActionEnvelope, ActionError> {
800 apply_steps(doc, action, encoded, (actor, Some(context)), &mut |_| {})
801}
802
803pub fn commit_written(
819 doc: &mut Doc,
820 action: &dyn Action,
821 encoded: EncodedAction,
822 actor: &[u8],
823 context: ActionContext,
824 described: Option<Described>,
825) -> Result<ActionEnvelope, ActionError> {
826 if doc.get_actor().to_bytes() != actor || doc.pending_ops() == 0 {
827 return Err(ActionError::Refused(
828 "the document holds no writes of this actor to commit".into(),
829 ));
830 }
831 let env = envelope_for(
832 doc,
833 action,
834 encoded,
835 Some(actor),
836 Some(context),
837 Before::Written(described.map(Box::new)),
838 )?;
839 commit_pinned(doc, &env, None);
840 Ok(env)
841}
842
843pub fn replay(
853 doc: &mut Doc,
854 env: &ActionEnvelope,
855 registry: &ActionRegistry,
856) -> Result<(), ActionError> {
857 let action = registry.decode(&env.action)?;
858 replay_decoded(doc, env, action.as_ref(), registry.content())
859}
860
861pub fn replay_decoded(
869 doc: &mut Doc,
870 env: &ActionEnvelope,
871 action: &dyn Action,
872 content: Option<&tilo_content::ContentStore>,
873) -> Result<(), ActionError> {
874 let _replaying = ReplayScope::enter();
875 let base_heads = env.base_change_hashes();
876 if doc.get_heads() == base_heads {
877 validate_compensation(doc, action, env)?;
878 return apply_under_envelope(doc, action, env, content).map(drop);
879 }
880
881 let mut replay_base = doc.fork_at(&base_heads)?;
890 validate_compensation(&mut replay_base, action, env)?;
891 apply_under_envelope(&mut replay_base, action, env, content).map(drop)?;
892 merge_replayed(doc, &mut replay_base)?;
893 Ok(())
894}
895
896#[expect(
900 clippy::disallowed_methods,
901 reason = "the action layer's one merge, dropping what it logs"
902)]
903fn merge_replayed(
904 doc: &mut Doc,
905 replayed: &mut Doc,
906) -> Result<Vec<automerge::ChangeHash>, automerge::AutomergeError> {
907 let merged = doc.merge(replayed);
908 if doc.diff_cursor().is_empty() {
909 doc.reset_diff_cursor();
910 }
911 merged
912}
913
914#[derive(Clone, Debug, PartialEq, Eq)]
916pub enum Verified {
917 Reproduced,
919 NothingRecorded,
922 UnknownAction(String),
925 ContentMissing(String),
928}
929
930pub fn recorded_form(action: &EncodedAction) -> Result<EncodedAction, ActionError> {
937 if recorded_size(action) <= crate::context::WHOLE_ACTION_BUDGET {
938 return Ok(action.clone());
939 }
940 let recorded = action.with_content_parts(crate::content::CONTENT_PART_THRESHOLD)?;
941 if recorded_size(&recorded) > crate::context::HISTORY_BUDGET {
942 return Err(ActionError::Refused(
943 "the action is too large to record, even with its large parts kept as content".into(),
944 ));
945 }
946 Ok(recorded)
947}
948
949fn recorded_size(action: &EncodedAction) -> usize {
952 action.type_id.len().saturating_add(action.payload.len())
953}
954
955pub fn verify_change(
962 doc: &mut Doc,
963 hash: automerge::ChangeHash,
964 registry: &ActionRegistry,
965) -> Result<Verified, ActionError> {
966 let change = doc
967 .get_change_meta_by_hash(&hash)
968 .ok_or_else(|| ActionError::Refused("the change is not in the document".into()))?
969 .into_owned();
970 let Some(context) = entry_of(doc.committed_document(), hash) else {
971 return Ok(Verified::NothingRecorded);
972 };
973 let Some(recorded) = context.action.as_ref() else {
974 return Ok(Verified::NothingRecorded);
975 };
976 if !registry.contains(&recorded.type_id) {
977 return Ok(Verified::UnknownAction(recorded.type_id.clone()));
978 }
979 let action = match registry.resolve(recorded)? {
980 Ok(action) => action,
981 Err(missing) => return Ok(Verified::ContentMissing(missing.0)),
982 };
983 let env = ActionEnvelope {
984 id: ActionId::new(),
985 action,
986 base_heads: change.deps.iter().map(|head| head.0).collect(),
987 timestamp: change.timestamp,
988 locus: ExecutionLocus::ClientLocal,
989 actor: Some(change.actor.to_bytes().to_vec()),
990 context: Some(context),
991 };
992 let mut original = doc.fork_at(&change.deps)?;
993 replay(&mut original, &env, registry)?;
994 if original.get_heads() != [hash] {
995 return Err(ActionError::Refused(
996 "the change is not what its recorded action produces".into(),
997 ));
998 }
999 Ok(Verified::Reproduced)
1000}
1001
1002pub fn verified_compensation(
1005 doc: &mut Doc,
1006 hash: automerge::ChangeHash,
1007 registry: &ActionRegistry,
1008) -> Result<Option<Box<dyn Action>>, ActionError> {
1009 doc.get_change_meta_by_hash(&hash)
1010 .ok_or_else(|| ActionError::Refused("history change is unavailable".into()))?;
1011 let inverse = entry_of(doc.committed_document(), hash).and_then(|context| context.compensation);
1012 let Some(inverse) = inverse else {
1013 return Ok(None);
1014 };
1015 match verify_change(doc, hash, registry)? {
1016 Verified::Reproduced => registry.decode(&inverse).map(Some),
1017 Verified::NothingRecorded | Verified::UnknownAction(_) | Verified::ContentMissing(_) => {
1018 Err(ActionError::Refused(
1019 "recorded history action does not reproduce its change".into(),
1020 ))
1021 }
1022 }
1023}
1024
1025fn validate_compensation(
1026 doc: &mut Doc,
1027 action: &dyn Action,
1028 env: &ActionEnvelope,
1029) -> Result<(), ActionError> {
1030 let Some(context) = env.context.as_ref() else {
1031 return Ok(());
1032 };
1033 let Some(recorded) = context.action.as_ref() else {
1034 return Ok(());
1035 };
1036 if recorded.recorded_parts_of(&env.action).is_none()
1037 || inverse_as(doc, action, env.actor()) != context.compensation
1038 {
1039 return Err(ActionError::Refused(
1040 "recorded compensation differs from the action's canonical before state".into(),
1041 ));
1042 }
1043 Ok(())
1044}
1045
1046#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1048pub enum HostDecision {
1049 AcceptedByHost,
1052 Unavailable,
1054}
1055
1056pub trait ActionTransport {
1061 fn replicate(&mut self, env: &ActionEnvelope);
1063
1064 fn submit_to_host(&mut self, _env: &ActionEnvelope) -> HostDecision {
1068 HostDecision::Unavailable
1069 }
1070}
1071
1072#[derive(Clone, Debug, PartialEq, Eq)]
1074pub enum Dispatched {
1075 AppliedLocal(ActionEnvelope),
1077 SubmittedToHost(ActionEnvelope),
1080}
1081
1082impl Dispatched {
1083 pub fn envelope(&self) -> &ActionEnvelope {
1085 match self {
1086 Dispatched::AppliedLocal(e) | Dispatched::SubmittedToHost(e) => e,
1087 }
1088 }
1089
1090 pub fn mutated_local(&self) -> bool {
1093 !matches!(self, Dispatched::SubmittedToHost(_))
1094 }
1095}
1096
1097pub fn dispatch(
1107 doc: &mut Doc,
1108 action: &dyn Action,
1109 encoded: EncodedAction,
1110 transport: &mut dyn ActionTransport,
1111) -> Result<Dispatched, ActionError> {
1112 dispatch_by(doc, action, encoded, transport, None)
1113}
1114
1115pub fn dispatch_by(
1123 doc: &mut Doc,
1124 action: &dyn Action,
1125 encoded: EncodedAction,
1126 transport: &mut dyn ActionTransport,
1127 actor: Option<&[u8]>,
1128) -> Result<Dispatched, ActionError> {
1129 dispatch_by_maybe_context(doc, action, encoded, transport, actor, None)
1130}
1131
1132pub fn dispatch_with_context(
1139 doc: &mut Doc,
1140 action: &dyn Action,
1141 encoded: EncodedAction,
1142 transport: &mut dyn ActionTransport,
1143 context: ActionContext,
1144) -> Result<Dispatched, ActionError> {
1145 dispatch_by_maybe_context(doc, action, encoded, transport, None, Some(context))
1146}
1147
1148pub fn dispatch_by_with_context(
1154 doc: &mut Doc,
1155 action: &dyn Action,
1156 encoded: EncodedAction,
1157 transport: &mut dyn ActionTransport,
1158 actor: Option<&[u8]>,
1159 context: ActionContext,
1160) -> Result<Dispatched, ActionError> {
1161 dispatch_by_maybe_context(doc, action, encoded, transport, actor, Some(context))
1162}
1163
1164fn dispatch_by_maybe_context(
1165 doc: &mut Doc,
1166 action: &dyn Action,
1167 encoded: EncodedAction,
1168 transport: &mut dyn ActionTransport,
1169 actor: Option<&[u8]>,
1170 context: Option<ActionContext>,
1171) -> Result<Dispatched, ActionError> {
1172 match action.locus() {
1177 ExecutionLocus::ClientLocal => {
1178 apply_steps(doc, action, encoded, (actor, context), &mut |env| {
1179 transport.replicate(env);
1180 })
1181 .map(Dispatched::AppliedLocal)
1182 }
1183 ExecutionLocus::ServerPreferred => {
1184 let env = envelope_for(doc, action, encoded, actor, context, Before::Doc)?;
1185 match transport.submit_to_host(&env) {
1186 HostDecision::AcceptedByHost => Ok(Dispatched::SubmittedToHost(env)),
1187 HostDecision::Unavailable => Err(ActionError::Refused(
1188 "this action requires an authoritative host, but none is reachable".into(),
1189 )),
1190 }
1191 }
1192 }
1193}
1194
1195#[derive(Default)]
1199pub struct LocalTransport {
1200 pub replicated: Vec<ActionEnvelope>,
1201}
1202
1203impl LocalTransport {
1204 pub fn new() -> Self {
1205 Self::default()
1206 }
1207}
1208
1209impl ActionTransport for LocalTransport {
1210 fn replicate(&mut self, env: &ActionEnvelope) {
1211 self.replicated.push(env.clone());
1212 }
1213 }