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_actions::{ActionError, ExecutionLocus, RiskLevel};
18use tilo_member_types::MemberId;
19
20pub use crate::apply_cache::forget_record;
21
22use crate::collection::Id;
23use crate::kind::ResourceKind;
24use crate::model::{Doc, Fields};
25use crate::resource::Resource;
26
27#[derive(Debug)]
33pub struct ActionCx {
34 preview: bool,
35 seed: [u8; 32],
36 minted: u64,
37 ids: Vec<Id>,
39 now_ms: i64,
40 author: Option<MemberId>,
41 invocation: Option<tilo_actions::InvocationId>,
42 removes_item: bool,
44}
45
46fn invoking_author() -> Option<MemberId> {
48 tilo_actions::reading_invoking_context(|context| {
49 context
50 .and_then(|context| context.invoker.as_ref())
51 .and_then(invoker_member)
52 })
53 .or_else(|| RESOURCE_ACTOR.with_borrow(Clone::clone))
54}
55
56fn invoker_member(invoker: &tilo_actions::ActionInvoker) -> Option<MemberId> {
59 invoker
60 .acting
61 .members()
62 .first()
63 .map(|member| (*member).clone())
64}
65
66pub(crate) fn writing_author() -> Option<MemberId> {
71 tilo_actions::reading_invoking_context(|context| match context {
72 Some(context) => context.invoker.as_ref().and_then(invoker_member),
73 None => RESOURCE_ACTOR.with_borrow(Clone::clone),
74 })
75}
76
77thread_local! {
78 static RESOURCE_ACTOR: std::cell::RefCell<Option<MemberId>> = const { std::cell::RefCell::new(None) };
79}
80
81pub struct ResourceActorScope(Option<MemberId>);
87
88impl ResourceActorScope {
89 #[must_use]
91 pub fn enter(actor: MemberId) -> Self {
92 Self(RESOURCE_ACTOR.replace(Some(actor)))
93 }
94}
95
96impl Drop for ResourceActorScope {
97 fn drop(&mut self) {
98 RESOURCE_ACTOR.replace(self.0.take());
99 }
100}
101
102fn invoking_invocation() -> Option<tilo_actions::InvocationId> {
103 tilo_actions::reading_invoking_context(|context| context?.source_invocation)
104}
105
106impl ActionCx {
107 pub fn remove_item(&mut self) {
112 self.removes_item = true;
113 }
114
115 #[doc(hidden)]
118 pub fn take_item_removal(&mut self) -> bool {
119 std::mem::take(&mut self.removes_item)
120 }
121
122 #[must_use]
129 pub fn for_apply(doc: &Doc, payload: &[u8], now_ms: i64) -> Self {
130 Self {
131 preview: tilo_actions::executor::is_replaying(),
132 seed: seed(doc, b"tilo-resource/action-seed/v1", payload),
133 minted: 0,
134 ids: Vec::new(),
135 now_ms,
136 author: invoking_author(),
137 invocation: invoking_invocation(),
138 removes_item: false,
139 }
140 }
141
142 #[must_use]
147 pub fn for_write(doc: &Doc, payload: &[u8]) -> Self {
148 let mut hasher = blake3::Hasher::new();
149 hasher.update(b"tilo-resource/write-seed/v1");
150 if let Some((group, position)) = crate::group::current_member() {
151 hasher.update(b"member");
152 hasher.update(&group);
153 hasher.update(&position.to_le_bytes());
154 } else {
155 hasher.update(doc.get_actor().to_bytes());
156 let mut heads = automerge::transaction::Transactable::base_heads(doc);
157 heads.compact_sort();
158 for head in heads {
159 hasher.update(&head.0);
160 }
161 }
162 hasher.update(payload);
163 Self {
164 preview: tilo_actions::executor::is_replaying(),
165 seed: *hasher.finalize().as_bytes(),
166 minted: 0,
167 ids: Vec::new(),
168 now_ms: 0,
169 author: invoking_author(),
170 invocation: invoking_invocation(),
171 removes_item: false,
172 }
173 }
174
175 #[must_use]
179 pub fn is_preview(&self) -> bool {
180 self.preview
181 }
182
183 pub fn id(&mut self) -> Id {
185 let id = minted(&self.seed, self.minted);
186 self.minted = self.minted.saturating_add(1);
187 self.ids.push(id.clone());
188 note_minted(id.as_str());
189 id
190 }
191
192 pub fn uuid(&mut self) -> uuid::Uuid {
194 let uuid = minted_uuid(&self.seed, self.minted);
195 self.minted = self.minted.saturating_add(1);
196 note_minted(&uuid.to_string());
197 uuid
198 }
199
200 pub fn named(&mut self, id: impl Into<String>, label: impl Into<String>) {
207 NAMED.with(|named| {
208 named.borrow_mut().replace(tilo_actions::ActionItem {
209 id: id.into(),
210 label: label.into(),
211 });
212 });
213 }
214
215 #[must_use]
218 pub fn acting_name(&self) -> String {
219 invoking_name()
220 }
221
222 #[must_use]
225 pub fn appearance(&self) -> Option<tilo_actions::Appearance> {
226 tilo_actions::reading_invoking_context(|context| {
227 context?
228 .invoker
229 .as_ref()
230 .filter(|invoker| invoker.acting.is_bot())?
231 .appearance
232 .clone()
233 })
234 }
235
236 #[must_use]
239 pub fn invoked_by(&self) -> Option<tilo_actions::Acting> {
240 tilo_actions::reading_invoking_context(|context| {
241 Some(context?.invoker.as_ref()?.acting.clone())
242 })
243 }
244
245 pub fn now_ms(&self) -> i64 {
248 self.now_ms
249 }
250
251 pub fn author(&self) -> Option<&MemberId> {
257 self.author.as_ref()
258 }
259
260 pub const fn invocation(&self) -> Option<tilo_actions::InvocationId> {
264 self.invocation
265 }
266}
267
268fn uuid_from(digest: &[u8; 32]) -> uuid::Uuid {
269 let mut bytes = [0_u8; 16];
270 bytes.copy_from_slice(digest.get(..16).unwrap_or(&[0; 16]));
271 uuid::Builder::from_random_bytes(bytes).into_uuid()
272}
273
274thread_local! {
275 static MINTED: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
277 static ENTRIES: std::cell::RefCell<std::collections::HashMap<String, automerge::ObjId>> =
280 std::cell::RefCell::new(std::collections::HashMap::new());
281 static NAMED: std::cell::RefCell<Option<tilo_actions::ActionItem>> =
285 const { std::cell::RefCell::new(None) };
286}
287
288pub(crate) fn start_minting() {
291 drop(take_minted());
292 ENTRIES.with(|entries| entries.borrow_mut().clear());
293 NAMED.with(|named| named.borrow_mut().take());
294}
295
296pub(crate) fn note_entry(map: &automerge::ObjId, id: &str) {
299 ENTRIES.with(|entries| {
300 entries.borrow_mut().insert(id.to_owned(), map.clone());
301 });
302}
303
304#[must_use]
308pub fn minted_entry(id: &str) -> Option<automerge::ObjId> {
309 ENTRIES.with(|entries| entries.borrow().get(id).cloned())
310}
311
312pub(crate) fn named_item() -> Option<tilo_actions::ActionItem> {
315 NAMED.with_borrow(Clone::clone)
316}
317
318pub(crate) fn entries_so_far() -> Vec<String> {
321 ENTRIES.with_borrow(|entries| entries.keys().cloned().collect())
322}
323
324pub(crate) fn minted_so_far() -> Vec<String> {
328 MINTED.with_borrow(Clone::clone)
329}
330
331pub(crate) fn note_minted(id: &str) {
334 MINTED.with(|minted| minted.borrow_mut().push(id.to_owned()));
335}
336
337#[must_use]
341pub fn take_minted() -> Vec<String> {
342 MINTED.with(|minted| std::mem::take(&mut *minted.borrow_mut()))
343}
344
345pub fn restore_minted(ids: impl IntoIterator<Item = String>) {
348 MINTED.with(|minted| minted.borrow_mut().extend(ids));
349}
350
351thread_local! {
352 static MINT: std::cell::Cell<Option<([u8; 32], u64)>> = const { std::cell::Cell::new(None) };
355}
356
357struct MintScope(Option<([u8; 32], u64)>);
358
359impl MintScope {
360 fn enter(cx: &ActionCx) -> Self {
361 let mut hasher = blake3::Hasher::new();
362 hasher.update(b"tilo-resource/fresh-uuid/v1");
363 hasher.update(&cx.seed);
364 let seed = *hasher.finalize().as_bytes();
365 Self(MINT.with(|mint| mint.replace(Some((seed, 0)))))
366 }
367}
368
369impl Drop for MintScope {
370 fn drop(&mut self) {
371 MINT.with(|mint| mint.set(self.0));
372 }
373}
374
375#[must_use]
379pub fn invoking_member() -> Option<MemberId> {
380 invoking_author()
381}
382
383#[must_use]
387pub fn invoking_name() -> String {
388 tilo_actions::reading_invoking_context(|context| {
389 context
390 .and_then(|context| context.invoker.as_ref())
391 .filter(|invoker| !invoker.acting.is_person())
392 .and_then(|invoker| invoker.name.clone())
393 .filter(|name| !name.trim().is_empty())
394 .unwrap_or_default()
395 })
396}
397
398#[must_use]
403pub fn fresh_uuid() -> uuid::Uuid {
404 MINT.with(|mint| match mint.get() {
405 Some((seed, counter)) => {
406 mint.set(Some((seed, counter.saturating_add(1))));
407 let mut hasher = blake3::Hasher::new();
408 hasher.update(&seed);
409 hasher.update(&counter.to_le_bytes());
410 let uuid = uuid_from(hasher.finalize().as_bytes());
411 note_minted(&uuid.to_string());
412 uuid
413 }
414 None => uuid::Uuid::new_v4(),
415 })
416}
417
418fn minted_uuid(seed: &[u8; 32], counter: u64) -> uuid::Uuid {
419 let mut hasher = blake3::Hasher::new();
420 hasher.update(b"uuid");
421 hasher.update(seed);
422 hasher.update(&counter.to_le_bytes());
423 uuid_from(hasher.finalize().as_bytes())
424}
425
426fn minted(seed: &[u8; 32], counter: u64) -> Id {
427 let mut hasher = blake3::Hasher::new();
428 hasher.update(seed);
429 hasher.update(&counter.to_le_bytes());
430 let digest = hasher.finalize();
431 let hex = digest.to_hex();
432 Id::from_raw(hex.as_str().get(..20).unwrap_or_default())
433}
434
435pub fn minted_ids(envelope: &tilo_actions::ActionEnvelope) -> impl Iterator<Item = Id> {
440 let seed = envelope_seed(envelope);
441 (0_u64..).map(move |counter| minted(&seed, counter))
442}
443
444pub fn minted_keys(envelope: &tilo_actions::ActionEnvelope) -> impl Iterator<Item = [String; 2]> {
448 let seed = envelope_seed(envelope);
449 (0_u64..).map(move |counter| {
450 [
451 minted(&seed, counter).as_str().to_owned(),
452 minted_uuid(&seed, counter).to_string(),
453 ]
454 })
455}
456
457fn envelope_seed(envelope: &tilo_actions::ActionEnvelope) -> [u8; 32] {
459 let mut hasher = blake3::Hasher::new();
460 hasher.update(b"tilo-resource/action-seed/v1");
461 hasher.update(envelope.actor().to_bytes());
462 let mut heads = envelope.base_heads.clone();
463 heads.compact_sort();
464 for head in &heads {
465 hasher.update(head);
466 }
467 hasher.update(&envelope.action.payload);
468 *hasher.finalize().as_bytes()
469}
470
471pub(crate) fn seed(doc: &Doc, domain: &[u8], payload: &[u8]) -> [u8; 32] {
475 use automerge::transaction::Transactable as _;
476 let mut hasher = blake3::Hasher::new();
477 hasher.update(domain);
478 if let Some((group, position)) = crate::group::current_member() {
479 hasher.update(b"member");
480 hasher.update(&group);
481 hasher.update(&position.to_le_bytes());
482 } else {
483 hasher.update(doc.get_actor().to_bytes());
484 let mut heads = doc.base_heads();
489 heads.compact_sort();
490 for head in heads {
491 hasher.update(&head.0);
492 }
493 let pending = doc.pending_ops();
494 if pending > 0 {
495 hasher.update(b"pending");
496 hasher.update(&u64::try_from(pending).unwrap_or(u64::MAX).to_le_bytes());
497 }
498 }
499 hasher.update(payload);
500 *hasher.finalize().as_bytes()
501}
502
503pub trait Outcome {
505 fn into_result(self) -> Result<(), Refusal>;
506}
507
508impl Outcome for () {
509 fn into_result(self) -> Result<(), Refusal> {
510 Ok(())
511 }
512}
513
514impl<E: Into<Refusal>> Outcome for Result<(), E> {
515 fn into_result(self) -> Result<(), Refusal> {
516 self.map_err(Into::into)
517 }
518}
519
520pub use tilo_action_types::ActionKind;
521
522pub use tilo_actions::ActionKey;
523
524pub trait Operation: Serialize + DeserializeOwned + Clone + std::fmt::Debug + 'static {
526 type Record: Fields + 'static;
527
528 const KIND: &'static str;
530
531 fn edit(&self) -> Option<&crate::Edit<Self::Record>> {
534 None
535 }
536
537 fn kind(&self) -> ActionKind {
540 ActionKind::Undoable
541 }
542
543 fn perform(&self, record: &mut Self::Record, cx: &mut ActionCx) -> Result<(), Refusal>;
545
546 fn writes(&self) -> crate::footprint::Writes {
550 crate::footprint::Writes::record()
551 }
552
553 fn snapshot(record: &Self::Record) -> Option<Self::Record> {
558 let _ = record;
559 None
560 }
561
562 fn risk(&self) -> RiskLevel {
567 RiskLevel::Low
568 }
569
570 fn change_kind(&self) -> tilo_actions::ChangeKind {
575 tilo_actions::ChangeKind::Content
576 }
577
578 fn incoming_message(&self) -> bool {
581 false
582 }
583
584 fn irreversible(&self) -> bool {
588 false
589 }
590
591 fn leaves(&self) -> bool {
594 false
595 }
596
597 fn by_app(&self) -> bool {
601 false
602 }
603
604 fn compensates(&self) -> bool {
607 false
608 }
609
610 const QUEUES: bool = false;
613
614 fn queue(record: &mut Self::Record, before: &Self::Record, cx: &mut ActionCx) {
617 let _ = (record, before, cx);
618 }
619
620 fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>> {
625 let _ = (doc, cx);
626 None
627 }
628
629 fn field_edit(edit: crate::Edit<Self::Record>) -> Option<Self> {
631 let _ = edit;
632 None
633 }
634
635 fn compensation(
639 &self,
640 before: &Self::Record,
641 after: &Self::Record,
642 minted: &[Id],
643 ) -> Option<Result<Self, String>> {
644 let _ = (before, after, minted);
645 None
646 }
647}
648
649pub struct Undoing<'a, R, P> {
656 pub before: &'a R,
657 pub after: &'a R,
658 pub minted: &'a [Id],
659 pub params: &'a P,
660}
661
662impl<R, P> Clone for Undoing<'_, R, P> {
663 fn clone(&self) -> Self {
664 *self
665 }
666}
667
668impl<R, P> Copy for Undoing<'_, R, P> {}
669
670#[allow(
673 clippy::needless_pass_by_value,
674 reason = "`map_err` hands it the error by value"
675)]
676fn model_refused(error: crate::ModelError) -> ActionError {
677 ActionError::Refused(error.to_string())
678}
679
680#[allow(
682 clippy::needless_pass_by_value,
683 reason = "`map_err` hands it the error by value"
684)]
685fn automerge_refused(error: automerge::AutomergeError) -> ActionError {
686 ActionError::Refused(error.to_string())
687}
688
689pub use tilo_actions::Refusal;
690
691fn refusal_refused(refusal: Refusal) -> ActionError {
693 refusal.into()
694}
695
696#[derive(Serialize, Clone)]
699pub struct Stamped<O> {
700 #[serde(rename = "op")]
701 pub operation: O,
702 #[serde(rename = "at", default)]
703 pub now_ms: i64,
704}
705
706impl<O: Operation> Stamped<O> {
707 #[must_use]
710 pub fn edited_field(&self) -> Option<&str> {
711 match self.operation.edit()?.path().first()? {
712 crate::Segment::Field(key) => Some(key),
713 _ => None,
714 }
715 }
716}
717
718impl<O: std::fmt::Debug> std::fmt::Debug for Stamped<O> {
719 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
720 fmt_stamped(&self.operation, self.now_ms, f)
721 }
722}
723
724fn fmt_stamped(
725 operation: &dyn std::fmt::Debug,
726 now_ms: i64,
727 f: &mut std::fmt::Formatter<'_>,
728) -> std::fmt::Result {
729 f.debug_struct("Stamped")
730 .field("operation", operation)
731 .field("now_ms", &now_ms)
732 .finish()
733}
734
735impl<'de, O: DeserializeOwned> Deserialize<'de> for Stamped<O> {
738 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
739 let value = serde_json::Value::deserialize(deserializer)?;
740 match Self::from_json(value) {
741 Ok(stamped) => Ok(stamped),
742 Err(error) => Err(serde::de::Error::custom(error)),
743 }
744 }
745}
746
747impl<O: DeserializeOwned> Stamped<O> {
748 pub fn from_json(value: serde_json::Value) -> Result<Self, serde_json::Error> {
753 let (operation, now_ms) = stamped_parts(value)?;
754 Ok(Self {
755 operation: O::deserialize(operation)?,
756 now_ms,
757 })
758 }
759}
760
761#[inline(never)]
763fn stamped_parts(value: serde_json::Value) -> Result<(serde_json::Value, i64), serde_json::Error> {
764 use serde::de::Error as _;
765 let serde_json::Value::Object(mut fields) = value else {
766 return Err(serde_json::Error::custom(
767 "a stamped operation is an object",
768 ));
769 };
770 let operation = fields
771 .remove("op")
772 .ok_or_else(|| serde_json::Error::missing_field("op"))?;
773 let now_ms = match fields.remove("at") {
774 None | Some(serde_json::Value::Null) => 0,
775 Some(at) => i64::deserialize(at)?,
776 };
777 Ok((operation, now_ms))
778}
779
780fn settles(operation: &impl Operation) -> bool {
783 matches!(
784 operation.edit().map(crate::Edit::op),
785 Some(crate::EditOp::Settle { .. } | crate::EditOp::Forget { .. })
786 )
787}
788
789#[inline(never)]
792fn on_copy(doc: &Doc, apply: &mut dyn FnMut(&mut Doc)) {
793 let mut copy = doc.clone();
794 apply(&mut copy);
795}
796
797impl<O: Operation> Stamped<O> {
798 fn compensated(&self) -> bool {
803 if settles(&self.operation)
806 || matches!(
807 self.operation.change_kind(),
808 tilo_actions::ChangeKind::External | tilo_actions::ChangeKind::Housekeeping
809 )
810 {
811 return false;
812 }
813 O::QUEUES || (self.operation.edit().is_none() && self.operation.compensates())
814 }
815
816 fn applied_to_copy(&self, doc: &Doc) -> Option<(O::Record, Vec<Id>)> {
820 let payload = serde_json::to_vec(self).ok()?;
821 if let Some(edit) = self.operation.edit() {
822 let mut cx = ActionCx::for_apply(doc, &payload, self.now_ms);
823 cx.preview = true;
824 let mut after = None;
825 on_copy(doc, &mut |copy| {
826 after = edit
827 .apply(copy, &mut cx)
828 .ok()
829 .and_then(|()| O::Record::read_fields(copy, &ROOT).ok());
830 });
831 return Some((after?, cx.ids));
832 }
833 let mut after = O::Record::read_fields(doc, &ROOT).ok()?;
834 let mut cx = ActionCx::for_apply(doc, &payload, self.now_ms);
835 cx.preview = true;
836 let minting = MintScope::enter(&cx);
837 let performed = self.operation.perform(&mut after, &mut cx);
838 drop(minting);
839 performed.ok()?;
840 Some((after, cx.ids))
841 }
842
843 fn compensation(&self, doc: &Doc) -> Option<tilo_actions::EncodedAction> {
848 if !self.compensated() {
849 return None;
850 }
851 let before = O::Record::read_fields(doc, &ROOT).ok()?;
852 let (after, minted) = self.applied_to_copy(doc)?;
853 if self.operation.edit().is_none() && self.operation.compensates() {
854 let operation = self
857 .operation
858 .compensation(&before, &after, &minted)?
859 .ok()?;
860 let undo = Self {
861 operation,
862 now_ms: self.now_ms,
863 };
864 return tilo_actions::EncodedAction::encode(O::KIND, &undo).ok();
865 }
866 let mut restore: Vec<crate::Edit<()>> = Vec::new();
867 crate::Model::diff(&after, &before, &[], &mut restore);
868 let mut members = Vec::with_capacity(restore.len());
869 for edit in restore {
870 members.push(Self {
871 operation: O::field_edit(edit.retyped())?,
872 now_ms: self.now_ms,
873 });
874 }
875 let restore = match members.len() {
876 0 => return None,
877 1 => tilo_actions::EncodedAction::encode(O::KIND, &members.pop()?).ok()?,
878 _ => tilo_actions::EncodedAction::encode(
879 crate::group::group_type_of(O::KIND),
880 &crate::ActionGroup { actions: members },
881 )
882 .ok()?,
883 };
884 if serde_json::to_vec(&restore).ok()?.len() <= tilo_actions::context::COMPENSATION_BUDGET {
885 return Some(restore);
886 }
887 let reverting = Reverting::<O> {
890 actor: doc.get_actor().to_hex_string(),
891 deps: doc
892 .committed_heads()
893 .iter()
894 .map(ToString::to_string)
895 .collect(),
896 now_ms: self.now_ms,
897 operation: PhantomData,
898 };
899 tilo_actions::EncodedAction::encode(reverting_type(O::KIND), &reverting).ok()
900 }
901}
902
903pub fn reverting_type(kind: &str) -> String {
905 format!("{kind}+revert")
906}
907
908#[derive(Serialize)]
914#[serde(bound = "")]
915pub struct Reverting<O> {
916 actor: String,
917 deps: Vec<String>,
918 #[serde(rename = "at", default)]
919 now_ms: i64,
920 #[serde(skip)]
921 operation: PhantomData<O>,
922}
923
924impl<'de, O> Deserialize<'de> for Reverting<O> {
926 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
927 let value = serde_json::Value::deserialize(deserializer)?;
928 let (actor, deps, now_ms) = match reverted(value) {
929 Ok(target) => target,
930 Err(error) => return Err(serde::de::Error::custom(error)),
931 };
932 Ok(Self {
933 actor,
934 deps,
935 now_ms,
936 operation: PhantomData,
937 })
938 }
939}
940
941#[inline(never)]
943fn reverted(value: serde_json::Value) -> Result<(String, Vec<String>, i64), serde_json::Error> {
944 #[derive(Deserialize)]
945 struct Form {
946 actor: String,
947 deps: Vec<String>,
948 #[serde(rename = "at", default)]
949 now_ms: i64,
950 }
951 let form = Form::deserialize(value)?;
952 Ok((form.actor, form.deps, form.now_ms))
953}
954
955impl<O> std::fmt::Debug for Reverting<O> {
956 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
957 f.debug_struct("Reverting")
958 .field("actor", &self.actor)
959 .field("deps", &self.deps)
960 .finish_non_exhaustive()
961 }
962}
963
964impl<O: Operation> Reverting<O> {
965 fn change(&self, doc: &mut Doc) -> Result<automerge::ChangeHash, ActionError> {
968 reverted_change(&self.actor, &self.deps, doc)
969 }
970}
971
972#[inline(never)]
974fn reverted_change(
975 actor: &str,
976 deps: &[String],
977 doc: &mut Doc,
978) -> Result<automerge::ChangeHash, ActionError> {
979 let refused = |why: &str| ActionError::Refused(why.into());
980 let mut deps = deps
981 .iter()
982 .map(|hash| hash.parse())
983 .collect::<Result<Vec<automerge::ChangeHash>, _>>()
984 .map_err(|_| refused("a reverted change names invalid heads"))?;
985 deps.compact_sort();
986 doc.get_changes(&deps)
987 .into_iter()
988 .find(|change| {
989 change.actor_id().to_hex_string() == actor && {
990 let mut of = change.deps().to_vec();
991 of.compact_sort();
992 of == deps
993 }
994 })
995 .map(|change| change.hash())
996 .ok_or_else(|| refused("the change to take back is not in this document"))
997}
998
999impl<O: Operation> tilo_actions::Action for Reverting<O> {
1000 fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
1001 let change = self.change(doc)?;
1002 let payload = serde_json::to_vec(self).map_err(ActionError::Encode)?;
1003 revert(
1004 &ResourceOf::<O::Record>::OPS,
1005 &|record, before, cx| {
1006 if let (Some(record), Some(before)) = (
1007 record.downcast_mut::<O::Record>(),
1008 before.downcast_ref::<O::Record>(),
1009 ) {
1010 O::queue(record, before, cx);
1011 }
1012 },
1013 (change, &payload, self.now_ms),
1014 doc,
1015 )
1016 }
1017
1018 fn locus(&self) -> ExecutionLocus {
1019 ExecutionLocus::ClientLocal
1020 }
1021}
1022
1023fn revert(
1026 record: &ResourceOps,
1027 queue: &dyn Fn(&mut dyn Any, &dyn Any, &mut ActionCx),
1028 (change, payload, now_ms): (automerge::ChangeHash, &[u8], i64),
1029 doc: &mut Doc,
1030) -> Result<(), ActionError> {
1031 let deps: Vec<automerge::ChangeHash> = doc
1032 .get_change_meta_by_hash(&change)
1033 .map(|meta| meta.deps)
1034 .unwrap_or_default();
1035 let before = {
1036 let at = doc.committed_fork_at(&deps).map_err(automerge_refused)?;
1037 (record.read)(&at).map_err(model_refused)?
1038 };
1039 let after = {
1040 let at = doc
1041 .committed_fork_at(&[change])
1042 .map_err(automerge_refused)?;
1043 (record.read)(&at).map_err(model_refused)?
1044 };
1045 let restore = (record.diff)(after.as_ref(), before.as_ref());
1046 let mut cx = ActionCx::for_apply(doc, payload, now_ms);
1047 let current = (record.read)(doc).map_err(model_refused)?;
1048 for edit in &restore {
1049 (record.edit)(edit, doc, &mut cx).map_err(model_refused)?;
1050 }
1051 let mut written = (record.read)(doc).map_err(model_refused)?;
1052 let minting = MintScope::enter(&cx);
1053 queue(written.as_mut(), current.as_ref(), &mut cx);
1054 drop(minting);
1055 (record.write)(written.as_ref(), doc).map_err(model_refused)
1056}
1057
1058type WriteChanged =
1061 fn(&dyn Any, &dyn Any, &mut Doc, &crate::Delta) -> Result<(), crate::ModelError>;
1062
1063pub(crate) struct ResourceOps {
1067 shape: crate::Shape,
1068 name: fn() -> &'static str,
1069 kind: fn() -> std::any::TypeId,
1070 read: fn(&Doc) -> Result<Box<dyn Any>, crate::ModelError>,
1071 write: fn(&dyn Any, &mut Doc) -> Result<(), crate::ModelError>,
1072 write_changed: WriteChanged,
1073 check: fn(&dyn Any) -> Result<(), Refusal>,
1074 refresh: fn(&mut dyn Any, &Doc, &crate::Delta) -> bool,
1075 diff: fn(&dyn Any, &dyn Any) -> Vec<crate::Edit<()>>,
1077 edit: fn(&crate::Edit<()>, &mut Doc, &mut ActionCx) -> Result<(), crate::ModelError>,
1078}
1079
1080fn resource_of<R: 'static>(record: &dyn Any) -> Result<&R, crate::ModelError> {
1082 match record.downcast_ref::<R>() {
1083 Some(record) => Ok(record),
1084 None => Err(crate::ModelError::invalid("a record of another type")),
1085 }
1086}
1087
1088fn read_resource<R: Fields + 'static>(doc: &Doc) -> Result<Box<dyn Any>, crate::ModelError> {
1089 match R::read_fields(doc, &ROOT) {
1090 Ok(record) => Ok(Box::new(record)),
1091 Err(error) => Err(error),
1092 }
1093}
1094
1095fn write_resource<R: Fields + 'static>(
1096 record: &dyn Any,
1097 doc: &mut Doc,
1098) -> Result<(), crate::ModelError> {
1099 resource_of::<R>(record)?.write_fields(doc, &ROOT)
1100}
1101
1102fn write_changed_resource<R: Fields + 'static>(
1103 record: &dyn Any,
1104 kept: &dyn Any,
1105 doc: &mut Doc,
1106 dirty: &crate::Delta,
1107) -> Result<(), crate::ModelError> {
1108 resource_of::<R>(record)?.write_changed_fields(resource_of::<R>(kept)?, doc, &ROOT, dirty)
1109}
1110
1111fn check_resource<R: Fields + 'static>(record: &dyn Any) -> Result<(), Refusal> {
1112 match record.downcast_ref::<R>() {
1113 Some(record) => crate::Model::check(record),
1114 None => Err(Refusal::new("a record of another type")),
1115 }
1116}
1117
1118fn refresh_resource<R: Fields + 'static>(
1119 record: &mut dyn Any,
1120 doc: &Doc,
1121 delta: &crate::Delta,
1122) -> bool {
1123 match record.downcast_mut::<R>() {
1124 Some(record) => record.refresh_fields(doc, &ROOT, delta).is_ok(),
1125 None => false,
1126 }
1127}
1128
1129fn diff_resources<R: Fields + 'static>(from: &dyn Any, to: &dyn Any) -> Vec<crate::Edit<()>> {
1130 let mut edits = Vec::new();
1131 if let (Some(from), Some(to)) = (from.downcast_ref::<R>(), to.downcast_ref::<R>()) {
1132 crate::Model::diff(from, to, &[], &mut edits);
1133 }
1134 edits
1135}
1136
1137fn edit_resource<R: Fields + 'static>(
1138 edit: &crate::Edit<()>,
1139 doc: &mut Doc,
1140 cx: &mut ActionCx,
1141) -> Result<(), crate::ModelError> {
1142 R::edit_fields(doc, &ROOT, edit.path(), edit.op(), cx)
1143}
1144
1145pub(crate) struct ResourceOf<R>(PhantomData<R>);
1146
1147impl<R: Fields + 'static> ResourceOf<R> {
1148 pub(crate) const OPS: ResourceOps = ResourceOps {
1149 shape: <R as crate::Model>::SHAPE,
1150 name: std::any::type_name::<R>,
1151 kind: std::any::TypeId::of::<R>,
1152 read: read_resource::<R>,
1153 write: write_resource::<R>,
1154 write_changed: write_changed_resource::<R>,
1155 check: check_resource::<R>,
1156 refresh: refresh_resource::<R>,
1157 diff: diff_resources::<R>,
1158 edit: edit_resource::<R>,
1159 };
1160}
1161
1162fn apply_edit(
1164 operation: &dyn Performs,
1165 doc: &mut Doc,
1166 cx: &mut ActionCx,
1167) -> Result<(), ActionError> {
1168 match operation.apply_edit(doc, cx) {
1169 Some(applied) => applied.map_err(model_refused),
1170 None => Ok(()),
1171 }
1172}
1173
1174trait Performs {
1176 fn is_edit(&self) -> bool;
1177 fn apply_edit(&self, doc: &mut Doc, cx: &mut ActionCx)
1179 -> Option<Result<(), crate::ModelError>>;
1180 fn queues(&self) -> bool;
1181 fn perform(&self, record: &mut dyn Any, cx: &mut ActionCx) -> Result<(), Refusal>;
1182 fn queue(&self, record: &mut dyn Any, before: &dyn Any, cx: &mut ActionCx);
1183 fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>>;
1184 fn writes(&self) -> crate::footprint::Writes;
1185 fn snapshot(&self, record: &dyn Any) -> Option<Box<dyn Any>>;
1186}
1187
1188impl<O: Operation> Performs for O {
1189 fn is_edit(&self) -> bool {
1190 self.edit().is_some()
1191 }
1192
1193 fn apply_edit(
1194 &self,
1195 doc: &mut Doc,
1196 cx: &mut ActionCx,
1197 ) -> Option<Result<(), crate::ModelError>> {
1198 let edit = self.edit()?;
1199 Some(O::Record::edit_fields(
1200 doc,
1201 &ROOT,
1202 edit.path(),
1203 edit.op(),
1204 cx,
1205 ))
1206 }
1207
1208 fn queues(&self) -> bool {
1209 O::QUEUES && !settles(self)
1210 }
1211
1212 fn perform(&self, record: &mut dyn Any, cx: &mut ActionCx) -> Result<(), Refusal> {
1213 match record.downcast_mut::<O::Record>() {
1214 Some(record) => Operation::perform(self, record, cx),
1215 None => Err(Refusal::new("a record of another type")),
1216 }
1217 }
1218
1219 fn queue(&self, record: &mut dyn Any, before: &dyn Any, cx: &mut ActionCx) {
1220 if let (Some(record), Some(before)) = (
1221 record.downcast_mut::<O::Record>(),
1222 before.downcast_ref::<O::Record>(),
1223 ) {
1224 O::queue(record, before, cx);
1225 }
1226 }
1227
1228 fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>> {
1229 Operation::perform_item(self, doc, cx)
1230 }
1231
1232 fn writes(&self) -> crate::footprint::Writes {
1233 Operation::writes(self)
1234 }
1235
1236 fn snapshot(&self, record: &dyn Any) -> Option<Box<dyn Any>> {
1237 let record = record.downcast_ref::<O::Record>()?;
1238 O::snapshot(record).map(|record| Box::new(record) as Box<dyn Any>)
1239 }
1240}
1241
1242fn apply_edit_queued(
1245 record: &'static ResourceOps,
1246 operation: &dyn Performs,
1247 doc: &mut Doc,
1248 cx: &mut ActionCx,
1249) -> Result<(), ActionError> {
1250 if !operation.queues() {
1251 return apply_edit(operation, doc, cx);
1252 }
1253 let before = (record.read)(doc).map_err(model_refused)?;
1254 apply_edit(operation, doc, cx)?;
1255 let mut after = (record.read)(doc).map_err(model_refused)?;
1256 let minting = MintScope::enter(cx);
1257 operation.queue(after.as_mut(), before.as_ref(), cx);
1258 drop(minting);
1259 (record.write)(after.as_ref(), doc).map_err(model_refused)
1260}
1261
1262fn read_whole(ops: &'static ResourceOps, doc: &Doc) -> Result<Box<dyn Any>, ActionError> {
1265 let _whole = crate::profiling::Phase::start("resource.apply_whole_read");
1266 #[cfg(any(test, feature = "test-support"))]
1267 if let Some(record) = crate::apply_cache::current_record() {
1268 let mut counts = WHOLE_READS
1269 .lock()
1270 .unwrap_or_else(std::sync::PoisonError::into_inner);
1271 let count = counts.entry(record.to_string()).or_default();
1272 *count = count.saturating_add(1);
1273 drop(counts);
1274 }
1275 (ops.read)(doc).map_err(model_refused)
1276}
1277
1278#[cfg(any(test, feature = "test-support"))]
1282#[must_use]
1283pub fn whole_reads(record: &str) -> usize {
1284 WHOLE_READS
1285 .lock()
1286 .unwrap_or_else(std::sync::PoisonError::into_inner)
1287 .get(record)
1288 .copied()
1289 .unwrap_or_default()
1290}
1291
1292#[cfg(any(test, feature = "test-support"))]
1294static WHOLE_READS: std::sync::LazyLock<
1295 std::sync::Mutex<std::collections::BTreeMap<String, usize>>,
1296> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::BTreeMap::new()));
1297
1298fn apply_operation(
1308 record: &'static ResourceOps,
1309 operation: &dyn Performs,
1310 (payload, now_ms): (&[u8], i64),
1311 doc: &mut Doc,
1312) -> Result<(), ActionError> {
1313 if crate::group::current_member().is_none() {
1315 start_minting();
1316 }
1317 let mut cx = ActionCx::for_apply(doc, payload, now_ms);
1318 let shape = record.shape;
1319 let units = crate::footprint::has_units(shape);
1320 let index = |doc: &mut Doc| {
1323 if units {
1324 crate::footprint::index(doc, shape).map_err(automerge_refused)?;
1325 }
1326 Ok::<(), ActionError>(())
1327 };
1328 let queues = operation.queues();
1329 let grouping = crate::group::grouping();
1333 if grouping {
1334 if !operation.is_edit() && !queues && held::holds(record) {
1335 return held::perform(record, operation, &mut cx);
1336 }
1337 held::flush(record, doc)?;
1338 }
1339 if operation.is_edit() {
1340 apply_edit_queued(record, operation, doc, &mut cx)?;
1341 return index(doc);
1342 }
1343 if !queues {
1346 let minting = MintScope::enter(&cx);
1347 let performed = operation.perform_item(doc, &mut cx);
1348 drop(minting);
1349 if let Some(performed) = performed {
1350 performed.map_err(refusal_refused)?;
1351 return index(doc);
1352 }
1353 }
1354 let committed = automerge::transaction::Transactable::pending_ops(doc) == 0;
1357 let started = automerge::transaction::Transactable::base_heads(doc);
1358 let (mut current, dirty) =
1359 match crate::apply_cache::take_any((record.kind)(), doc, &record.refresh) {
1360 Some((warm, dirty)) => (warm, Some(dirty)),
1361 None => (read_whole(record, doc)?, None),
1362 };
1363 if grouping && !queues {
1366 let base = operation.snapshot(current.as_ref());
1368 held::start(record, current, base, dirty);
1369 return held::perform(record, operation, &mut cx);
1370 }
1371 let kept = if committed || queues || units || dirty.is_some() {
1374 operation.snapshot(current.as_ref())
1375 } else {
1376 None
1377 };
1378 let read_before;
1379 let before: Option<&dyn Any> = match (&kept, queues || units) {
1380 (_, false) => None,
1381 (Some(kept), true) => Some(kept.as_ref()),
1382 (None, true) => {
1383 read_before = (record.read)(doc).map_err(model_refused)?;
1384 Some(read_before.as_ref())
1385 }
1386 };
1387 let minting = MintScope::enter(&cx);
1388 let performed = operation.perform(current.as_mut(), &mut cx);
1389 if let (Ok(()), Some(before), true) = (&performed, before, queues) {
1390 operation.queue(current.as_mut(), before, &mut cx);
1391 }
1392 drop(minting);
1393 performed.map_err(refusal_refused)?;
1394 if grouping {
1395 crate::group::check_or_defer(format!("{}@root", (record.name)()), doc, move |doc| {
1397 match (record.read)(doc) {
1398 Ok(read) => (record.check)(read.as_ref()),
1399 Err(error) => Err(Refusal::new(error.to_string())),
1400 }
1401 })
1402 .map_err(refusal_refused)?;
1403 } else {
1404 (record.check)(current.as_ref()).map_err(refusal_refused)?;
1405 }
1406 if let (Some(before), true) = (before, units) {
1407 let edits = (record.diff)(before, current.as_ref());
1408 crate::footprint::check_edits(shape, &edits, &operation.writes())
1409 .map_err(refusal_refused)?;
1410 }
1411 crate::apply_cache::begin_storing();
1412 match (&kept, &dirty) {
1413 (Some(kept), Some(dirty)) => {
1414 (record.write_changed)(current.as_ref(), kept.as_ref(), doc, dirty)
1415 }
1416 _ => (record.write)(current.as_ref(), doc),
1417 }
1418 .map_err(model_refused)?;
1419 index(doc)?;
1420 crate::apply_cache::seal_stored(doc);
1421 if automerge::transaction::Transactable::pending_ops(doc) > 0 {
1426 crate::apply_cache::keep_open((record.kind)(), current, doc);
1427 } else if let Some(kept) = kept {
1428 crate::apply_cache::keep_any((record.kind)(), kept, doc, &started);
1429 }
1430 Ok(())
1431}
1432
1433mod held {
1439 use std::any::{Any, TypeId};
1440 use std::cell::RefCell;
1441
1442 use tilo_actions::ActionError;
1443
1444 use super::{ActionCx, MintScope, Performs, ResourceOps, model_refused, refusal_refused};
1445 use crate::footprint::Footprints;
1446 use crate::model::Doc;
1447
1448 struct Held {
1449 record: &'static ResourceOps,
1450 current: Box<dyn Any>,
1452 base: Option<Box<dyn Any>>,
1455 dirty: Option<crate::Delta>,
1458 footprints: Footprints,
1460 }
1461
1462 thread_local! {
1463 static HELD: RefCell<Option<Vec<Held>>> = const { RefCell::new(None) };
1465 }
1466
1467 pub(crate) fn begin() {
1469 HELD.with(|held| *held.borrow_mut() = Some(Vec::new()));
1470 }
1471
1472 pub(crate) fn end() {
1474 HELD.with(|held| held.borrow_mut().take());
1475 }
1476
1477 fn kind(record: &ResourceOps) -> TypeId {
1478 (record.kind)()
1479 }
1480
1481 pub(super) fn holds(record: &ResourceOps) -> bool {
1483 HELD.with(|held| {
1484 held.borrow()
1485 .as_ref()
1486 .is_some_and(|held| held.iter().any(|entry| kind(entry.record) == kind(record)))
1487 })
1488 }
1489
1490 pub(super) fn start(
1492 record: &'static ResourceOps,
1493 current: Box<dyn Any>,
1494 base: Option<Box<dyn Any>>,
1495 dirty: Option<crate::Delta>,
1496 ) {
1497 HELD.with(|held| {
1498 if let Some(held) = held.borrow_mut().as_mut() {
1499 held.push(Held {
1500 record,
1501 current,
1502 base,
1503 dirty,
1504 footprints: Footprints::default(),
1505 });
1506 }
1507 });
1508 }
1509
1510 pub(super) fn perform(
1512 record: &'static ResourceOps,
1513 operation: &dyn Performs,
1514 cx: &mut ActionCx,
1515 ) -> Result<(), ActionError> {
1516 HELD.with(|held| {
1517 let mut held = held.borrow_mut();
1518 let entry = held
1519 .as_mut()
1520 .and_then(|held| {
1521 held.iter_mut()
1522 .find(|entry| kind(entry.record) == kind(record))
1523 })
1524 .ok_or_else(|| ActionError::Refused("the group does not hold the record".into()))?;
1525 let minting = MintScope::enter(cx);
1526 let performed = operation.perform(entry.current.as_mut(), cx);
1527 drop(minting);
1528 performed.map_err(refusal_refused)?;
1529 entry.footprints.add(&operation.writes());
1530 Ok(())
1531 })
1532 }
1533
1534 pub(super) fn flush(record: &ResourceOps, doc: &mut Doc) -> Result<(), ActionError> {
1537 let taken = HELD.with(|held| {
1538 let mut held = held.borrow_mut();
1539 let held = held.as_mut()?;
1540 let at = held
1541 .iter()
1542 .position(|entry| kind(entry.record) == kind(record))?;
1543 Some(held.remove(at))
1544 });
1545 match taken {
1546 Some(entry) => write(entry, doc, Checked::AtTheEnd),
1547 None => Ok(()),
1548 }
1549 }
1550
1551 pub(crate) fn flush_all(doc: &mut Doc) -> Result<(), ActionError> {
1553 let taken = HELD.with(|held| held.borrow_mut().as_mut().map(std::mem::take));
1554 for entry in taken.unwrap_or_default() {
1555 write(entry, doc, Checked::Now)?;
1556 }
1557 Ok(())
1558 }
1559
1560 #[derive(Clone, Copy)]
1562 enum Checked {
1563 Now,
1565 AtTheEnd,
1567 }
1568
1569 fn write(entry: Held, doc: &mut Doc, checked: Checked) -> Result<(), ActionError> {
1570 let Held {
1571 record,
1572 current,
1573 base,
1574 dirty,
1575 footprints,
1576 } = entry;
1577 let units = crate::footprint::has_units(record.shape);
1578 let read_base;
1579 let before: Option<&dyn Any> = match (&base, units) {
1580 (_, false) => None,
1581 (Some(base), true) => Some(base.as_ref()),
1582 (None, true) => {
1583 read_base = (record.read)(doc).map_err(model_refused)?;
1584 Some(read_base.as_ref())
1585 }
1586 };
1587 match checked {
1589 Checked::Now => (record.check)(current.as_ref()).map_err(refusal_refused)?,
1590 Checked::AtTheEnd => {
1591 crate::group::check_or_defer(
1592 format!("{}@root", (record.name)()),
1593 doc,
1594 move |doc| match (record.read)(doc) {
1595 Ok(read) => (record.check)(read.as_ref()),
1596 Err(error) => Err(crate::Refusal::new(error.to_string())),
1597 },
1598 )
1599 .map_err(refusal_refused)?;
1600 }
1601 }
1602 if let Some(before) = before {
1603 let edits = (record.diff)(before, current.as_ref());
1604 crate::footprint::check_edits_of(record.shape, &edits, &footprints)
1605 .map_err(refusal_refused)?;
1606 }
1607 crate::apply_cache::begin_storing();
1608 match (&base, &dirty) {
1609 (Some(base), Some(dirty)) => {
1610 (record.write_changed)(current.as_ref(), base.as_ref(), doc, dirty)
1611 }
1612 _ => (record.write)(current.as_ref(), doc),
1613 }
1614 .map_err(model_refused)?;
1615 if units {
1616 crate::footprint::index(doc, record.shape).map_err(super::automerge_refused)?;
1617 }
1618 crate::apply_cache::seal_stored(doc);
1619 crate::apply_cache::keep_open((record.kind)(), current, doc);
1621 Ok(())
1622 }
1623}
1624
1625pub(crate) use held::{begin as hold_records, end as drop_held, flush_all as write_held};
1626
1627impl<O: Operation> tilo_actions::Action for Stamped<O> {
1628 fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
1631 let payload = serde_json::to_vec(self).map_err(ActionError::Encode)?;
1632 apply_operation(
1633 &ResourceOf::<O::Record>::OPS,
1634 &self.operation,
1635 (&payload, self.now_ms),
1636 doc,
1637 )
1638 }
1639
1640 fn locus(&self) -> ExecutionLocus {
1641 ExecutionLocus::ClientLocal
1642 }
1643
1644 fn risk(&self) -> RiskLevel {
1645 self.operation.risk()
1646 }
1647
1648 fn change_kind(&self) -> tilo_actions::ChangeKind {
1652 match self.operation.edit().map(crate::Edit::op) {
1653 Some(crate::EditOp::Settle { .. }) => tilo_actions::ChangeKind::External,
1654 Some(crate::EditOp::Forget { .. }) => tilo_actions::ChangeKind::Housekeeping,
1655 _ => self.operation.change_kind(),
1656 }
1657 }
1658
1659 fn action_kind(&self) -> ActionKind {
1660 self.operation.kind()
1661 }
1662
1663 fn incoming_message(&self) -> bool {
1664 self.operation.incoming_message()
1665 }
1666
1667 fn irreversible(&self) -> bool {
1668 self.operation.irreversible()
1669 }
1670
1671 fn leaves(&self) -> bool {
1672 self.operation.leaves()
1673 }
1674
1675 fn inverse_encoded(&self, doc: &Doc) -> Option<tilo_actions::EncodedAction> {
1679 self.compensation(doc)
1680 }
1681
1682 fn compensates(&self) -> bool {
1683 self.compensated()
1684 }
1685
1686 fn describe(&self, doc: &Doc) -> Option<tilo_actions::Described> {
1689 let shape = <O::Record as crate::Model>::SHAPE;
1690 if let Some(edit) = self.operation.edit() {
1691 return crate::describe::edit(doc, shape, edit);
1692 }
1693 let value = crate::__private::json_via_bytes(&self.operation).ok()?;
1694 crate::describe::verb(doc, shape, O::KIND, &value)
1695 }
1696
1697 fn made(&self, doc: &Doc) -> Option<tilo_actions::ActionItem> {
1702 crate::describe::made::<O::Record>(doc)
1703 }
1704}
1705
1706pub struct ActionRef<R, A> {
1718 pub id: &'static str,
1719 pub params: &'static [&'static str],
1720 kind: ResourceKind,
1723 marker: PhantomData<fn(A) -> R>,
1724}
1725
1726impl<R, A> Clone for ActionRef<R, A> {
1727 fn clone(&self) -> Self {
1728 *self
1729 }
1730}
1731impl<R, A> Copy for ActionRef<R, A> {}
1732
1733impl<R, A> std::fmt::Debug for ActionRef<R, A> {
1734 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1735 f.debug_struct("ActionRef")
1736 .field("id", &self.id)
1737 .field("params", &self.params)
1738 .field("kind", &self.kind())
1739 .finish_non_exhaustive()
1740 }
1741}
1742
1743impl<R, A> ActionRef<R, A> {
1744 #[must_use]
1746 pub const fn id(&self) -> &'static str {
1747 self.id
1748 }
1749
1750 #[must_use]
1752 pub const fn params(&self) -> &'static [&'static str] {
1753 self.params
1754 }
1755
1756 #[must_use]
1758 pub const fn kind(&self) -> &ResourceKind {
1759 &self.kind
1760 }
1761
1762 #[must_use]
1766 pub fn key(&self) -> ActionKey {
1767 ActionKey::new(self.kind.declaring_app(), self.kind.kind(), self.id)
1768 }
1769}
1770
1771impl<E: crate::Effect, A> ActionRef<E, A> {
1772 #[must_use]
1776 pub fn spec(&self) -> Option<tilo_actions::ActionSpec> {
1777 E::spec(self.id)
1778 }
1779
1780 pub fn binding(
1789 &self,
1790 resource: impl Into<String>,
1791 ) -> Result<tilo_actions::ActionBinding<()>, tilo_actions::ActionBindingError> {
1792 let resource = resource.into();
1793 let spec = E::spec(self.id).ok_or_else(|| {
1794 tilo_actions::ActionBindingError::ActionNotExported {
1795 resource: resource.clone(),
1796 action: self.id.to_owned(),
1797 }
1798 })?;
1799 tilo_actions::ActionBinding::declared(resource, spec)
1800 }
1801}
1802
1803impl<R, A: Serialize> ActionRef<R, A> {
1804 #[must_use]
1809 pub const fn new(
1810 id: &'static str,
1811 params: &'static [&'static str],
1812 kind: ResourceKind,
1813 ) -> Self {
1814 Self {
1815 id,
1816 params,
1817 kind,
1818 marker: PhantomData,
1819 }
1820 }
1821
1822 #[must_use]
1828 pub fn on(&self, resource: impl Into<String>) -> tilo_actions::ActionAddress {
1829 tilo_actions::ActionAddress::new(resource, self.id)
1830 }
1831
1832 pub fn arguments(
1835 &self,
1836 input: &A,
1837 ) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1838 bind_serialized(
1841 self.id,
1842 self.params,
1843 crate::__private::json_via_bytes(input),
1844 )
1845 }
1846
1847 pub fn with(&self, input: impl Into<A>) -> Invoke<R> {
1853 Invoke::bound(self.id, self.arguments(&input.into()))
1854 }
1855
1856 pub fn try_with(&self, input: impl Into<A>) -> Result<Invoke<R>, String> {
1858 let invoke = self.with(input);
1859 match invoke.refusal {
1860 Some(refusal) => Err(refusal),
1861 None => Ok(invoke),
1862 }
1863 }
1864}
1865
1866#[inline(never)]
1869fn bind_serialized(
1870 id: &'static str,
1871 params: &'static [&'static str],
1872 value: Result<serde_json::Value, serde_json::Error>,
1873) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1874 match value {
1875 Ok(value) => bind_arguments(id, params, value),
1876 Err(error) => Err(format!("`{id}`: {error}")),
1877 }
1878}
1879
1880fn bind_arguments(
1883 id: &str,
1884 params: &[&str],
1885 value: serde_json::Value,
1886) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1887 let given = |fields: Vec<(String, serde_json::Value)>| {
1889 fields
1890 .into_iter()
1891 .filter(|(_, value)| !value.is_null())
1892 .collect()
1893 };
1894 match (params, value) {
1895 ([], serde_json::Value::Object(fields)) => Ok(given(fields.into_iter().collect())),
1896 ([], serde_json::Value::Null) => Ok(serde_json::Map::new()),
1897 ([], other) => Err(format!("`{id}` takes named arguments, not `{other}`")),
1898 ([single], value) => Ok(given(vec![((*single).to_owned(), value)])),
1899 (names, serde_json::Value::Array(values)) if values.len() == names.len() => Ok(given(
1900 names
1901 .iter()
1902 .map(|name| (*name).to_owned())
1903 .zip(values)
1904 .collect(),
1905 )),
1906 (names, other) => Err(format!(
1907 "`{id}` takes {} arguments ({}), not `{other}`",
1908 names.len(),
1909 names.join(", ")
1910 )),
1911 }
1912}
1913
1914impl<R, A: Serialize> ActionRef<R, A> {
1915 pub fn map<I, T, F>(self, map: F) -> Mapped<R, A, F>
1918 where
1919 F: Fn(I) -> T,
1920 T: Into<A>,
1921 {
1922 Mapped { action: self, map }
1923 }
1924
1925 pub fn try_map<I, T, F>(self, parse: F) -> TryMapped<R, A, F>
1935 where
1936 F: Fn(I) -> Option<T>,
1937 T: Into<A>,
1938 {
1939 TryMapped {
1940 action: self,
1941 parse,
1942 }
1943 }
1944}
1945
1946pub struct TryMapped<R, A, F> {
1949 action: ActionRef<R, A>,
1950 parse: F,
1951}
1952
1953impl<R, A, F: Clone> Clone for TryMapped<R, A, F> {
1954 fn clone(&self) -> Self {
1955 Self {
1956 action: self.action,
1957 parse: self.parse.clone(),
1958 }
1959 }
1960}
1961
1962pub struct Mapped<R, A, F> {
1964 action: ActionRef<R, A>,
1965 map: F,
1966}
1967
1968impl<R, A, F: Clone> Clone for Mapped<R, A, F> {
1969 fn clone(&self) -> Self {
1970 Self {
1971 action: self.action,
1972 map: self.map.clone(),
1973 }
1974 }
1975}
1976
1977pub trait Binds<R, I>: Send + Sync + 'static {
1980 fn action_id(&self) -> &'static str;
1981
1982 fn action_key(&self) -> ActionKey
1987 where
1988 R: Resource,
1989 {
1990 ActionKey::new(R::APP_ID, R::KIND, self.action_id())
1991 }
1992
1993 fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String>;
1998}
1999
2000impl<R: 'static, A: Serialize + 'static, I: Into<A>> Binds<R, I> for ActionRef<R, A> {
2003 fn action_id(&self) -> &'static str {
2004 self.id
2005 }
2006 fn action_key(&self) -> ActionKey {
2007 ActionRef::key(self)
2008 }
2009 fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
2010 ActionRef::arguments(self, &input.into())
2011 }
2012}
2013
2014impl<R, A, I, T, F> Binds<R, I> for Mapped<R, A, F>
2015where
2016 R: 'static,
2017 A: Serialize + 'static,
2018 T: Into<A>,
2019 F: Fn(I) -> T + Send + Sync + 'static,
2020{
2021 fn action_id(&self) -> &'static str {
2022 self.action.id
2023 }
2024 fn action_key(&self) -> ActionKey {
2025 ActionRef::key(&self.action)
2026 }
2027 fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
2028 self.action.arguments(&(self.map)(input).into())
2029 }
2030}
2031
2032impl<R, A, I, T, F> Binds<R, I> for TryMapped<R, A, F>
2033where
2034 R: 'static,
2035 A: Serialize + 'static,
2036 T: Into<A>,
2037 F: Fn(I) -> Option<T> + Send + Sync + 'static,
2038{
2039 fn action_id(&self) -> &'static str {
2040 self.action.id
2041 }
2042 fn action_key(&self) -> ActionKey {
2043 ActionRef::key(&self.action)
2044 }
2045 fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
2046 let Some(parsed) = (self.parse)(input) else {
2047 return Err(no_arguments(self.action.id));
2048 };
2049 self.action.arguments(&parsed.into())
2050 }
2051}
2052
2053#[inline(never)]
2056fn no_arguments(id: &str) -> String {
2057 format!("the input makes no arguments for `{id}`")
2058}
2059
2060pub trait NoParams {}
2063
2064impl NoParams for () {}
2065
2066pub trait Params: Serialize + DeserializeOwned + crate::JsonSchema + Clone + 'static {
2070 type Resource;
2072 type Paths: Clone;
2074 const ACTION: ActionRef<Self::Resource, Self>;
2076
2077 fn paths() -> Self::Paths;
2079}
2080
2081impl<R, A: NoParams> ActionRef<R, A> {
2082 pub fn invoke(&self) -> Invoke<R> {
2084 Invoke {
2085 id: self.id,
2086 arguments: serde_json::Map::new(),
2087 refusal: None,
2088 effect: false,
2089 on: None,
2090 marker: PhantomData,
2091 }
2092 }
2093}
2094
2095pub struct Invoke<R> {
2098 pub id: &'static str,
2099 pub arguments: serde_json::Map<String, serde_json::Value>,
2100 refusal: Option<String>,
2102 effect: bool,
2103 on: Option<String>,
2105 marker: PhantomData<fn() -> R>,
2106}
2107
2108impl<R> Clone for Invoke<R> {
2109 fn clone(&self) -> Self {
2110 Self {
2111 id: self.id,
2112 arguments: self.arguments.clone(),
2113 refusal: self.refusal.clone(),
2114 effect: self.effect,
2115 on: self.on.clone(),
2116 marker: PhantomData,
2117 }
2118 }
2119}
2120
2121impl<R> std::fmt::Debug for Invoke<R> {
2122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2123 f.debug_struct("Invoke")
2124 .field("id", &self.id)
2125 .field("arguments", &self.arguments)
2126 .field("refusal", &self.refusal)
2127 .field("effect", &self.effect)
2128 .field("on", &self.on)
2129 .finish()
2130 }
2131}
2132
2133impl<R> Invoke<R> {
2134 pub fn effect<E: crate::Effect>(effect: &E) -> Self {
2143 let id = effect.id();
2144 let refusal = E::declaration(id)
2145 .is_some_and(|declaration| declaration.row)
2146 .then(|| format!("`{id}` is offered only on rows: invoke it on one"));
2147 Self {
2148 id,
2149 arguments: effect.arguments(),
2150 refusal,
2151 effect: true,
2152 on: None,
2153 marker: PhantomData,
2154 }
2155 }
2156
2157 #[must_use]
2160 pub fn on(mut self, row: impl Into<String>) -> Self {
2161 if self.effect {
2162 self.refusal = None;
2163 }
2164 self.on = Some(row.into());
2165 self
2166 }
2167
2168 pub fn row(&self) -> Option<&str> {
2170 self.on.as_deref()
2171 }
2172
2173 #[inline(never)]
2177 pub(crate) fn bound(
2178 id: &'static str,
2179 bound: Result<serde_json::Map<String, serde_json::Value>, String>,
2180 ) -> Self {
2181 let (arguments, refusal) = match bound {
2182 Ok(arguments) => (arguments, None),
2183 Err(refusal) => (serde_json::Map::new(), Some(refusal)),
2184 };
2185 Self {
2186 id,
2187 arguments,
2188 refusal,
2189 effect: false,
2190 on: None,
2191 marker: PhantomData,
2192 }
2193 }
2194
2195 pub fn refusal(&self) -> Option<&str> {
2198 self.refusal.as_deref()
2199 }
2200
2201 pub fn is_effect(&self) -> bool {
2204 self.effect
2205 }
2206
2207 #[must_use]
2210 pub fn address_on(&self, resource: impl Into<String>) -> tilo_actions::ActionAddress {
2211 tilo_actions::ActionAddress::new(resource, self.id)
2212 }
2213}
2214
2215impl<R: Resource> Invoke<R> {
2216 #[must_use]
2218 pub fn address(&self) -> tilo_actions::ActionAddress {
2219 self.address_on(R::KIND)
2220 }
2221
2222 pub fn apply(action: &R::Action) -> Result<Self, serde_json::Error> {
2228 let value = match crate::__private::json_via_bytes(action)? {
2231 serde_json::Value::String(variant) => serde_json::Value::Object(
2232 serde_json::Map::from_iter([(variant, serde_json::Value::Null)]),
2233 ),
2234 value => value,
2235 };
2236 Ok(Self {
2237 id: crate::APPLY,
2238 arguments: serde_json::Map::from_iter([(crate::APPLY_PARAM.to_owned(), value)]),
2239 refusal: None,
2240 effect: false,
2241 on: None,
2242 marker: PhantomData,
2243 })
2244 }
2245
2246 pub fn edit(edit: &crate::Edit<R>) -> Result<Self, serde_json::Error> {
2251 Ok(Self {
2252 id: crate::FIELD_EDIT,
2253 arguments: serde_json::Map::from_iter([(
2254 crate::EDIT_PARAM.to_owned(),
2255 crate::__private::json_via_bytes(edit)?,
2256 )]),
2257 refusal: None,
2258 effect: false,
2259 on: None,
2260 marker: PhantomData,
2261 })
2262 }
2263
2264 fn from_edit(edit: &crate::Edit<R>) -> Self {
2268 Self::edit(edit).unwrap_or_else(|error| Self {
2269 id: crate::FIELD_EDIT,
2270 arguments: serde_json::Map::new(),
2271 refusal: Some(error.to_string()),
2272 effect: false,
2273 on: None,
2274 marker: PhantomData,
2275 })
2276 }
2277
2278 pub fn group(members: impl IntoIterator<Item = Self>) -> Self {
2281 let mut actions = Vec::new();
2282 let mut refusal = None;
2283 for member in members {
2284 if refusal.is_none() {
2285 refusal.clone_from(&member.refusal);
2286 }
2287 if member.is_group() {
2288 if let Some(serde_json::Value::Array(inner)) =
2289 member.arguments.get(crate::GROUP_PARAM)
2290 {
2291 actions.extend(inner.iter().cloned());
2292 }
2293 } else {
2294 actions.push(serde_json::json!({
2295 "action": member.id,
2296 "args": member.arguments,
2297 }));
2298 }
2299 }
2300 Self {
2301 id: crate::GROUP,
2302 arguments: serde_json::Map::from_iter([(
2303 crate::GROUP_PARAM.to_owned(),
2304 serde_json::Value::Array(actions),
2305 )]),
2306 refusal,
2307 effect: false,
2308 on: None,
2309 marker: PhantomData,
2310 }
2311 }
2312
2313 pub fn is_group(&self) -> bool {
2315 self.id == crate::GROUP
2316 }
2317
2318 pub fn build(&self, now_ms: i64) -> Result<R::Action, String> {
2321 if let Some(refusal) = &self.refusal {
2322 return Err(refusal.clone());
2323 }
2324 if let Some(built) = R::build_by_app(self.id, &self.arguments, now_ms) {
2327 return built;
2328 }
2329 crate::resource::build_action::<R>(self.id, &self.arguments, now_ms)
2330 }
2331}
2332
2333impl<R: Resource> From<crate::Edit<R>> for Invoke<R> {
2334 fn from(edit: crate::Edit<R>) -> Self {
2335 Self::from_edit(&edit)
2336 }
2337}
2338
2339impl<R: Resource> From<&crate::Edit<R>> for Invoke<R> {
2340 fn from(edit: &crate::Edit<R>) -> Self {
2341 Self::from_edit(edit)
2342 }
2343}
2344
2345#[cfg(test)]
2346mod seed_tests {
2347 use super::*;
2348 use automerge::transaction::Transactable as _;
2349
2350 #[test]
2351 fn a_seed_read_mid_transaction_leaves_it_open_and_moves_with_it() {
2352 let mut doc = Doc::new();
2353 doc.put(ROOT, "a", 1).unwrap();
2354 doc.commit();
2355 let committed = seed(&doc, b"test", b"payload");
2356 doc.put(ROOT, "b", 2).unwrap();
2357 let base = doc.base_heads();
2358 let open = seed(&doc, b"test", b"payload");
2359 assert!(doc.pending_ops() > 0, "reading the seed commits nothing");
2360 assert_eq!(doc.base_heads(), base);
2361 assert_ne!(open, committed, "an open transaction moves the seed");
2362 doc.put(ROOT, "c", 3).unwrap();
2363 assert_ne!(seed(&doc, b"test", b"payload"), open);
2364 doc.commit();
2365 assert_ne!(seed(&doc, b"test", b"payload"), committed);
2366 }
2367}