Skip to main content

tablo_core/panel/
commit_hook.rs

1//! [`Panel::before_commit`]: the hooks every write of a panel runs inside its transaction, whichever
2//! resource wrote it.
3
4use std::{any::TypeId, future::Future};
5
6use toasty::Executor;
7use topcoat::{Result, context::Cx};
8
9use super::{Panel, state::current};
10use crate::{
11    BoxFuture, PanelModel, Text,
12    resource::{Acted, Change, Resource, require_mounted},
13};
14
15/// Work every write of a panel does inside its transaction, whichever of the panel's resources
16/// wrote it: an audit trail no resource can leave out. [`Panel::before_commit`] registers it.
17///
18/// It runs on the writes [`Resource::before_commit`] runs on, and on a CSV export, right after
19/// that hook, with the
20/// same transaction and the same rules: run every statement through `ex`, and an `Err` rolls the
21/// whole write back and fails the request with the write's failure toast.
22///
23/// ```rust
24/// # use tablo_core::{Change, CommitHook, PanelChange};
25/// # use topcoat::{Result, context::Cx};
26/// # #[derive(Debug, toasty::Model)]
27/// # struct AuditEntry { #[key] #[auto] id: uuid::Uuid, resource: String, record: String }
28/// struct Audit;
29///
30/// impl CommitHook for Audit {
31///     async fn before_commit(
32///         cx: &Cx,
33///         change: &PanelChange,
34///         ex: &mut dyn toasty::Executor,
35///     ) -> Result<()> {
36///         for record in change.change().records() {
37///             toasty::create!(AuditEntry {
38///                 resource: change.label().localize(cx),
39///                 record: record.key().to_string(),
40///             })
41///             .exec(&mut *ex)
42///             .await?;
43///         }
44///         Ok(())
45///     }
46/// }
47/// ```
48pub trait CommitHook: 'static {
49    /// Work inside the write's transaction, after the resource's own
50    /// [`Resource::before_commit`].
51    fn before_commit(
52        cx: &Cx,
53        change: &PanelChange,
54        ex: &mut dyn Executor,
55    ) -> impl Future<Output = Result<()>> + Send;
56}
57
58/// A [`Change`] as a [`CommitHook`] receives it: the resource that wrote it, and each record it
59/// names by its key, its URL and the fields the write changed.
60#[derive(Debug, Clone, PartialEq)]
61pub struct PanelChange {
62    slug: String,
63    label: Text,
64    change: Change<ChangedRecord>,
65}
66
67impl PanelChange {
68    /// The slug of the resource that wrote, as its URLs spell it: `posts`.
69    pub fn slug(&self) -> &str {
70        &self.slug
71    }
72
73    /// The resource's label: `Post`, or the message its catalog spells it with.
74    pub fn label(&self) -> &Text {
75        &self.label
76    }
77
78    /// What the write changed, each record named by its key, URL and fields.
79    pub fn change(&self) -> &Change<ChangedRecord> {
80        &self.change
81    }
82}
83
84/// A record a [`PanelChange`] names.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct ChangedRecord {
87    key: String,
88    url: Option<String>,
89    fields: Vec<ChangedField>,
90}
91
92impl ChangedRecord {
93    /// The record's key, as its URLs spell it: `42`.
94    pub fn key(&self) -> &str {
95        &self.key
96    }
97
98    /// The record's detail page, as [`url::record`](crate::url::record) spells it; `None` when
99    /// the resource serves none.
100    pub fn url(&self) -> Option<&str> {
101        self.url.as_deref()
102    }
103
104    /// The fields the write changed on this record, each with its value before and after it.
105    ///
106    /// They are the fields the model's [`PanelModel::table`] lists, each spelled as that column
107    /// spells it in an export, in the request's locale, then its foreign keys and
108    /// [`TenantId`](crate::TenantId) fields, which the table leaves out, spelled as the database
109    /// stores them: a field marked `#[columns(skip)]`, such as a password hash, never appears. A
110    /// create names each field it filled, an update's `after` record and an action's
111    /// [`Acted::after`](crate::Acted::after) each field whose spelling changed, and a delete's or
112    /// a force delete's records, and an action's `before` for a row the run removed, each field
113    /// they held. The other records name none: a restore, an attach and a detach write what the
114    /// model's columns do not say, and an update's or an action's `before` record leaves the
115    /// change to its `after`. An action that writes only other tables names none either.
116    pub fn fields(&self) -> &[ChangedField] {
117        &self.fields
118    }
119}
120
121/// One field a write changed on a [`ChangedRecord`]: its name, its label, and its spelling before
122/// and after the write, `None` where it held nothing.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct ChangedField {
125    name: String,
126    label: Text,
127    before: Option<String>,
128    after: Option<String>,
129}
130
131impl ChangedField {
132    /// The column's name, the model field it reads: `title`.
133    pub fn name(&self) -> &str {
134        &self.name
135    }
136
137    /// The column's label: `Title`, or the message its catalog spells it with.
138    pub fn label(&self) -> &Text {
139        &self.label
140    }
141
142    /// The field's spelling before the write; `None` for a create, or a field that held nothing.
143    pub fn before(&self) -> Option<&str> {
144        self.before.as_deref()
145    }
146
147    /// The field's spelling after the write; `None` for a delete, or a field left empty.
148    pub fn after(&self) -> Option<&str> {
149        self.after.as_deref()
150    }
151}
152
153/// The fields `before` and `after` spell differently, by the columns of `M`'s default table and
154/// its [`references`](PanelModel::references); a record that is absent spells every field empty.
155fn changed_fields<M: PanelModel>(
156    cx: &Cx,
157    before: Option<&M>,
158    after: Option<&M>,
159) -> Vec<ChangedField> {
160    let table = M::table();
161    let (before_record, after_record) = (before, after);
162    let spell = |record: Option<&M>| record.map(|record| table.spell(cx, record));
163    let (before, after) = (spell(before), spell(after));
164    let columns = after.as_ref().or(before.as_ref()).map_or(0, Vec::len);
165    let held = |spelled: &Option<Vec<(String, Text, String)>>, index: usize| {
166        spelled
167            .as_ref()
168            .map(|spelled| spelled[index].2.clone())
169            .filter(|text| !text.is_empty())
170    };
171    let mut changed: Vec<ChangedField> = (0..columns)
172        .filter_map(|index| {
173            let (was, is) = (held(&before, index), held(&after, index));
174            let (name, label, _) = after.as_ref().or(before.as_ref())?[index].clone();
175            (was != is).then_some(ChangedField {
176                name,
177                label,
178                before: was,
179                after: is,
180            })
181        })
182        .collect();
183    let references = |record: Option<&M>| record.map(PanelModel::references);
184    let (was, is) = (references(before_record), references(after_record));
185    let names = is.as_ref().or(was.as_ref()).cloned().unwrap_or_default();
186    for (index, (name, _)) in names.into_iter().enumerate() {
187        let held = |spelled: &Option<Vec<(&str, Option<String>)>>| {
188            spelled
189                .as_ref()
190                .and_then(|spelled| spelled[index].1.clone())
191        };
192        let (before, after) = (held(&was), held(&is));
193        if before != after && changed.iter().all(|field| field.name != name) {
194            changed.push(ChangedField {
195                name: name.to_owned(),
196                label: Text::field(name),
197                before,
198                after,
199            });
200        }
201    }
202    changed
203}
204
205/// `change` with each record named by its key and URL, and the fields the write changed on it.
206fn changed_records<R: Resource>(
207    cx: &Cx,
208    change: &Change<R::Model>,
209    key: impl Fn(&R::Model) -> String,
210) -> Change<ChangedRecord> {
211    let named = |record: &R::Model, fields| ChangedRecord {
212        key: key(record),
213        url: crate::url::record::<R>(cx, record),
214        fields,
215    };
216    let held = |records: &[R::Model]| {
217        records
218            .iter()
219            .map(|record| named(record, changed_fields(cx, Some(record), None)))
220            .collect()
221    };
222    match change {
223        Change::Create(record) => Change::Create(named(
224            record,
225            changed_fields::<R::Model>(cx, None, Some(record)),
226        )),
227        Change::Update { before, after } => Change::Update {
228            before: named(before, Vec::new()),
229            after: named(after, changed_fields(cx, Some(before), Some(after))),
230        },
231        Change::Delete(records) => Change::Delete(held(records)),
232        Change::ForceDelete(records) => Change::ForceDelete(held(records)),
233        // As an update: the record the run left names the fields it changed. A record the run
234        // removed names the fields it held, as a delete's does.
235        Change::Action { name, records } => Change::Action {
236            name,
237            records: records
238                .iter()
239                .map(|acted| Acted {
240                    before: named(
241                        &acted.before,
242                        match &acted.after {
243                            Some(_) => Vec::new(),
244                            None => changed_fields(cx, Some(&acted.before), None),
245                        },
246                    ),
247                    after: acted.after.as_ref().map(|after| {
248                        named(after, changed_fields(cx, Some(&acted.before), Some(after)))
249                    }),
250                })
251                .collect(),
252        },
253        other => other.map(|record| named(record, Vec::new())),
254    }
255}
256
257/// A registered [`CommitHook`], its type erased.
258pub(crate) type CommitHookFn =
259    for<'a> fn(&'a Cx, &'a PanelChange, &'a mut dyn Executor) -> BoxFuture<'a, Result<()>>;
260
261fn erased<'a, H: CommitHook>(
262    cx: &'a Cx,
263    change: &'a PanelChange,
264    ex: &'a mut dyn Executor,
265) -> BoxFuture<'a, Result<()>> {
266    Box::pin(H::before_commit(cx, change, ex))
267}
268
269impl Panel {
270    /// Runs the [`CommitHook`] `H` inside the transaction of every write of the panel, after the
271    /// writing resource's own [`Resource::before_commit`]. Several hooks run in the order they
272    /// are registered; registering `H` again changes nothing, so it never runs twice.
273    pub fn before_commit<H: CommitHook>(mut self) -> Self {
274        let id = TypeId::of::<H>();
275        if !self.commit_hooks.iter().any(|(hook, _)| *hook == id) {
276            self.commit_hooks.push((id, erased::<H>));
277        }
278        self
279    }
280}
281
282impl<R: Resource> crate::ResourceDef<R> {
283    /// Refuses to mount the resource on a panel that does not run the [`CommitHook`] `H`
284    /// ([`MissingCommitHook`](crate::DeclarationErrorKind::MissingCommitHook)): a list of what
285    /// `H` stores would stay empty, however it is placed.
286    #[must_use]
287    pub fn requires_commit_hook<H: CommitHook>(mut self) -> Self {
288        let hook = (TypeId::of::<H>(), std::any::type_name::<H>());
289        if !self.required_hooks.contains(&hook) {
290            self.required_hooks.push(hook);
291        }
292        self
293    }
294}
295
296/// A fault for each hook a registered resource requires that `hooks` leaves out.
297pub(super) fn missing_commit_hooks(
298    resources: &[super::register::Registered],
299    hooks: &[(TypeId, CommitHookFn)],
300) -> Vec<crate::DeclarationError> {
301    resources
302        .iter()
303        .flat_map(|resource| {
304            resource
305                .required_hooks
306                .iter()
307                .map(move |hook| (resource, hook))
308        })
309        .filter(|(_, (id, _))| !hooks.iter().any(|(hook, _)| hook == id))
310        .map(|(resource, (_, hook))| crate::DeclarationError {
311            resource: Some(resource.name),
312            site: crate::Site::Registration,
313            kind: crate::DeclarationErrorKind::MissingCommitHook { hook },
314        })
315        .collect()
316}
317
318/// Run `R`'s [`Resource::before_commit`] on `change`, then each of the panel's [`CommitHook`]s,
319/// inside the write's transaction `ex`.
320pub(crate) async fn before_commit<R: Resource>(
321    cx: &Cx,
322    change: &Change<R::Model>,
323    ex: &mut dyn Executor,
324) -> Result<()> {
325    R::before_commit(cx, change, &mut *ex).await?;
326    let hooks = current(cx).map_or(&[][..], |panel| panel.commit_hooks.as_slice());
327    if hooks.is_empty() {
328        return Ok(());
329    }
330    let mounted = require_mounted::<R>(cx)?;
331    let change = PanelChange {
332        slug: mounted.slug.clone(),
333        label: mounted.label.clone(),
334        change: changed_records::<R>(cx, change, |record| mounted.table.key_of(record)),
335    };
336    run(cx, hooks, &change, ex).await
337}
338
339/// Run each of `hooks` on `change`, stopping at the first error.
340fn run<'a>(
341    cx: &'a Cx,
342    hooks: &'a [CommitHookFn],
343    change: &'a PanelChange,
344    ex: &'a mut dyn Executor,
345) -> BoxFuture<'a, Result<()>> {
346    Box::pin(async move {
347        for hook in hooks {
348            hook(cx, change, &mut *ex).await?;
349        }
350        Ok(())
351    })
352}
353
354#[cfg(test)]
355mod tests;