1use std::any::Any;
11use std::marker::PhantomData;
12use tilo_sort::CompactSort as _;
13
14use automerge::ROOT;
15use serde::de::DeserializeOwned;
16use serde::{Deserialize, Serialize};
17use tilo_action_policy::MemberId;
18use tilo_actions::{ActionError, ExecutionLocus, RiskLevel};
19
20use crate::collection::Id;
21use crate::kind::ResourceKind;
22use crate::model::{Doc, Fields};
23use crate::resource::Resource;
24
25#[derive(Debug)]
31pub struct ActionCx {
32 preview: bool,
33 seed: [u8; 32],
34 minted: u64,
35 ids: Vec<Id>,
37 now_ms: i64,
38 author: Option<MemberId>,
39 invocation: Option<tilo_actions::InvocationId>,
40 removes_item: bool,
42}
43
44fn invoking_author() -> Option<MemberId> {
46 tilo_actions::reading_invoking_context(|context| {
47 context
48 .and_then(|context| context.invoker.as_ref())
49 .and_then(invoker_member)
50 })
51 .or_else(|| RESOURCE_ACTOR.with_borrow(Clone::clone))
52}
53
54fn invoker_member(invoker: &tilo_actions::ActionInvoker) -> Option<MemberId> {
57 invoker
58 .acting
59 .members()
60 .first()
61 .map(|member| (*member).clone())
62}
63
64pub(crate) fn writing_author() -> Option<MemberId> {
69 tilo_actions::reading_invoking_context(|context| match context {
70 Some(context) => context.invoker.as_ref().and_then(invoker_member),
71 None => RESOURCE_ACTOR.with_borrow(Clone::clone),
72 })
73}
74
75thread_local! {
76 static RESOURCE_ACTOR: std::cell::RefCell<Option<MemberId>> = const { std::cell::RefCell::new(None) };
77}
78
79pub struct ResourceActorScope(Option<MemberId>);
85
86impl ResourceActorScope {
87 #[must_use]
89 pub fn enter(actor: MemberId) -> Self {
90 Self(RESOURCE_ACTOR.replace(Some(actor)))
91 }
92}
93
94impl Drop for ResourceActorScope {
95 fn drop(&mut self) {
96 RESOURCE_ACTOR.replace(self.0.take());
97 }
98}
99
100fn invoking_invocation() -> Option<tilo_actions::InvocationId> {
101 tilo_actions::reading_invoking_context(|context| context?.source_invocation)
102}
103
104impl ActionCx {
105 pub fn remove_item(&mut self) {
110 self.removes_item = true;
111 }
112
113 #[doc(hidden)]
116 pub fn take_item_removal(&mut self) -> bool {
117 std::mem::take(&mut self.removes_item)
118 }
119
120 #[must_use]
127 pub fn for_apply(doc: &Doc, payload: &[u8], now_ms: i64) -> Self {
128 Self {
129 preview: tilo_actions::executor::is_replaying(),
130 seed: seed(doc, b"tilo-resource/action-seed/v1", payload),
131 minted: 0,
132 ids: Vec::new(),
133 now_ms,
134 author: invoking_author(),
135 invocation: invoking_invocation(),
136 removes_item: false,
137 }
138 }
139
140 #[must_use]
145 pub fn for_write(doc: &Doc, payload: &[u8]) -> Self {
146 let mut hasher = blake3::Hasher::new();
147 hasher.update(b"tilo-resource/write-seed/v1");
148 if let Some((group, position)) = crate::group::current_member() {
149 hasher.update(b"member");
150 hasher.update(&group);
151 hasher.update(&position.to_le_bytes());
152 } else {
153 hasher.update(doc.get_actor().to_bytes());
154 let mut heads = automerge::transaction::Transactable::base_heads(doc);
155 heads.compact_sort();
156 for head in heads {
157 hasher.update(&head.0);
158 }
159 }
160 hasher.update(payload);
161 Self {
162 preview: tilo_actions::executor::is_replaying(),
163 seed: *hasher.finalize().as_bytes(),
164 minted: 0,
165 ids: Vec::new(),
166 now_ms: 0,
167 author: invoking_author(),
168 invocation: invoking_invocation(),
169 removes_item: false,
170 }
171 }
172
173 #[must_use]
177 pub fn is_preview(&self) -> bool {
178 self.preview
179 }
180
181 pub fn id(&mut self) -> Id {
183 let id = minted(&self.seed, self.minted);
184 self.minted = self.minted.saturating_add(1);
185 self.ids.push(id.clone());
186 note_minted(id.as_str());
187 id
188 }
189
190 pub fn uuid(&mut self) -> uuid::Uuid {
192 let uuid = minted_uuid(&self.seed, self.minted);
193 self.minted = self.minted.saturating_add(1);
194 note_minted(&uuid.to_string());
195 uuid
196 }
197
198 pub fn named(&mut self, id: impl Into<String>, label: impl Into<String>) {
205 NAMED.with(|named| {
206 named.borrow_mut().replace(tilo_actions::ActionItem {
207 id: id.into(),
208 label: label.into(),
209 });
210 });
211 }
212
213 #[must_use]
216 pub fn acting_name(&self) -> String {
217 invoking_name()
218 }
219
220 #[must_use]
223 pub fn appearance(&self) -> Option<tilo_actions::Appearance> {
224 tilo_actions::reading_invoking_context(|context| {
225 context?
226 .invoker
227 .as_ref()
228 .filter(|invoker| invoker.acting.is_bot())?
229 .appearance
230 .clone()
231 })
232 }
233
234 #[must_use]
237 pub fn invoked_by(&self) -> Option<tilo_actions::Acting> {
238 tilo_actions::reading_invoking_context(|context| {
239 Some(context?.invoker.as_ref()?.acting.clone())
240 })
241 }
242
243 pub fn now_ms(&self) -> i64 {
246 self.now_ms
247 }
248
249 pub fn author(&self) -> Option<&MemberId> {
255 self.author.as_ref()
256 }
257
258 pub const fn invocation(&self) -> Option<tilo_actions::InvocationId> {
262 self.invocation
263 }
264}
265
266fn uuid_from(digest: &[u8; 32]) -> uuid::Uuid {
267 let mut bytes = [0_u8; 16];
268 bytes.copy_from_slice(digest.get(..16).unwrap_or(&[0; 16]));
269 uuid::Builder::from_random_bytes(bytes).into_uuid()
270}
271
272thread_local! {
273 static MINTED: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
275 static ENTRIES: std::cell::RefCell<std::collections::HashMap<String, automerge::ObjId>> =
278 std::cell::RefCell::new(std::collections::HashMap::new());
279 static NAMED: std::cell::RefCell<Option<tilo_actions::ActionItem>> =
283 const { std::cell::RefCell::new(None) };
284}
285
286pub(crate) fn start_minting() {
289 drop(take_minted());
290 ENTRIES.with(|entries| entries.borrow_mut().clear());
291 NAMED.with(|named| named.borrow_mut().take());
292}
293
294pub(crate) fn note_entry(map: &automerge::ObjId, id: &str) {
297 ENTRIES.with(|entries| {
298 entries.borrow_mut().insert(id.to_owned(), map.clone());
299 });
300}
301
302#[must_use]
306pub fn minted_entry(id: &str) -> Option<automerge::ObjId> {
307 ENTRIES.with(|entries| entries.borrow().get(id).cloned())
308}
309
310pub(crate) fn named_item() -> Option<tilo_actions::ActionItem> {
313 NAMED.with_borrow(Clone::clone)
314}
315
316pub(crate) fn entries_so_far() -> Vec<String> {
319 ENTRIES.with_borrow(|entries| entries.keys().cloned().collect())
320}
321
322pub(crate) fn minted_so_far() -> Vec<String> {
326 MINTED.with_borrow(Clone::clone)
327}
328
329pub(crate) fn note_minted(id: &str) {
332 MINTED.with(|minted| minted.borrow_mut().push(id.to_owned()));
333}
334
335#[must_use]
339pub fn take_minted() -> Vec<String> {
340 MINTED.with(|minted| std::mem::take(&mut *minted.borrow_mut()))
341}
342
343pub fn restore_minted(ids: impl IntoIterator<Item = String>) {
346 MINTED.with(|minted| minted.borrow_mut().extend(ids));
347}
348
349thread_local! {
350 static MINT: std::cell::Cell<Option<([u8; 32], u64)>> = const { std::cell::Cell::new(None) };
353}
354
355struct MintScope(Option<([u8; 32], u64)>);
356
357impl MintScope {
358 fn enter(cx: &ActionCx) -> Self {
359 let mut hasher = blake3::Hasher::new();
360 hasher.update(b"tilo-resource/fresh-uuid/v1");
361 hasher.update(&cx.seed);
362 let seed = *hasher.finalize().as_bytes();
363 Self(MINT.with(|mint| mint.replace(Some((seed, 0)))))
364 }
365}
366
367impl Drop for MintScope {
368 fn drop(&mut self) {
369 MINT.with(|mint| mint.set(self.0));
370 }
371}
372
373#[must_use]
377pub fn invoking_member() -> Option<MemberId> {
378 invoking_author()
379}
380
381#[must_use]
385pub fn invoking_name() -> String {
386 tilo_actions::reading_invoking_context(|context| {
387 context
388 .and_then(|context| context.invoker.as_ref())
389 .filter(|invoker| !invoker.acting.is_person())
390 .and_then(|invoker| invoker.name.clone())
391 .filter(|name| !name.trim().is_empty())
392 .unwrap_or_default()
393 })
394}
395
396#[must_use]
401pub fn fresh_uuid() -> uuid::Uuid {
402 MINT.with(|mint| match mint.get() {
403 Some((seed, counter)) => {
404 mint.set(Some((seed, counter.saturating_add(1))));
405 let mut hasher = blake3::Hasher::new();
406 hasher.update(&seed);
407 hasher.update(&counter.to_le_bytes());
408 let uuid = uuid_from(hasher.finalize().as_bytes());
409 note_minted(&uuid.to_string());
410 uuid
411 }
412 None => uuid::Uuid::new_v4(),
413 })
414}
415
416fn minted_uuid(seed: &[u8; 32], counter: u64) -> uuid::Uuid {
417 let mut hasher = blake3::Hasher::new();
418 hasher.update(b"uuid");
419 hasher.update(seed);
420 hasher.update(&counter.to_le_bytes());
421 uuid_from(hasher.finalize().as_bytes())
422}
423
424fn minted(seed: &[u8; 32], counter: u64) -> Id {
425 let mut hasher = blake3::Hasher::new();
426 hasher.update(seed);
427 hasher.update(&counter.to_le_bytes());
428 let digest = hasher.finalize();
429 let hex = digest.to_hex();
430 Id::from_raw(hex.as_str().get(..20).unwrap_or_default())
431}
432
433pub fn minted_ids(envelope: &tilo_actions::ActionEnvelope) -> impl Iterator<Item = Id> {
438 let seed = envelope_seed(envelope);
439 (0_u64..).map(move |counter| minted(&seed, counter))
440}
441
442pub fn minted_keys(envelope: &tilo_actions::ActionEnvelope) -> impl Iterator<Item = [String; 2]> {
446 let seed = envelope_seed(envelope);
447 (0_u64..).map(move |counter| {
448 [
449 minted(&seed, counter).as_str().to_owned(),
450 minted_uuid(&seed, counter).to_string(),
451 ]
452 })
453}
454
455fn envelope_seed(envelope: &tilo_actions::ActionEnvelope) -> [u8; 32] {
457 let mut hasher = blake3::Hasher::new();
458 hasher.update(b"tilo-resource/action-seed/v1");
459 hasher.update(envelope.actor().to_bytes());
460 let mut heads = envelope.base_heads.clone();
461 heads.compact_sort();
462 for head in &heads {
463 hasher.update(head);
464 }
465 hasher.update(&envelope.action.payload);
466 *hasher.finalize().as_bytes()
467}
468
469pub(crate) fn seed(doc: &Doc, domain: &[u8], payload: &[u8]) -> [u8; 32] {
473 use automerge::transaction::Transactable as _;
474 let mut hasher = blake3::Hasher::new();
475 hasher.update(domain);
476 if let Some((group, position)) = crate::group::current_member() {
477 hasher.update(b"member");
478 hasher.update(&group);
479 hasher.update(&position.to_le_bytes());
480 } else {
481 hasher.update(doc.get_actor().to_bytes());
482 let mut heads = doc.base_heads();
487 heads.compact_sort();
488 for head in heads {
489 hasher.update(&head.0);
490 }
491 let pending = doc.pending_ops();
492 if pending > 0 {
493 hasher.update(b"pending");
494 hasher.update(&u64::try_from(pending).unwrap_or(u64::MAX).to_le_bytes());
495 }
496 }
497 hasher.update(payload);
498 *hasher.finalize().as_bytes()
499}
500
501pub trait Outcome {
503 fn into_result(self) -> Result<(), Refusal>;
504}
505
506impl Outcome for () {
507 fn into_result(self) -> Result<(), Refusal> {
508 Ok(())
509 }
510}
511
512impl<E: Into<Refusal>> Outcome for Result<(), E> {
513 fn into_result(self) -> Result<(), Refusal> {
514 self.map_err(Into::into)
515 }
516}
517
518pub use tilo_action_policy::ActionKind;
519
520pub use tilo_actions::ActionKey;
521
522pub trait Operation: Serialize + DeserializeOwned + Clone + std::fmt::Debug + 'static {
524 type Record: Fields + 'static;
525
526 const KIND: &'static str;
528
529 fn edit(&self) -> Option<&crate::Edit<Self::Record>> {
532 None
533 }
534
535 fn kind(&self) -> ActionKind {
538 ActionKind::Undoable
539 }
540
541 fn perform(&self, record: &mut Self::Record, cx: &mut ActionCx) -> Result<(), Refusal>;
543
544 fn writes(&self) -> crate::footprint::Writes {
548 crate::footprint::Writes::record()
549 }
550
551 fn snapshot(record: &Self::Record) -> Option<Self::Record> {
556 let _ = record;
557 None
558 }
559
560 fn risk(&self) -> RiskLevel {
565 RiskLevel::Low
566 }
567
568 fn change_kind(&self) -> tilo_actions::ChangeKind {
573 tilo_actions::ChangeKind::Content
574 }
575
576 fn incoming_message(&self) -> bool {
579 false
580 }
581
582 fn irreversible(&self) -> bool {
586 false
587 }
588
589 fn by_app(&self) -> bool {
593 false
594 }
595
596 fn compensates(&self) -> bool {
599 false
600 }
601
602 const QUEUES: bool = false;
605
606 fn queue(record: &mut Self::Record, before: &Self::Record, cx: &mut ActionCx) {
609 let _ = (record, before, cx);
610 }
611
612 fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>> {
617 let _ = (doc, cx);
618 None
619 }
620
621 fn field_edit(edit: crate::Edit<Self::Record>) -> Option<Self> {
623 let _ = edit;
624 None
625 }
626
627 fn compensation(
631 &self,
632 before: &Self::Record,
633 after: &Self::Record,
634 minted: &[Id],
635 ) -> Option<Result<Self, String>> {
636 let _ = (before, after, minted);
637 None
638 }
639}
640
641pub struct Undoing<'a, R, P> {
648 pub before: &'a R,
649 pub after: &'a R,
650 pub minted: &'a [Id],
651 pub params: &'a P,
652}
653
654impl<R, P> Clone for Undoing<'_, R, P> {
655 fn clone(&self) -> Self {
656 *self
657 }
658}
659
660impl<R, P> Copy for Undoing<'_, R, P> {}
661
662#[allow(
665 clippy::needless_pass_by_value,
666 reason = "`map_err` hands it the error by value"
667)]
668fn model_refused(error: crate::ModelError) -> ActionError {
669 ActionError::Refused(error.to_string())
670}
671
672#[allow(
674 clippy::needless_pass_by_value,
675 reason = "`map_err` hands it the error by value"
676)]
677fn automerge_refused(error: automerge::AutomergeError) -> ActionError {
678 ActionError::Refused(error.to_string())
679}
680
681pub use tilo_actions::Refusal;
682
683fn refusal_refused(refusal: Refusal) -> ActionError {
685 refusal.into()
686}
687
688#[derive(Serialize, Clone)]
691pub struct Stamped<O> {
692 #[serde(rename = "op")]
693 pub operation: O,
694 #[serde(rename = "at", default)]
695 pub now_ms: i64,
696}
697
698impl<O: std::fmt::Debug> std::fmt::Debug for Stamped<O> {
699 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
700 fmt_stamped(&self.operation, self.now_ms, f)
701 }
702}
703
704fn fmt_stamped(
705 operation: &dyn std::fmt::Debug,
706 now_ms: i64,
707 f: &mut std::fmt::Formatter<'_>,
708) -> std::fmt::Result {
709 f.debug_struct("Stamped")
710 .field("operation", operation)
711 .field("now_ms", &now_ms)
712 .finish()
713}
714
715impl<'de, O: DeserializeOwned> Deserialize<'de> for Stamped<O> {
718 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
719 let value = serde_json::Value::deserialize(deserializer)?;
720 match Self::from_json(value) {
721 Ok(stamped) => Ok(stamped),
722 Err(error) => Err(serde::de::Error::custom(error)),
723 }
724 }
725}
726
727impl<O: DeserializeOwned> Stamped<O> {
728 pub fn from_json(value: serde_json::Value) -> Result<Self, serde_json::Error> {
733 let (operation, now_ms) = stamped_parts(value)?;
734 Ok(Self {
735 operation: O::deserialize(operation)?,
736 now_ms,
737 })
738 }
739}
740
741#[inline(never)]
743fn stamped_parts(value: serde_json::Value) -> Result<(serde_json::Value, i64), serde_json::Error> {
744 use serde::de::Error as _;
745 let serde_json::Value::Object(mut fields) = value else {
746 return Err(serde_json::Error::custom(
747 "a stamped operation is an object",
748 ));
749 };
750 let operation = fields
751 .remove("op")
752 .ok_or_else(|| serde_json::Error::missing_field("op"))?;
753 let now_ms = match fields.remove("at") {
754 None | Some(serde_json::Value::Null) => 0,
755 Some(at) => i64::deserialize(at)?,
756 };
757 Ok((operation, now_ms))
758}
759
760fn settles(operation: &impl Operation) -> bool {
763 matches!(
764 operation.edit().map(crate::Edit::op),
765 Some(crate::EditOp::Settle { .. } | crate::EditOp::Forget { .. })
766 )
767}
768
769#[inline(never)]
772fn on_copy(doc: &Doc, apply: &mut dyn FnMut(&mut Doc)) {
773 let mut copy = doc.clone();
774 apply(&mut copy);
775}
776
777impl<O: Operation> Stamped<O> {
778 fn compensated(&self) -> bool {
783 if settles(&self.operation)
786 || matches!(
787 self.operation.change_kind(),
788 tilo_actions::ChangeKind::External | tilo_actions::ChangeKind::Housekeeping
789 )
790 {
791 return false;
792 }
793 O::QUEUES || (self.operation.edit().is_none() && self.operation.compensates())
794 }
795
796 fn applied_to_copy(&self, doc: &Doc) -> Option<(O::Record, Vec<Id>)> {
800 let payload = serde_json::to_vec(self).ok()?;
801 if let Some(edit) = self.operation.edit() {
802 let mut cx = ActionCx::for_apply(doc, &payload, self.now_ms);
803 cx.preview = true;
804 let mut after = None;
805 on_copy(doc, &mut |copy| {
806 after = edit
807 .apply(copy, &mut cx)
808 .ok()
809 .and_then(|()| O::Record::read_fields(copy, &ROOT).ok());
810 });
811 return Some((after?, cx.ids));
812 }
813 let mut after = O::Record::read_fields(doc, &ROOT).ok()?;
814 let mut cx = ActionCx::for_apply(doc, &payload, self.now_ms);
815 cx.preview = true;
816 let minting = MintScope::enter(&cx);
817 let performed = self.operation.perform(&mut after, &mut cx);
818 drop(minting);
819 performed.ok()?;
820 Some((after, cx.ids))
821 }
822
823 fn compensation(&self, doc: &Doc) -> Option<tilo_actions::EncodedAction> {
828 if !self.compensated() {
829 return None;
830 }
831 let before = O::Record::read_fields(doc, &ROOT).ok()?;
832 let (after, minted) = self.applied_to_copy(doc)?;
833 if self.operation.edit().is_none() && self.operation.compensates() {
834 let operation = self
837 .operation
838 .compensation(&before, &after, &minted)?
839 .ok()?;
840 let undo = Self {
841 operation,
842 now_ms: self.now_ms,
843 };
844 return tilo_actions::EncodedAction::encode(O::KIND, &undo).ok();
845 }
846 let mut restore: Vec<crate::Edit<()>> = Vec::new();
847 crate::Model::diff(&after, &before, &[], &mut restore);
848 let mut members = Vec::with_capacity(restore.len());
849 for edit in restore {
850 members.push(Self {
851 operation: O::field_edit(edit.retyped())?,
852 now_ms: self.now_ms,
853 });
854 }
855 let restore = match members.len() {
856 0 => return None,
857 1 => tilo_actions::EncodedAction::encode(O::KIND, &members.pop()?).ok()?,
858 _ => tilo_actions::EncodedAction::encode(
859 crate::group::group_type_of(O::KIND),
860 &crate::ActionGroup { actions: members },
861 )
862 .ok()?,
863 };
864 if serde_json::to_vec(&restore).ok()?.len() <= tilo_actions::context::COMPENSATION_BUDGET {
865 return Some(restore);
866 }
867 let reverting = Reverting::<O> {
870 actor: doc.get_actor().to_hex_string(),
871 deps: doc
872 .committed_heads()
873 .iter()
874 .map(ToString::to_string)
875 .collect(),
876 now_ms: self.now_ms,
877 operation: PhantomData,
878 };
879 tilo_actions::EncodedAction::encode(reverting_type(O::KIND), &reverting).ok()
880 }
881}
882
883pub fn reverting_type(kind: &str) -> String {
885 format!("{kind}+revert")
886}
887
888#[derive(Serialize)]
894#[serde(bound = "")]
895pub struct Reverting<O> {
896 actor: String,
897 deps: Vec<String>,
898 #[serde(rename = "at", default)]
899 now_ms: i64,
900 #[serde(skip)]
901 operation: PhantomData<O>,
902}
903
904impl<'de, O> Deserialize<'de> for Reverting<O> {
906 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
907 let value = serde_json::Value::deserialize(deserializer)?;
908 let (actor, deps, now_ms) = match reverted(value) {
909 Ok(target) => target,
910 Err(error) => return Err(serde::de::Error::custom(error)),
911 };
912 Ok(Self {
913 actor,
914 deps,
915 now_ms,
916 operation: PhantomData,
917 })
918 }
919}
920
921#[inline(never)]
923fn reverted(value: serde_json::Value) -> Result<(String, Vec<String>, i64), serde_json::Error> {
924 #[derive(Deserialize)]
925 struct Form {
926 actor: String,
927 deps: Vec<String>,
928 #[serde(rename = "at", default)]
929 now_ms: i64,
930 }
931 let form = Form::deserialize(value)?;
932 Ok((form.actor, form.deps, form.now_ms))
933}
934
935impl<O> std::fmt::Debug for Reverting<O> {
936 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
937 f.debug_struct("Reverting")
938 .field("actor", &self.actor)
939 .field("deps", &self.deps)
940 .finish_non_exhaustive()
941 }
942}
943
944impl<O: Operation> Reverting<O> {
945 fn change(&self, doc: &mut Doc) -> Result<automerge::ChangeHash, ActionError> {
948 reverted_change(&self.actor, &self.deps, doc)
949 }
950}
951
952#[inline(never)]
954fn reverted_change(
955 actor: &str,
956 deps: &[String],
957 doc: &mut Doc,
958) -> Result<automerge::ChangeHash, ActionError> {
959 let refused = |why: &str| ActionError::Refused(why.into());
960 let mut deps = deps
961 .iter()
962 .map(|hash| hash.parse())
963 .collect::<Result<Vec<automerge::ChangeHash>, _>>()
964 .map_err(|_| refused("a reverted change names invalid heads"))?;
965 deps.compact_sort();
966 doc.get_changes(&deps)
967 .into_iter()
968 .find(|change| {
969 change.actor_id().to_hex_string() == actor && {
970 let mut of = change.deps().to_vec();
971 of.compact_sort();
972 of == deps
973 }
974 })
975 .map(|change| change.hash())
976 .ok_or_else(|| refused("the change to take back is not in this document"))
977}
978
979impl<O: Operation> tilo_actions::Action for Reverting<O> {
980 fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
981 let change = self.change(doc)?;
982 let payload = serde_json::to_vec(self).map_err(ActionError::Encode)?;
983 revert(
984 &ResourceOf::<O::Record>::OPS,
985 &|record, before, cx| {
986 if let (Some(record), Some(before)) = (
987 record.downcast_mut::<O::Record>(),
988 before.downcast_ref::<O::Record>(),
989 ) {
990 O::queue(record, before, cx);
991 }
992 },
993 (change, &payload, self.now_ms),
994 doc,
995 )
996 }
997
998 fn locus(&self) -> ExecutionLocus {
999 ExecutionLocus::ClientLocal
1000 }
1001}
1002
1003fn revert(
1006 record: &ResourceOps,
1007 queue: &dyn Fn(&mut dyn Any, &dyn Any, &mut ActionCx),
1008 (change, payload, now_ms): (automerge::ChangeHash, &[u8], i64),
1009 doc: &mut Doc,
1010) -> Result<(), ActionError> {
1011 let deps: Vec<automerge::ChangeHash> = doc
1012 .get_change_meta_by_hash(&change)
1013 .map(|meta| meta.deps)
1014 .unwrap_or_default();
1015 let before = {
1016 let at = doc.committed_fork_at(&deps).map_err(automerge_refused)?;
1017 (record.read)(&at).map_err(model_refused)?
1018 };
1019 let after = {
1020 let at = doc
1021 .committed_fork_at(&[change])
1022 .map_err(automerge_refused)?;
1023 (record.read)(&at).map_err(model_refused)?
1024 };
1025 let restore = (record.diff)(after.as_ref(), before.as_ref());
1026 let mut cx = ActionCx::for_apply(doc, payload, now_ms);
1027 let current = (record.read)(doc).map_err(model_refused)?;
1028 for edit in &restore {
1029 (record.edit)(edit, doc, &mut cx).map_err(model_refused)?;
1030 }
1031 let mut written = (record.read)(doc).map_err(model_refused)?;
1032 let minting = MintScope::enter(&cx);
1033 queue(written.as_mut(), current.as_ref(), &mut cx);
1034 drop(minting);
1035 (record.write)(written.as_ref(), doc).map_err(model_refused)
1036}
1037
1038type WriteChanged =
1041 fn(&dyn Any, &dyn Any, &mut Doc, &crate::Delta) -> Result<(), crate::ModelError>;
1042
1043pub(crate) struct ResourceOps {
1047 shape: crate::Shape,
1048 name: fn() -> &'static str,
1049 kind: fn() -> std::any::TypeId,
1050 read: fn(&Doc) -> Result<Box<dyn Any>, crate::ModelError>,
1051 write: fn(&dyn Any, &mut Doc) -> Result<(), crate::ModelError>,
1052 write_changed: WriteChanged,
1053 check: fn(&dyn Any) -> Result<(), Refusal>,
1054 refresh: fn(&mut dyn Any, &Doc, &crate::Delta) -> bool,
1055 diff: fn(&dyn Any, &dyn Any) -> Vec<crate::Edit<()>>,
1057 edit: fn(&crate::Edit<()>, &mut Doc, &mut ActionCx) -> Result<(), crate::ModelError>,
1058}
1059
1060fn resource_of<R: 'static>(record: &dyn Any) -> Result<&R, crate::ModelError> {
1062 match record.downcast_ref::<R>() {
1063 Some(record) => Ok(record),
1064 None => Err(crate::ModelError::invalid("a record of another type")),
1065 }
1066}
1067
1068fn read_resource<R: Fields + 'static>(doc: &Doc) -> Result<Box<dyn Any>, crate::ModelError> {
1069 match R::read_fields(doc, &ROOT) {
1070 Ok(record) => Ok(Box::new(record)),
1071 Err(error) => Err(error),
1072 }
1073}
1074
1075fn write_resource<R: Fields + 'static>(
1076 record: &dyn Any,
1077 doc: &mut Doc,
1078) -> Result<(), crate::ModelError> {
1079 resource_of::<R>(record)?.write_fields(doc, &ROOT)
1080}
1081
1082fn write_changed_resource<R: Fields + 'static>(
1083 record: &dyn Any,
1084 kept: &dyn Any,
1085 doc: &mut Doc,
1086 dirty: &crate::Delta,
1087) -> Result<(), crate::ModelError> {
1088 resource_of::<R>(record)?.write_changed_fields(resource_of::<R>(kept)?, doc, &ROOT, dirty)
1089}
1090
1091fn check_resource<R: Fields + 'static>(record: &dyn Any) -> Result<(), Refusal> {
1092 match record.downcast_ref::<R>() {
1093 Some(record) => crate::Model::check(record),
1094 None => Err(Refusal::new("a record of another type")),
1095 }
1096}
1097
1098fn refresh_resource<R: Fields + 'static>(
1099 record: &mut dyn Any,
1100 doc: &Doc,
1101 delta: &crate::Delta,
1102) -> bool {
1103 match record.downcast_mut::<R>() {
1104 Some(record) => record.refresh_fields(doc, &ROOT, delta).is_ok(),
1105 None => false,
1106 }
1107}
1108
1109fn diff_resources<R: Fields + 'static>(from: &dyn Any, to: &dyn Any) -> Vec<crate::Edit<()>> {
1110 let mut edits = Vec::new();
1111 if let (Some(from), Some(to)) = (from.downcast_ref::<R>(), to.downcast_ref::<R>()) {
1112 crate::Model::diff(from, to, &[], &mut edits);
1113 }
1114 edits
1115}
1116
1117fn edit_resource<R: Fields + 'static>(
1118 edit: &crate::Edit<()>,
1119 doc: &mut Doc,
1120 cx: &mut ActionCx,
1121) -> Result<(), crate::ModelError> {
1122 R::edit_fields(doc, &ROOT, edit.path(), edit.op(), cx)
1123}
1124
1125pub(crate) struct ResourceOf<R>(PhantomData<R>);
1126
1127impl<R: Fields + 'static> ResourceOf<R> {
1128 pub(crate) const OPS: ResourceOps = ResourceOps {
1129 shape: <R as crate::Model>::SHAPE,
1130 name: std::any::type_name::<R>,
1131 kind: std::any::TypeId::of::<R>,
1132 read: read_resource::<R>,
1133 write: write_resource::<R>,
1134 write_changed: write_changed_resource::<R>,
1135 check: check_resource::<R>,
1136 refresh: refresh_resource::<R>,
1137 diff: diff_resources::<R>,
1138 edit: edit_resource::<R>,
1139 };
1140}
1141
1142fn apply_edit(
1144 operation: &dyn Performs,
1145 doc: &mut Doc,
1146 cx: &mut ActionCx,
1147) -> Result<(), ActionError> {
1148 match operation.apply_edit(doc, cx) {
1149 Some(applied) => applied.map_err(model_refused),
1150 None => Ok(()),
1151 }
1152}
1153
1154trait Performs {
1156 fn is_edit(&self) -> bool;
1157 fn apply_edit(&self, doc: &mut Doc, cx: &mut ActionCx)
1159 -> Option<Result<(), crate::ModelError>>;
1160 fn queues(&self) -> bool;
1161 fn perform(&self, record: &mut dyn Any, cx: &mut ActionCx) -> Result<(), Refusal>;
1162 fn queue(&self, record: &mut dyn Any, before: &dyn Any, cx: &mut ActionCx);
1163 fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>>;
1164 fn writes(&self) -> crate::footprint::Writes;
1165 fn snapshot(&self, record: &dyn Any) -> Option<Box<dyn Any>>;
1166}
1167
1168impl<O: Operation> Performs for O {
1169 fn is_edit(&self) -> bool {
1170 self.edit().is_some()
1171 }
1172
1173 fn apply_edit(
1174 &self,
1175 doc: &mut Doc,
1176 cx: &mut ActionCx,
1177 ) -> Option<Result<(), crate::ModelError>> {
1178 let edit = self.edit()?;
1179 Some(O::Record::edit_fields(
1180 doc,
1181 &ROOT,
1182 edit.path(),
1183 edit.op(),
1184 cx,
1185 ))
1186 }
1187
1188 fn queues(&self) -> bool {
1189 O::QUEUES && !settles(self)
1190 }
1191
1192 fn perform(&self, record: &mut dyn Any, cx: &mut ActionCx) -> Result<(), Refusal> {
1193 match record.downcast_mut::<O::Record>() {
1194 Some(record) => Operation::perform(self, record, cx),
1195 None => Err(Refusal::new("a record of another type")),
1196 }
1197 }
1198
1199 fn queue(&self, record: &mut dyn Any, before: &dyn Any, cx: &mut ActionCx) {
1200 if let (Some(record), Some(before)) = (
1201 record.downcast_mut::<O::Record>(),
1202 before.downcast_ref::<O::Record>(),
1203 ) {
1204 O::queue(record, before, cx);
1205 }
1206 }
1207
1208 fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>> {
1209 Operation::perform_item(self, doc, cx)
1210 }
1211
1212 fn writes(&self) -> crate::footprint::Writes {
1213 Operation::writes(self)
1214 }
1215
1216 fn snapshot(&self, record: &dyn Any) -> Option<Box<dyn Any>> {
1217 let record = record.downcast_ref::<O::Record>()?;
1218 O::snapshot(record).map(|record| Box::new(record) as Box<dyn Any>)
1219 }
1220}
1221
1222fn apply_edit_queued(
1225 record: &'static ResourceOps,
1226 operation: &dyn Performs,
1227 doc: &mut Doc,
1228 cx: &mut ActionCx,
1229) -> Result<(), ActionError> {
1230 if !operation.queues() {
1231 return apply_edit(operation, doc, cx);
1232 }
1233 let before = (record.read)(doc).map_err(model_refused)?;
1234 apply_edit(operation, doc, cx)?;
1235 let mut after = (record.read)(doc).map_err(model_refused)?;
1236 let minting = MintScope::enter(cx);
1237 operation.queue(after.as_mut(), before.as_ref(), cx);
1238 drop(minting);
1239 (record.write)(after.as_ref(), doc).map_err(model_refused)
1240}
1241
1242fn read_whole(ops: &'static ResourceOps, doc: &Doc) -> Result<Box<dyn Any>, ActionError> {
1245 let _whole = crate::profiling::Phase::start("resource.apply_whole_read");
1246 (ops.read)(doc).map_err(model_refused)
1247}
1248
1249fn apply_operation(
1259 record: &'static ResourceOps,
1260 operation: &dyn Performs,
1261 (payload, now_ms): (&[u8], i64),
1262 doc: &mut Doc,
1263) -> Result<(), ActionError> {
1264 if crate::group::current_member().is_none() {
1266 start_minting();
1267 }
1268 let mut cx = ActionCx::for_apply(doc, payload, now_ms);
1269 let shape = record.shape;
1270 let units = crate::footprint::has_units(shape);
1271 let index = |doc: &mut Doc| {
1274 if units {
1275 crate::footprint::index(doc, shape).map_err(automerge_refused)?;
1276 }
1277 Ok::<(), ActionError>(())
1278 };
1279 let queues = operation.queues();
1280 let grouping = crate::group::grouping();
1284 if grouping {
1285 if !operation.is_edit() && !queues && held::holds(record) {
1286 return held::perform(record, operation, &mut cx);
1287 }
1288 held::flush(record, doc)?;
1289 }
1290 if operation.is_edit() {
1291 apply_edit_queued(record, operation, doc, &mut cx)?;
1292 return index(doc);
1293 }
1294 if !queues {
1297 let minting = MintScope::enter(&cx);
1298 let performed = operation.perform_item(doc, &mut cx);
1299 drop(minting);
1300 if let Some(performed) = performed {
1301 performed.map_err(refusal_refused)?;
1302 return index(doc);
1303 }
1304 }
1305 let committed = automerge::transaction::Transactable::pending_ops(doc) == 0;
1308 let started = automerge::transaction::Transactable::base_heads(doc);
1309 let (mut current, dirty) =
1310 match crate::apply_cache::take_any((record.kind)(), doc, &record.refresh) {
1311 Some((warm, dirty)) => (warm, Some(dirty)),
1312 None => (read_whole(record, doc)?, None),
1313 };
1314 if grouping && !queues {
1317 let base = operation.snapshot(current.as_ref());
1319 held::start(record, current, base, dirty);
1320 return held::perform(record, operation, &mut cx);
1321 }
1322 let kept = if committed || queues || units || dirty.is_some() {
1325 operation.snapshot(current.as_ref())
1326 } else {
1327 None
1328 };
1329 let read_before;
1330 let before: Option<&dyn Any> = match (&kept, queues || units) {
1331 (_, false) => None,
1332 (Some(kept), true) => Some(kept.as_ref()),
1333 (None, true) => {
1334 read_before = (record.read)(doc).map_err(model_refused)?;
1335 Some(read_before.as_ref())
1336 }
1337 };
1338 let minting = MintScope::enter(&cx);
1339 let performed = operation.perform(current.as_mut(), &mut cx);
1340 if let (Ok(()), Some(before), true) = (&performed, before, queues) {
1341 operation.queue(current.as_mut(), before, &mut cx);
1342 }
1343 drop(minting);
1344 performed.map_err(refusal_refused)?;
1345 if grouping {
1346 crate::group::check_or_defer(format!("{}@root", (record.name)()), doc, move |doc| {
1348 match (record.read)(doc) {
1349 Ok(read) => (record.check)(read.as_ref()),
1350 Err(error) => Err(Refusal::new(error.to_string())),
1351 }
1352 })
1353 .map_err(refusal_refused)?;
1354 } else {
1355 (record.check)(current.as_ref()).map_err(refusal_refused)?;
1356 }
1357 if let (Some(before), true) = (before, units) {
1358 let edits = (record.diff)(before, current.as_ref());
1359 crate::footprint::check_edits(shape, &edits, &operation.writes())
1360 .map_err(refusal_refused)?;
1361 }
1362 crate::apply_cache::begin_storing();
1363 match (&kept, &dirty) {
1364 (Some(kept), Some(dirty)) => {
1365 (record.write_changed)(current.as_ref(), kept.as_ref(), doc, dirty)
1366 }
1367 _ => (record.write)(current.as_ref(), doc),
1368 }
1369 .map_err(model_refused)?;
1370 index(doc)?;
1371 crate::apply_cache::seal_stored(doc);
1372 if committed {
1376 if let Some(kept) = kept {
1377 crate::apply_cache::keep_any((record.kind)(), kept, doc, &started);
1378 }
1379 } else {
1380 crate::apply_cache::keep_open((record.kind)(), current, doc);
1381 }
1382 Ok(())
1383}
1384
1385mod held {
1391 use std::any::{Any, TypeId};
1392 use std::cell::RefCell;
1393
1394 use tilo_actions::ActionError;
1395
1396 use super::{ActionCx, MintScope, Performs, ResourceOps, model_refused, refusal_refused};
1397 use crate::footprint::Footprints;
1398 use crate::model::Doc;
1399
1400 struct Held {
1401 record: &'static ResourceOps,
1402 current: Box<dyn Any>,
1404 base: Option<Box<dyn Any>>,
1407 dirty: Option<crate::Delta>,
1410 footprints: Footprints,
1412 }
1413
1414 thread_local! {
1415 static HELD: RefCell<Option<Vec<Held>>> = const { RefCell::new(None) };
1417 }
1418
1419 pub(crate) fn begin() {
1421 HELD.with(|held| *held.borrow_mut() = Some(Vec::new()));
1422 }
1423
1424 pub(crate) fn end() {
1426 HELD.with(|held| held.borrow_mut().take());
1427 }
1428
1429 fn kind(record: &ResourceOps) -> TypeId {
1430 (record.kind)()
1431 }
1432
1433 pub(super) fn holds(record: &ResourceOps) -> bool {
1435 HELD.with(|held| {
1436 held.borrow()
1437 .as_ref()
1438 .is_some_and(|held| held.iter().any(|entry| kind(entry.record) == kind(record)))
1439 })
1440 }
1441
1442 pub(super) fn start(
1444 record: &'static ResourceOps,
1445 current: Box<dyn Any>,
1446 base: Option<Box<dyn Any>>,
1447 dirty: Option<crate::Delta>,
1448 ) {
1449 HELD.with(|held| {
1450 if let Some(held) = held.borrow_mut().as_mut() {
1451 held.push(Held {
1452 record,
1453 current,
1454 base,
1455 dirty,
1456 footprints: Footprints::default(),
1457 });
1458 }
1459 });
1460 }
1461
1462 pub(super) fn perform(
1464 record: &'static ResourceOps,
1465 operation: &dyn Performs,
1466 cx: &mut ActionCx,
1467 ) -> Result<(), ActionError> {
1468 HELD.with(|held| {
1469 let mut held = held.borrow_mut();
1470 let entry = held
1471 .as_mut()
1472 .and_then(|held| {
1473 held.iter_mut()
1474 .find(|entry| kind(entry.record) == kind(record))
1475 })
1476 .ok_or_else(|| ActionError::Refused("the group does not hold the record".into()))?;
1477 let minting = MintScope::enter(cx);
1478 let performed = operation.perform(entry.current.as_mut(), cx);
1479 drop(minting);
1480 performed.map_err(refusal_refused)?;
1481 entry.footprints.add(&operation.writes());
1482 Ok(())
1483 })
1484 }
1485
1486 pub(super) fn flush(record: &ResourceOps, doc: &mut Doc) -> Result<(), ActionError> {
1489 let taken = HELD.with(|held| {
1490 let mut held = held.borrow_mut();
1491 let held = held.as_mut()?;
1492 let at = held
1493 .iter()
1494 .position(|entry| kind(entry.record) == kind(record))?;
1495 Some(held.remove(at))
1496 });
1497 match taken {
1498 Some(entry) => write(entry, doc, Checked::AtTheEnd),
1499 None => Ok(()),
1500 }
1501 }
1502
1503 pub(crate) fn flush_all(doc: &mut Doc) -> Result<(), ActionError> {
1505 let taken = HELD.with(|held| held.borrow_mut().as_mut().map(std::mem::take));
1506 for entry in taken.unwrap_or_default() {
1507 write(entry, doc, Checked::Now)?;
1508 }
1509 Ok(())
1510 }
1511
1512 #[derive(Clone, Copy)]
1514 enum Checked {
1515 Now,
1517 AtTheEnd,
1519 }
1520
1521 fn write(entry: Held, doc: &mut Doc, checked: Checked) -> Result<(), ActionError> {
1522 let Held {
1523 record,
1524 current,
1525 base,
1526 dirty,
1527 footprints,
1528 } = entry;
1529 let units = crate::footprint::has_units(record.shape);
1530 let read_base;
1531 let before: Option<&dyn Any> = match (&base, units) {
1532 (_, false) => None,
1533 (Some(base), true) => Some(base.as_ref()),
1534 (None, true) => {
1535 read_base = (record.read)(doc).map_err(model_refused)?;
1536 Some(read_base.as_ref())
1537 }
1538 };
1539 match checked {
1541 Checked::Now => (record.check)(current.as_ref()).map_err(refusal_refused)?,
1542 Checked::AtTheEnd => {
1543 crate::group::check_or_defer(
1544 format!("{}@root", (record.name)()),
1545 doc,
1546 move |doc| match (record.read)(doc) {
1547 Ok(read) => (record.check)(read.as_ref()),
1548 Err(error) => Err(crate::Refusal::new(error.to_string())),
1549 },
1550 )
1551 .map_err(refusal_refused)?;
1552 }
1553 }
1554 if let Some(before) = before {
1555 let edits = (record.diff)(before, current.as_ref());
1556 crate::footprint::check_edits_of(record.shape, &edits, &footprints)
1557 .map_err(refusal_refused)?;
1558 }
1559 crate::apply_cache::begin_storing();
1560 match (&base, &dirty) {
1561 (Some(base), Some(dirty)) => {
1562 (record.write_changed)(current.as_ref(), base.as_ref(), doc, dirty)
1563 }
1564 _ => (record.write)(current.as_ref(), doc),
1565 }
1566 .map_err(model_refused)?;
1567 if units {
1568 crate::footprint::index(doc, record.shape).map_err(super::automerge_refused)?;
1569 }
1570 crate::apply_cache::seal_stored(doc);
1571 crate::apply_cache::keep_open((record.kind)(), current, doc);
1573 Ok(())
1574 }
1575}
1576
1577pub(crate) use held::{begin as hold_records, end as drop_held, flush_all as write_held};
1578
1579impl<O: Operation> tilo_actions::Action for Stamped<O> {
1580 fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
1583 let payload = serde_json::to_vec(self).map_err(ActionError::Encode)?;
1584 apply_operation(
1585 &ResourceOf::<O::Record>::OPS,
1586 &self.operation,
1587 (&payload, self.now_ms),
1588 doc,
1589 )
1590 }
1591
1592 fn locus(&self) -> ExecutionLocus {
1593 ExecutionLocus::ClientLocal
1594 }
1595
1596 fn risk(&self) -> RiskLevel {
1597 self.operation.risk()
1598 }
1599
1600 fn change_kind(&self) -> tilo_actions::ChangeKind {
1604 match self.operation.edit().map(crate::Edit::op) {
1605 Some(crate::EditOp::Settle { .. }) => tilo_actions::ChangeKind::External,
1606 Some(crate::EditOp::Forget { .. }) => tilo_actions::ChangeKind::Housekeeping,
1607 _ => self.operation.change_kind(),
1608 }
1609 }
1610
1611 fn action_kind(&self) -> ActionKind {
1612 self.operation.kind()
1613 }
1614
1615 fn incoming_message(&self) -> bool {
1616 self.operation.incoming_message()
1617 }
1618
1619 fn irreversible(&self) -> bool {
1620 self.operation.irreversible()
1621 }
1622
1623 fn inverse_encoded(&self, doc: &Doc) -> Option<tilo_actions::EncodedAction> {
1627 self.compensation(doc)
1628 }
1629
1630 fn compensates(&self) -> bool {
1631 self.compensated()
1632 }
1633
1634 fn describe(&self, doc: &Doc) -> Option<tilo_actions::Described> {
1637 let shape = <O::Record as crate::Model>::SHAPE;
1638 if let Some(edit) = self.operation.edit() {
1639 return crate::describe::edit(doc, shape, edit);
1640 }
1641 let value = crate::__private::json_via_bytes(&self.operation).ok()?;
1642 crate::describe::verb(doc, shape, O::KIND, &value)
1643 }
1644
1645 fn made(&self, doc: &Doc) -> Option<tilo_actions::ActionItem> {
1650 crate::describe::made::<O::Record>(doc)
1651 }
1652}
1653
1654pub struct ActionRef<R, A> {
1666 pub id: &'static str,
1667 pub params: &'static [&'static str],
1668 kind: ResourceKind,
1671 marker: PhantomData<fn(A) -> R>,
1672}
1673
1674impl<R, A> Clone for ActionRef<R, A> {
1675 fn clone(&self) -> Self {
1676 *self
1677 }
1678}
1679impl<R, A> Copy for ActionRef<R, A> {}
1680
1681impl<R, A> std::fmt::Debug for ActionRef<R, A> {
1682 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1683 f.debug_struct("ActionRef")
1684 .field("id", &self.id)
1685 .field("params", &self.params)
1686 .field("kind", &self.kind())
1687 .finish_non_exhaustive()
1688 }
1689}
1690
1691impl<R, A> ActionRef<R, A> {
1692 #[must_use]
1694 pub const fn id(&self) -> &'static str {
1695 self.id
1696 }
1697
1698 #[must_use]
1700 pub const fn params(&self) -> &'static [&'static str] {
1701 self.params
1702 }
1703
1704 #[must_use]
1706 pub const fn kind(&self) -> &ResourceKind {
1707 &self.kind
1708 }
1709
1710 #[must_use]
1714 pub fn key(&self) -> ActionKey {
1715 ActionKey::new(self.kind.declaring_app(), self.kind.kind(), self.id)
1716 }
1717}
1718
1719impl<E: crate::Effect, A> ActionRef<E, A> {
1720 #[must_use]
1724 pub fn spec(&self) -> Option<tilo_actions::ActionSpec> {
1725 E::spec(self.id)
1726 }
1727
1728 pub fn binding(
1737 &self,
1738 resource: impl Into<String>,
1739 ) -> Result<tilo_actions::ActionBinding<()>, tilo_actions::ActionBindingError> {
1740 let resource = resource.into();
1741 let spec = E::spec(self.id).ok_or_else(|| {
1742 tilo_actions::ActionBindingError::ActionNotExported {
1743 resource: resource.clone(),
1744 action: self.id.to_owned(),
1745 }
1746 })?;
1747 tilo_actions::ActionBinding::declared(resource, spec)
1748 }
1749}
1750
1751impl<R, A: Serialize> ActionRef<R, A> {
1752 #[must_use]
1757 pub const fn new(
1758 id: &'static str,
1759 params: &'static [&'static str],
1760 kind: ResourceKind,
1761 ) -> Self {
1762 Self {
1763 id,
1764 params,
1765 kind,
1766 marker: PhantomData,
1767 }
1768 }
1769
1770 #[must_use]
1776 pub fn on(&self, resource: impl Into<String>) -> tilo_actions::ActionAddress {
1777 tilo_actions::ActionAddress::new(resource, self.id)
1778 }
1779
1780 pub fn arguments(
1783 &self,
1784 input: &A,
1785 ) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1786 bind_serialized(
1789 self.id,
1790 self.params,
1791 crate::__private::json_via_bytes(input),
1792 )
1793 }
1794
1795 pub fn with(&self, input: impl Into<A>) -> Invoke<R> {
1801 Invoke::bound(self.id, self.arguments(&input.into()))
1802 }
1803
1804 pub fn try_with(&self, input: impl Into<A>) -> Result<Invoke<R>, String> {
1806 let invoke = self.with(input);
1807 match invoke.refusal {
1808 Some(refusal) => Err(refusal),
1809 None => Ok(invoke),
1810 }
1811 }
1812}
1813
1814#[inline(never)]
1817fn bind_serialized(
1818 id: &'static str,
1819 params: &'static [&'static str],
1820 value: Result<serde_json::Value, serde_json::Error>,
1821) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1822 match value {
1823 Ok(value) => bind_arguments(id, params, value),
1824 Err(error) => Err(format!("`{id}`: {error}")),
1825 }
1826}
1827
1828fn bind_arguments(
1831 id: &str,
1832 params: &[&str],
1833 value: serde_json::Value,
1834) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1835 let given = |fields: Vec<(String, serde_json::Value)>| {
1837 fields
1838 .into_iter()
1839 .filter(|(_, value)| !value.is_null())
1840 .collect()
1841 };
1842 match (params, value) {
1843 ([], serde_json::Value::Object(fields)) => Ok(given(fields.into_iter().collect())),
1844 ([], serde_json::Value::Null) => Ok(serde_json::Map::new()),
1845 ([], other) => Err(format!("`{id}` takes named arguments, not `{other}`")),
1846 ([single], value) => Ok(given(vec![((*single).to_owned(), value)])),
1847 (names, serde_json::Value::Array(values)) if values.len() == names.len() => Ok(given(
1848 names
1849 .iter()
1850 .map(|name| (*name).to_owned())
1851 .zip(values)
1852 .collect(),
1853 )),
1854 (names, other) => Err(format!(
1855 "`{id}` takes {} arguments ({}), not `{other}`",
1856 names.len(),
1857 names.join(", ")
1858 )),
1859 }
1860}
1861
1862impl<R, A: Serialize> ActionRef<R, A> {
1863 pub fn map<I, T, F>(self, map: F) -> Mapped<R, A, F>
1866 where
1867 F: Fn(I) -> T,
1868 T: Into<A>,
1869 {
1870 Mapped { action: self, map }
1871 }
1872
1873 pub fn try_map<I, T, F>(self, parse: F) -> TryMapped<R, A, F>
1883 where
1884 F: Fn(I) -> Option<T>,
1885 T: Into<A>,
1886 {
1887 TryMapped {
1888 action: self,
1889 parse,
1890 }
1891 }
1892}
1893
1894pub struct TryMapped<R, A, F> {
1897 action: ActionRef<R, A>,
1898 parse: F,
1899}
1900
1901impl<R, A, F: Clone> Clone for TryMapped<R, A, F> {
1902 fn clone(&self) -> Self {
1903 Self {
1904 action: self.action,
1905 parse: self.parse.clone(),
1906 }
1907 }
1908}
1909
1910pub struct Mapped<R, A, F> {
1912 action: ActionRef<R, A>,
1913 map: F,
1914}
1915
1916impl<R, A, F: Clone> Clone for Mapped<R, A, F> {
1917 fn clone(&self) -> Self {
1918 Self {
1919 action: self.action,
1920 map: self.map.clone(),
1921 }
1922 }
1923}
1924
1925pub trait Binds<R, I>: Send + Sync + 'static {
1928 fn action_id(&self) -> &'static str;
1929
1930 fn action_key(&self) -> ActionKey
1935 where
1936 R: Resource,
1937 {
1938 ActionKey::new(R::APP_ID, R::KIND, self.action_id())
1939 }
1940
1941 fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String>;
1946}
1947
1948impl<R: 'static, A: Serialize + 'static, I: Into<A>> Binds<R, I> for ActionRef<R, A> {
1951 fn action_id(&self) -> &'static str {
1952 self.id
1953 }
1954 fn action_key(&self) -> ActionKey {
1955 ActionRef::key(self)
1956 }
1957 fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1958 ActionRef::arguments(self, &input.into())
1959 }
1960}
1961
1962impl<R, A, I, T, F> Binds<R, I> for Mapped<R, A, F>
1963where
1964 R: 'static,
1965 A: Serialize + 'static,
1966 T: Into<A>,
1967 F: Fn(I) -> T + Send + Sync + 'static,
1968{
1969 fn action_id(&self) -> &'static str {
1970 self.action.id
1971 }
1972 fn action_key(&self) -> ActionKey {
1973 ActionRef::key(&self.action)
1974 }
1975 fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1976 self.action.arguments(&(self.map)(input).into())
1977 }
1978}
1979
1980impl<R, A, I, T, F> Binds<R, I> for TryMapped<R, A, F>
1981where
1982 R: 'static,
1983 A: Serialize + 'static,
1984 T: Into<A>,
1985 F: Fn(I) -> Option<T> + Send + Sync + 'static,
1986{
1987 fn action_id(&self) -> &'static str {
1988 self.action.id
1989 }
1990 fn action_key(&self) -> ActionKey {
1991 ActionRef::key(&self.action)
1992 }
1993 fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1994 let Some(parsed) = (self.parse)(input) else {
1995 return Err(no_arguments(self.action.id));
1996 };
1997 self.action.arguments(&parsed.into())
1998 }
1999}
2000
2001#[inline(never)]
2004fn no_arguments(id: &str) -> String {
2005 format!("the input makes no arguments for `{id}`")
2006}
2007
2008pub trait NoParams {}
2011
2012impl NoParams for () {}
2013
2014pub trait Params: Serialize + DeserializeOwned + crate::JsonSchema + Clone + 'static {
2018 type Resource;
2020 type Paths: Clone;
2022 const ACTION: ActionRef<Self::Resource, Self>;
2024
2025 fn paths() -> Self::Paths;
2027}
2028
2029impl<R, A: NoParams> ActionRef<R, A> {
2030 pub fn invoke(&self) -> Invoke<R> {
2032 Invoke {
2033 id: self.id,
2034 arguments: serde_json::Map::new(),
2035 refusal: None,
2036 effect: false,
2037 on: None,
2038 marker: PhantomData,
2039 }
2040 }
2041}
2042
2043pub struct Invoke<R> {
2046 pub id: &'static str,
2047 pub arguments: serde_json::Map<String, serde_json::Value>,
2048 refusal: Option<String>,
2050 effect: bool,
2051 on: Option<String>,
2053 marker: PhantomData<fn() -> R>,
2054}
2055
2056impl<R> Clone for Invoke<R> {
2057 fn clone(&self) -> Self {
2058 Self {
2059 id: self.id,
2060 arguments: self.arguments.clone(),
2061 refusal: self.refusal.clone(),
2062 effect: self.effect,
2063 on: self.on.clone(),
2064 marker: PhantomData,
2065 }
2066 }
2067}
2068
2069impl<R> std::fmt::Debug for Invoke<R> {
2070 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2071 f.debug_struct("Invoke")
2072 .field("id", &self.id)
2073 .field("arguments", &self.arguments)
2074 .field("refusal", &self.refusal)
2075 .field("effect", &self.effect)
2076 .field("on", &self.on)
2077 .finish()
2078 }
2079}
2080
2081impl<R> Invoke<R> {
2082 pub fn effect<E: crate::Effect>(effect: &E) -> Self {
2091 let id = effect.id();
2092 let refusal = E::declaration(id)
2093 .is_some_and(|declaration| declaration.row)
2094 .then(|| format!("`{id}` is offered only on rows: invoke it on one"));
2095 Self {
2096 id,
2097 arguments: effect.arguments(),
2098 refusal,
2099 effect: true,
2100 on: None,
2101 marker: PhantomData,
2102 }
2103 }
2104
2105 #[must_use]
2108 pub fn on(mut self, row: impl Into<String>) -> Self {
2109 if self.effect {
2110 self.refusal = None;
2111 }
2112 self.on = Some(row.into());
2113 self
2114 }
2115
2116 pub fn row(&self) -> Option<&str> {
2118 self.on.as_deref()
2119 }
2120
2121 #[inline(never)]
2125 pub(crate) fn bound(
2126 id: &'static str,
2127 bound: Result<serde_json::Map<String, serde_json::Value>, String>,
2128 ) -> Self {
2129 let (arguments, refusal) = match bound {
2130 Ok(arguments) => (arguments, None),
2131 Err(refusal) => (serde_json::Map::new(), Some(refusal)),
2132 };
2133 Self {
2134 id,
2135 arguments,
2136 refusal,
2137 effect: false,
2138 on: None,
2139 marker: PhantomData,
2140 }
2141 }
2142
2143 pub fn refusal(&self) -> Option<&str> {
2146 self.refusal.as_deref()
2147 }
2148
2149 pub fn is_effect(&self) -> bool {
2152 self.effect
2153 }
2154
2155 #[must_use]
2158 pub fn address_on(&self, resource: impl Into<String>) -> tilo_actions::ActionAddress {
2159 tilo_actions::ActionAddress::new(resource, self.id)
2160 }
2161}
2162
2163impl<R: Resource> Invoke<R> {
2164 #[must_use]
2166 pub fn address(&self) -> tilo_actions::ActionAddress {
2167 self.address_on(R::KIND)
2168 }
2169
2170 pub fn apply(action: &R::Action) -> Result<Self, serde_json::Error> {
2176 let value = match crate::__private::json_via_bytes(action)? {
2179 serde_json::Value::String(variant) => serde_json::Value::Object(
2180 serde_json::Map::from_iter([(variant, serde_json::Value::Null)]),
2181 ),
2182 value => value,
2183 };
2184 Ok(Self {
2185 id: crate::APPLY,
2186 arguments: serde_json::Map::from_iter([(crate::APPLY_PARAM.to_owned(), value)]),
2187 refusal: None,
2188 effect: false,
2189 on: None,
2190 marker: PhantomData,
2191 })
2192 }
2193
2194 pub fn edit(edit: &crate::Edit<R>) -> Result<Self, serde_json::Error> {
2199 Ok(Self {
2200 id: crate::FIELD_EDIT,
2201 arguments: serde_json::Map::from_iter([(
2202 crate::EDIT_PARAM.to_owned(),
2203 crate::__private::json_via_bytes(edit)?,
2204 )]),
2205 refusal: None,
2206 effect: false,
2207 on: None,
2208 marker: PhantomData,
2209 })
2210 }
2211
2212 fn from_edit(edit: &crate::Edit<R>) -> Self {
2216 Self::edit(edit).unwrap_or_else(|error| Self {
2217 id: crate::FIELD_EDIT,
2218 arguments: serde_json::Map::new(),
2219 refusal: Some(error.to_string()),
2220 effect: false,
2221 on: None,
2222 marker: PhantomData,
2223 })
2224 }
2225
2226 pub fn group(members: impl IntoIterator<Item = Self>) -> Self {
2229 let mut actions = Vec::new();
2230 let mut refusal = None;
2231 for member in members {
2232 if refusal.is_none() {
2233 refusal.clone_from(&member.refusal);
2234 }
2235 if member.is_group() {
2236 if let Some(serde_json::Value::Array(inner)) =
2237 member.arguments.get(crate::GROUP_PARAM)
2238 {
2239 actions.extend(inner.iter().cloned());
2240 }
2241 } else {
2242 actions.push(serde_json::json!({
2243 "action": member.id,
2244 "args": member.arguments,
2245 }));
2246 }
2247 }
2248 Self {
2249 id: crate::GROUP,
2250 arguments: serde_json::Map::from_iter([(
2251 crate::GROUP_PARAM.to_owned(),
2252 serde_json::Value::Array(actions),
2253 )]),
2254 refusal,
2255 effect: false,
2256 on: None,
2257 marker: PhantomData,
2258 }
2259 }
2260
2261 pub fn is_group(&self) -> bool {
2263 self.id == crate::GROUP
2264 }
2265
2266 pub fn build(&self, now_ms: i64) -> Result<R::Action, String> {
2269 if let Some(refusal) = &self.refusal {
2270 return Err(refusal.clone());
2271 }
2272 if let Some(built) = R::build_by_app(self.id, &self.arguments, now_ms) {
2275 return built;
2276 }
2277 crate::resource::build_action::<R>(self.id, &self.arguments, now_ms)
2278 }
2279}
2280
2281impl<R: Resource> From<crate::Edit<R>> for Invoke<R> {
2282 fn from(edit: crate::Edit<R>) -> Self {
2283 Self::from_edit(&edit)
2284 }
2285}
2286
2287impl<R: Resource> From<&crate::Edit<R>> for Invoke<R> {
2288 fn from(edit: &crate::Edit<R>) -> Self {
2289 Self::from_edit(edit)
2290 }
2291}
2292
2293#[cfg(test)]
2294mod seed_tests {
2295 use super::*;
2296 use automerge::transaction::Transactable as _;
2297
2298 #[test]
2299 fn a_seed_read_mid_transaction_leaves_it_open_and_moves_with_it() {
2300 let mut doc = Doc::new();
2301 doc.put(ROOT, "a", 1).unwrap();
2302 doc.commit();
2303 let committed = seed(&doc, b"test", b"payload");
2304 doc.put(ROOT, "b", 2).unwrap();
2305 let base = doc.base_heads();
2306 let open = seed(&doc, b"test", b"payload");
2307 assert!(doc.pending_ops() > 0, "reading the seed commits nothing");
2308 assert_eq!(doc.base_heads(), base);
2309 assert_ne!(open, committed, "an open transaction moves the seed");
2310 doc.put(ROOT, "c", 3).unwrap();
2311 assert_ne!(seed(&doc, b"test", b"payload"), open);
2312 doc.commit();
2313 assert_ne!(seed(&doc, b"test", b"payload"), committed);
2314 }
2315}