glacier-web 0.2.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Multi-step transactions, as Ecto.Multi: named steps that run in order
//! inside one transaction, each able to read the results of the steps
//! before it. If one fails, everything is rolled back and the error names
//! the step and why (its validation errors, or the error).
//!
//! ```ignore
//! let done = Multi::new()
//!     .insert("user", User::changeset().cast(&params))
//!     .run("team", |done| async move {
//!         let user: &User = done.get("user").unwrap();
//!         Team::create(Team::changeset().set(|t| t.owner_id, user.id)).await?.into_step()
//!     })
//!     .enqueue("welcome", WelcomeEmail { email: email.clone() })
//!     .commit()
//!     .await;
//! match done {
//!     Ok(done) => { let user: &User = done.get("user").unwrap(); … }
//!     Err(MultiError { step, failure: Failure::Invalid { errors, .. }, .. }) => { … }
//!     Err(err) => return Err(err.into()),
//! }
//! ```

use std::any::Any;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use super::{Changeset, Save};
use crate::error::Error;
use crate::model::Model;

type StepFuture =
    Pin<Box<dyn Future<Output = std::result::Result<Arc<dyn Any + Send + Sync>, Failure>> + Send>>;
type Step = Box<dyn FnOnce(Done) -> StepFuture + Send>;

/// Steps to run in one transaction (see the module docs).
#[derive(Default)]
pub struct Multi {
    steps: Vec<(String, Step)>,
}

/// The results of the steps so far, by name.
#[derive(Clone, Default)]
pub struct Done {
    results: Vec<(String, Arc<dyn Any + Send + Sync>)>,
}

/// Lists the steps that ran (their results are any type).
impl fmt::Debug for Done {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Done")
            .field("steps", &self.steps())
            .finish()
    }
}

impl Done {
    /// A step's result, when it has that type: the record an `insert` or
    /// `update` saved, the value a `run` returned, a job's id.
    pub fn get<T: Any>(&self, step: &str) -> Option<&T> {
        self.results
            .iter()
            .find(|(name, _)| name == step)
            .and_then(|(_, value)| value.downcast_ref::<T>())
    }

    /// The names of the steps that ran, in order.
    pub fn steps(&self) -> Vec<&str> {
        self.results.iter().map(|(name, _)| name.as_str()).collect()
    }
}

/// Why a step failed.
#[derive(Debug)]
pub enum Failure {
    /// A changeset didn't validate: its errors as `errors_json` gives them,
    /// and as sentences.
    Invalid {
        errors: serde_json::Value,
        messages: Vec<String>,
    },
    Error(Error),
}

impl From<Error> for Failure {
    fn from(err: Error) -> Self {
        Failure::Error(err)
    }
}

/// A failed multi: the step that failed, why, and the steps that had run
/// (all rolled back).
#[derive(Debug)]
pub struct MultiError {
    pub step: String,
    pub failure: Failure,
    pub completed: Vec<String>,
}

impl fmt::Display for MultiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.failure {
            Failure::Invalid { messages, .. } => {
                write!(
                    f,
                    "step `{}` was invalid: {}",
                    self.step,
                    messages.join(", ")
                )
            }
            Failure::Error(err) => write!(f, "step `{}` failed: {}", self.step, err.message()),
        }
    }
}

/// So `multi.commit().await?` works in an action: an invalid step is a
/// 422 carrying its errors, anything else the step's own error.
impl From<MultiError> for Error {
    fn from(err: MultiError) -> Self {
        match err.failure {
            Failure::Invalid { ref messages, .. } => {
                Error::unprocessable(format!("{}: {}", err.step, messages.join(", ")))
            }
            Failure::Error(inner) => inner,
        }
    }
}

impl<M: Model> Save<M> {
    /// The saved record, or the changeset's errors as a step failure:
    /// for a `run` step that saves (`Post::create(…).await?.into_step()`).
    pub fn into_step(self) -> std::result::Result<M, Failure> {
        match self {
            Save::Saved(record) => Ok(record),
            Save::Invalid(changeset) => Err(invalid(&changeset)),
        }
    }
}

