ulo 0.1.0-alpha.3

Fast and modular web framework for scalable applications
Documentation
use std::hash::Hash;
use std::sync::Mutex;

use crate::module::def::ModuleDef;
use crate::module::{Module, ModuleIdentity, ModuleSettings};

type Register = Box<dyn FnOnce(&mut ModuleDef<'_>) + Send>;

/// A module built at runtime by a function, for integration crates. Its identity is the owner
/// type plus the configuration value, so these are still distinct Rust-typed identities.
///
/// ```
/// # use ulo::{DynamicModule, ModuleDef};
/// # #[derive(Clone, PartialEq, Eq, Hash)]
/// # struct RedisConfig;
/// # struct RedisIntegration;
/// # struct RedisPool;
/// # impl RedisPool {
/// #     async fn connect(_: &RedisConfig) -> Self { RedisPool }
/// # }
/// pub fn redis_module(cfg: RedisConfig) -> DynamicModule {
///     DynamicModule::new::<RedisIntegration, _>(cfg.clone(), move |m| {
///         m.singleton(move || { let cfg = cfg.clone(); async move { RedisPool::connect(&cfg).await } });
///         m.export::<RedisPool>();
///     })
/// }
/// ```
///
/// The registration closure runs once: identities are deduplicated before `register` is called,
/// so a second import of an equal identity never reaches it.
pub struct DynamicModule {
    identity: ModuleIdentity,
    settings: ModuleSettings,
    register: Mutex<Option<Register>>,
}

impl DynamicModule {
    pub fn new<O: 'static, C: Eq + Hash + Clone + Send + Sync + 'static>(
        config: C,
        register: impl FnOnce(&mut ModuleDef<'_>) + Send + 'static,
    ) -> Self {
        DynamicModule {
            identity: ModuleIdentity::of_owner::<O, C>(&config),
            settings: ModuleSettings::new(),
            register: Mutex::new(Some(Box::new(register))),
        }
    }

    /// The name diagnostics print in place of the owner type's name.
    pub fn label(self, name: &'static str) -> Self {
        DynamicModule { identity: self.identity.label(name), ..self }
    }

    /// The settings the registration closure captures outside `config`, which a second import of
    /// an equal identity must repeat ([`Module::settings`]).
    pub fn with_settings(self, settings: ModuleSettings) -> Self {
        DynamicModule { settings, ..self }
    }
}

impl Module for DynamicModule {
    fn identity(&self) -> ModuleIdentity {
        self.identity.clone()
    }

    fn settings(&self) -> ModuleSettings {
        self.settings.clone()
    }

    fn register(&self, m: &mut ModuleDef<'_>) {
        // A poisoned slot still holds the closure, or `None` once taken; a panic elsewhere
        // under the lock does not change which.
        let register = match self.register.lock() {
            Ok(mut slot) => slot.take(),
            Err(poisoned) => poisoned.into_inner().take(),
        };
        if let Some(register) = register {
            register(m);
        }
    }
}