Skip to main content

tablo_core/resource/
commit.rs

1//! What a write changed, and the one place the framework hands it to the app's hooks.
2
3use topcoat::context::Cx;
4
5use super::{Action, HeaderAction, Resource};
6
7/// What one write of a resource changed: the mutation and the rows it wrote.
8///
9/// [`Resource::before_commit`] receives it inside the write's transaction and
10/// [`Resource::after_commit`] once the transaction commits. An [`Export`](Change::Export) writes
11/// nothing and reaches `before_commit` alone.
12///
13/// The enum is exhaustive on purpose: an audit hook that matches every variant stops compiling
14/// when a new kind of write appears, instead of skipping it.
15///
16/// A create or an update that also links or unlinks records through a many-to-many form field
17/// reports the record only: the links are not in `M`. Read them through the hook's executor when
18/// an audit needs them; the relation table's own writes report as [`Change::Attach`] and
19/// [`Change::Detach`].
20///
21/// A save that also writes a [`Relation::has_one`](crate::Relation::has_one)'s child reports the
22/// owner here, and the child to the related resource's hooks, as its own pages would.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum Change<M> {
25    /// A create wrote this row.
26    Create(M),
27    /// An update wrote `after` over `before`, the snapshot the handler loaded and authorized
28    /// inside the transaction. A submission that names no field writes nothing and still
29    /// reports an update, with `before == after`.
30    Update { before: M, after: M },
31    /// A delete or a bulk delete removed these rows, or trashed them on a soft-deleting resource,
32    /// as they stood before the delete.
33    Delete(Vec<M>),
34    /// A restore brought back these trashed rows, as they stood before it: their deleted-at
35    /// column still holds the time they were trashed.
36    Restore(Vec<M>),
37    /// A force delete removed these trashed rows for good, as they stood before it.
38    ForceDelete(Vec<M>),
39    /// The custom [`Action`] `name` ran on these rows: each as the handler loaded it before the
40    /// run, and as the run left it, reloaded inside the transaction.
41    Action {
42        name: &'static str,
43        records: Vec<Acted<M>>,
44    },
45    /// The [`HeaderAction`](crate::HeaderAction) `name` ran, on no record: its audit can record
46    /// who ran it, through the context, and which action.
47    HeaderAction { name: &'static str },
48    /// A many-to-many relation's table linked `owner` to the related record `key` names.
49    ///
50    /// `relation` is the owner's `#[has_many(via = ..)]` field and `key` the related resource's
51    /// record key, as its URLs spell it whatever spelling the request posted. Attaching a linked
52    /// record writes nothing and still reports the attach.
53    Attach {
54        owner: M,
55        relation: String,
56        key: String,
57    },
58    /// A many-to-many relation's table unlinked `owner` from the related records `keys` name, as
59    /// their URLs spell them.
60    Detach {
61        owner: M,
62        relation: String,
63        keys: Vec<String>,
64    },
65    /// The CSV export hands `rows` rows of the list, as its filters narrow it, to the user. It
66    /// writes nothing: [`Resource::before_commit`] runs in a transaction of its own that commits
67    /// before the first byte leaves, so an audit records who took the rows, and an `Err` refuses
68    /// the export. [`Resource::after_commit`] does not run.
69    Export { rows: u64 },
70}
71
72/// One row a custom [`Action`] ran on, as [`Change::Action`] reports it.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Acted<M> {
75    /// The row as the handler loaded and authorized it, before the run.
76    pub before: M,
77    /// The row as the run left it, reloaded by its key under the resource's tenant filter alone:
78    /// a [`query`](crate::ResourceDef::query) narrowing or the trash does not hide it, so an
79    /// action that archives or trashes the row still reports it. `None` when the run deleted
80    /// the row or moved it out of the request's tenant.
81    pub after: Option<M>,
82}
83
84impl<M> Acted<M> {
85    /// The row as the run left it, or as it stood before a run that removed it.
86    pub fn record(&self) -> &M {
87        self.after.as_ref().unwrap_or(&self.before)
88    }
89}
90
91impl<M> Change<M> {
92    /// The rows of this resource the change names: the created row, the updated row and each
93    /// row an action ran on as the write left it ([`Acted::record`]), the deleted, restored or
94    /// force-deleted rows as they stood before it, the owner of an attach or a detach, and none
95    /// for a header action or an export.
96    pub fn records(&self) -> Vec<&M> {
97        match self {
98            Self::Create(record)
99            | Self::Update { after: record, .. }
100            | Self::Attach { owner: record, .. }
101            | Self::Detach { owner: record, .. } => vec![record],
102            Self::Delete(records) | Self::Restore(records) | Self::ForceDelete(records) => {
103                records.iter().collect()
104            }
105            Self::Action { records, .. } => records.iter().map(Acted::record).collect(),
106            Self::HeaderAction { .. } | Self::Export { .. } => Vec::new(),
107        }
108    }
109
110    /// The same change, each record read through `f`.
111    pub(crate) fn map<N>(&self, f: impl Fn(&M) -> N) -> Change<N> {
112        match self {
113            Self::Create(record) => Change::Create(f(record)),
114            Self::Update { before, after } => Change::Update {
115                before: f(before),
116                after: f(after),
117            },
118            Self::Delete(records) => Change::Delete(records.iter().map(f).collect()),
119            Self::Restore(records) => Change::Restore(records.iter().map(f).collect()),
120            Self::ForceDelete(records) => Change::ForceDelete(records.iter().map(f).collect()),
121            Self::Action { name, records } => Change::Action {
122                name,
123                records: records
124                    .iter()
125                    .map(|acted| Acted {
126                        before: f(&acted.before),
127                        after: acted.after.as_ref().map(&f),
128                    })
129                    .collect(),
130            },
131            Self::HeaderAction { name } => Change::HeaderAction { name },
132            Self::Export { rows } => Change::Export { rows: *rows },
133            Self::Attach {
134                owner,
135                relation,
136                key,
137            } => Change::Attach {
138                owner: f(owner),
139                relation: relation.clone(),
140                key: key.clone(),
141            },
142            Self::Detach {
143                owner,
144                relation,
145                keys,
146            } => Change::Detach {
147                owner: f(owner),
148                relation: relation.clone(),
149                keys: keys.clone(),
150            },
151        }
152    }
153
154    /// Whether the change is a run of the custom action `A`.
155    ///
156    /// It compares against `A::NAME`, as [`Ability::is_action`](crate::Ability::is_action) does,
157    /// and a type that is not an action of a resource over `M` does not compile. `R` is inferred
158    /// when `A` is an action of one resource.
159    ///
160    /// ```rust
161    /// # use tablo_core::{Action, Change, NoForm, Resource};
162    /// # use topcoat::{Result, context::Cx};
163    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
164    /// # struct Post { #[key] #[auto] id: uuid::Uuid, published: bool }
165    /// # struct PostResource;
166    /// # impl Resource for PostResource {
167    /// #     type Model = Post;
168    /// #     type Form = NoForm<Post>;
169    /// # }
170    /// # struct Publish;
171    /// # impl Action<PostResource> for Publish {
172    /// #     type Input = ();
173    /// #     const NAME: &'static str = "publish";
174    /// #     async fn run(_: &Cx, _: &[Post], _: (), _: &mut dyn toasty::Executor) -> Result<tablo_core::Outcome, tablo_core::WriteError<()>> { Ok(tablo_core::Outcome::done()) }
175    /// # }
176    /// fn published(change: &Change<Post>) -> usize {
177    ///     if change.is_action::<Publish, _>() {
178    ///         change.records().len()
179    ///     } else {
180    ///         0
181    ///     }
182    /// }
183    /// ```
184    pub fn is_action<A, R>(&self) -> bool
185    where
186        A: Action<R>,
187        R: Resource<Model = M>,
188    {
189        matches!(self, Self::Action { name, .. } if *name == A::NAME)
190    }
191
192    /// Whether the change is a run of the header action `A`.
193    ///
194    /// It compares against `A::NAME`, as
195    /// [`Ability::is_header_action`](crate::Ability::is_header_action) does.
196    ///
197    /// ```rust
198    /// # use tablo_core::{Change, HeaderAction};
199    /// # use topcoat::{Result, context::Cx};
200    /// # #[derive(Debug, Clone, toasty::Model, tablo_core::PanelModel)]
201    /// # struct Post { #[key] #[auto] id: uuid::Uuid }
202    /// # struct RecountTags;
203    /// # impl HeaderAction for RecountTags {
204    /// #     type Input = ();
205    /// #     const NAME: &'static str = "recount-tags";
206    /// #     async fn run(_: &Cx, _: (), _: &mut dyn toasty::Executor) -> Result<tablo_core::Outcome, tablo_core::WriteError<()>> { Ok(tablo_core::Outcome::done()) }
207    /// # }
208    /// fn audited(change: &Change<Post>) -> bool {
209    ///     !change.is_header_action::<RecountTags>()
210    /// }
211    /// ```
212    pub fn is_header_action<A: HeaderAction>(&self) -> bool {
213        matches!(self, Self::HeaderAction { name } if *name == A::NAME)
214    }
215}
216
217/// Hand a committed change to the app.
218///
219/// A hook returning `Err` is logged and ignored: the write stays committed.
220pub(crate) async fn run_after_commit<R: Resource>(cx: &Cx, change: Change<R::Model>) {
221    if let Err(error) = R::after_commit(cx, change).await {
222        tracing::error!(
223            error = %error,
224            resource = std::any::type_name::<R>(),
225            "after_commit failed; the write stays committed"
226        );
227    }
228}