laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
use crate::cache::CacheManagerInternals as _;
use std::fmt;
use std::sync::Weak;

use futures_util::FutureExt;
use futures_util::future::{BoxFuture, Shared};

use super::provider::Providers;
use crate::cache::CacheManager;
use crate::container::Container;
use crate::context::{self, Context, Internals};
use crate::error::{ErrorInternals as _, Result};
use crate::errors::panic;

pub type Booted = Box<dyn FnOnce(Container) -> BoxFuture<'static, Result<()>> + Send>;

pub struct Boot {
    /// The one boot, which every caller awaits. `Boot` keeps the future
    /// instead of the first caller owning it, so a caller that stops waiting,
    /// such as on a timeout, doesn't cancel the boot. The next caller resumes it.
    boot: Shared<BoxFuture<'static, Result<()>>>,
}

impl Boot {
    pub(crate) fn new(app: Weak<context::App>, providers: Providers, booted: Vec<Booted>) -> Self {
        let boot = panic::catch(boot(app, providers, booted).map(Ok))
            .map(|caught| caught.unwrap_or_else(|error| Err(error.for_boot("booting the application failed"))));

        Self {
            boot: boot.boxed().shared(),
        }
    }

    pub(crate) async fn run(&self) -> Result<()> {
        self.boot.clone().await
    }
}

async fn boot(app: Weak<context::App>, providers: Providers, booted: Vec<Booted>) -> Result<()> {
    let app = app
        .upgrade()
        .ok_or_else(|| crate::error::fail("the application was dropped before it booted"))?;
    let container = app.services.container();

    Context::new(app, None)
        .scope(async move {
            for provider in providers.iter() {
                run_hook(|| provider.provider.boot(&container))
                    .await
                    .map_err(|error| error.for_boot(format!("booting `{}` failed", provider.name)))?;
            }

            for booted in booted {
                run_hook(|| booted(container.clone()))
                    .await
                    .map_err(|error| error.for_boot("booting the application failed"))?;
            }

            container
                .resolve::<CacheManager>()
                .await
                .and_then(|cache| cache.check_default_store())
                .map_err(|error| error.for_boot("booting the application failed"))
        })
        .await
}

async fn run_hook<'a>(hook: impl FnOnce() -> BoxFuture<'a, Result<()>>) -> Result<()> {
    panic::catch(async move { hook().await }).await
}

impl fmt::Debug for Boot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Boot")
            .field("booted", &matches!(self.boot.peek(), Some(Ok(()))))
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use crate::Application;
    use crate::config::Env;

    #[tokio::test]
    async fn the_boot_lets_go_of_the_application_once_its_done() {
        let app = Application::configure().replace_env(Env::default()).create();
        app.boot().await.unwrap();
        let shared = Arc::downgrade(&app.shared);

        drop(app);

        assert!(shared.upgrade().is_none(), "the application is freed");
    }
}