fn invalid<M: Model>(changeset: &Changeset<M>) -> Failure {
    Failure::Invalid {
        errors: changeset.errors_json(),
        messages: changeset.full_messages(),
    }
}

impl Multi {
    pub fn new() -> Self {
        Self::default()
    }

    /// Inserts a record from a changeset; its result is the saved record.
    #[must_use]
    pub fn insert<M>(self, name: &str, changeset: Changeset<M>) -> Self
    where
        M: Model + Send + Sync,
        Changeset<M>: Send,
    {
        self.step(name, move |_| async move {
            match changeset.insert().await? {
                Save::Saved(record) => Ok(record),
                Save::Invalid(changeset) => Err(invalid(&changeset)),
            }
        })
    }

    /// Updates a record from a changeset (`record.change()…`); its result
    /// is the saved record.
    #[must_use]
    pub fn update<M>(self, name: &str, changeset: Changeset<M>) -> Self
    where
        M: Model + Send + Sync,
        Changeset<M>: Send,
    {
        self.step(name, move |_| async move {
            match changeset.update().await? {
                Save::Saved(record) => Ok(record),
                Save::Invalid(changeset) => Err(invalid(&changeset)),
            }
        })
    }

    /// Queues a background job with the rest: it only runs if the multi
    /// commits. Its result is the job's id.
    #[must_use]
    pub fn enqueue<J: crate::jobs::Job>(self, name: &str, job: J) -> Self {
        self.step(name, move |_| async move { Ok(job.enqueue().await?) })
    }

    /// Runs any work, given the results so far; its result is what it
    /// returns. Return `Err(Failure::Invalid { … })` (or use
    /// `Save::into_step`) to fail with validation errors, or any `Error`
    /// with `?`.
    #[must_use]
    pub fn run<T, F, Fut>(self, name: &str, work: F) -> Self
    where
        T: Any + Send + Sync,
        F: FnOnce(Done) -> Fut + Send + 'static,
        Fut: Future<Output = std::result::Result<T, Failure>> + Send + 'static,
    {
        self.step(name, work)
    }

    fn step<T, F, Fut>(mut self, name: &str, work: F) -> Self
    where
        T: Any + Send + Sync,
        F: FnOnce(Done) -> Fut + Send + 'static,
        Fut: Future<Output = std::result::Result<T, Failure>> + Send + 'static,
    {
        assert!(
            !self.steps.iter().any(|(n, _)| n == name),
            "a Multi step is already named `{name}`"
        );
        let step: Step = Box::new(move |done| {
            Box::pin(async move {
                let value = work(done).await?;
                Ok(Arc::new(value) as Arc<dyn Any + Send + Sync>)
            })
        });
        self.steps.push((name.to_owned(), step));
        self
    }

    /// Runs the steps in order in one transaction (a savepoint, inside
    /// another transaction). All commit, or none do.
    // Unboxed so callers can match on `MultiError { step, failure, .. }`.
    #[allow(clippy::result_large_err)]
    pub async fn commit(self) -> std::result::Result<Done, MultiError> {
        // The failure, kept outside the transaction that rolls it back.
        let failed = std::sync::Mutex::new(None);
        let run = async {
            let mut done = Done::default();
            for (name, step) in self.steps {
                match step(done.clone()).await {
                    Ok(value) => done.results.push((name, value)),
                    Err(failure) => {
                        *failed.lock().unwrap_or_else(|e| e.into_inner()) = Some(MultiError {
                            completed: done.steps().into_iter().map(str::to_owned).collect(),
                            step: name,
                            failure,
                        });
                        return Err(Error::internal("multi step failed"));
                    }
                }
            }
            Ok(done)
        };
        match super::savepoint(run).await {
            Ok(done) => Ok(done),
            Err(err) => Err(failed
                .into_inner()
                .unwrap_or_else(|e| e.into_inner())
                .unwrap_or(MultiError {
                    step: "commit".to_owned(),
                    failure: Failure::Error(err),
                    completed: Vec::new(),
                })),
        }
    }
}