Skip to main content

glacier/db/
multi.rs

1//! Multi-step transactions, as Ecto.Multi: named steps that run in order
2//! inside one transaction, each able to read the results of the steps
3//! before it. If one fails, everything is rolled back and the error names
4//! the step and why (its validation errors, or the error).
5//!
6//! ```ignore
7//! let done = Multi::new()
8//!     .insert("user", User::changeset().cast(&params))
9//!     .run("team", |done| async move {
10//!         let user: &User = done.get("user").unwrap();
11//!         Team::create(Team::changeset().set(|t| t.owner_id, user.id)).await?.into_step()
12//!     })
13//!     .enqueue("welcome", WelcomeEmail { email: email.clone() })
14//!     .commit()
15//!     .await;
16//! match done {
17//!     Ok(done) => { let user: &User = done.get("user").unwrap(); … }
18//!     Err(MultiError { step, failure: Failure::Invalid { errors, .. }, .. }) => { … }
19//!     Err(err) => return Err(err.into()),
20//! }
21//! ```
22
23use std::any::Any;
24use std::fmt;
25use std::future::Future;
26use std::pin::Pin;
27use std::sync::Arc;
28
29use super::{Changeset, Save};
30use crate::error::Error;
31use crate::model::Model;
32
33type StepFuture =
34    Pin<Box<dyn Future<Output = std::result::Result<Arc<dyn Any + Send + Sync>, Failure>> + Send>>;
35type Step = Box<dyn FnOnce(Done) -> StepFuture + Send>;
36
37/// Steps to run in one transaction (see the module docs).
38#[derive(Default)]
39pub struct Multi {
40    steps: Vec<(String, Step)>,
41}
42
43/// The results of the steps so far, by name.
44#[derive(Clone, Default)]
45pub struct Done {
46    results: Vec<(String, Arc<dyn Any + Send + Sync>)>,
47}
48
49/// Lists the steps that ran (their results are any type).
50impl fmt::Debug for Done {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        f.debug_struct("Done")
53            .field("steps", &self.steps())
54            .finish()
55    }
56}
57
58impl Done {
59    /// A step's result, when it has that type: the record an `insert` or
60    /// `update` saved, the value a `run` returned, a job's id.
61    pub fn get<T: Any>(&self, step: &str) -> Option<&T> {
62        self.results
63            .iter()
64            .find(|(name, _)| name == step)
65            .and_then(|(_, value)| value.downcast_ref::<T>())
66    }
67
68    /// The names of the steps that ran, in order.
69    pub fn steps(&self) -> Vec<&str> {
70        self.results.iter().map(|(name, _)| name.as_str()).collect()
71    }
72}
73
74/// Why a step failed.
75#[derive(Debug)]
76pub enum Failure {
77    /// A changeset didn't validate: its errors as `errors_json` gives them,
78    /// and as sentences.
79    Invalid {
80        errors: serde_json::Value,
81        messages: Vec<String>,
82    },
83    Error(Error),
84}
85
86impl From<Error> for Failure {
87    fn from(err: Error) -> Self {
88        Failure::Error(err)
89    }
90}
91
92/// A failed multi: the step that failed, why, and the steps that had run
93/// (all rolled back).
94#[derive(Debug)]
95pub struct MultiError {
96    pub step: String,
97    pub failure: Failure,
98    pub completed: Vec<String>,
99}
100
101impl fmt::Display for MultiError {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match &self.failure {
104            Failure::Invalid { messages, .. } => {
105                write!(
106                    f,
107                    "step `{}` was invalid: {}",
108                    self.step,
109                    messages.join(", ")
110                )
111            }
112            Failure::Error(err) => write!(f, "step `{}` failed: {}", self.step, err.message()),
113        }
114    }
115}
116
117/// So `multi.commit().await?` works in an action: an invalid step is a
118/// 422 carrying its errors, anything else the step's own error.
119impl From<MultiError> for Error {
120    fn from(err: MultiError) -> Self {
121        match err.failure {
122            Failure::Invalid { ref messages, .. } => {
123                Error::unprocessable(format!("{}: {}", err.step, messages.join(", ")))
124            }
125            Failure::Error(inner) => inner,
126        }
127    }
128}
129
130impl<M: Model> Save<M> {
131    /// The saved record, or the changeset's errors as a step failure:
132    /// for a `run` step that saves (`Post::create(…).await?.into_step()`).
133    pub fn into_step(self) -> std::result::Result<M, Failure> {
134        match self {
135            Save::Saved(record) => Ok(record),
136            Save::Invalid(changeset) => Err(invalid(&changeset)),
137        }
138    }
139}
140
141fn invalid<M: Model>(changeset: &Changeset<M>) -> Failure {
142    Failure::Invalid {
143        errors: changeset.errors_json(),
144        messages: changeset.full_messages(),
145    }
146}
147
148impl Multi {
149    pub fn new() -> Self {
150        Self::default()
151    }
152
153    /// Inserts a record from a changeset; its result is the saved record.
154    #[must_use]
155    pub fn insert<M>(self, name: &str, changeset: Changeset<M>) -> Self
156    where
157        M: Model + Send + Sync,
158        Changeset<M>: Send,
159    {
160        self.step(name, move |_| async move {
161            match changeset.insert().await? {
162                Save::Saved(record) => Ok(record),
163                Save::Invalid(changeset) => Err(invalid(&changeset)),
164            }
165        })
166    }
167
168    /// Updates a record from a changeset (`record.change()…`); its result
169    /// is the saved record.
170    #[must_use]
171    pub fn update<M>(self, name: &str, changeset: Changeset<M>) -> Self
172    where
173        M: Model + Send + Sync,
174        Changeset<M>: Send,
175    {
176        self.step(name, move |_| async move {
177            match changeset.update().await? {
178                Save::Saved(record) => Ok(record),
179                Save::Invalid(changeset) => Err(invalid(&changeset)),
180            }
181        })
182    }
183
184    /// Queues a background job with the rest: it only runs if the multi
185    /// commits. Its result is the job's id.
186    #[must_use]
187    pub fn enqueue<J: crate::jobs::Job>(self, name: &str, job: J) -> Self {
188        self.step(name, move |_| async move { Ok(job.enqueue().await?) })
189    }
190
191    /// Runs any work, given the results so far; its result is what it
192    /// returns. Return `Err(Failure::Invalid { … })` (or use
193    /// `Save::into_step`) to fail with validation errors, or any `Error`
194    /// with `?`.
195    #[must_use]
196    pub fn run<T, F, Fut>(self, name: &str, work: F) -> Self
197    where
198        T: Any + Send + Sync,
199        F: FnOnce(Done) -> Fut + Send + 'static,
200        Fut: Future<Output = std::result::Result<T, Failure>> + Send + 'static,
201    {
202        self.step(name, work)
203    }
204
205    fn step<T, F, Fut>(mut self, name: &str, work: F) -> Self
206    where
207        T: Any + Send + Sync,
208        F: FnOnce(Done) -> Fut + Send + 'static,
209        Fut: Future<Output = std::result::Result<T, Failure>> + Send + 'static,
210    {
211        assert!(
212            !self.steps.iter().any(|(n, _)| n == name),
213            "a Multi step is already named `{name}`"
214        );
215        let step: Step = Box::new(move |done| {
216            Box::pin(async move {
217                let value = work(done).await?;
218                Ok(Arc::new(value) as Arc<dyn Any + Send + Sync>)
219            })
220        });
221        self.steps.push((name.to_owned(), step));
222        self
223    }
224
225    /// Runs the steps in order in one transaction (a savepoint, inside
226    /// another transaction). All commit, or none do.
227    // Unboxed so callers can match on `MultiError { step, failure, .. }`.
228    #[allow(clippy::result_large_err)]
229    pub async fn commit(self) -> std::result::Result<Done, MultiError> {
230        // The failure, kept outside the transaction that rolls it back.
231        let failed = std::sync::Mutex::new(None);
232        let run = async {
233            let mut done = Done::default();
234            for (name, step) in self.steps {
235                match step(done.clone()).await {
236                    Ok(value) => done.results.push((name, value)),
237                    Err(failure) => {
238                        *failed.lock().unwrap_or_else(|e| e.into_inner()) = Some(MultiError {
239                            completed: done.steps().into_iter().map(str::to_owned).collect(),
240                            step: name,
241                            failure,
242                        });
243                        return Err(Error::internal("multi step failed"));
244                    }
245                }
246            }
247            Ok(done)
248        };
249        match super::savepoint(run).await {
250            Ok(done) => Ok(done),
251            Err(err) => Err(failed
252                .into_inner()
253                .unwrap_or_else(|e| e.into_inner())
254                .unwrap_or(MultiError {
255                    step: "commit".to_owned(),
256                    failure: Failure::Error(err),
257                    completed: Vec::new(),
258                })),
259        }
260    }
261}