servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
use super::{App, Role};
use crate::{Error, Result};
use std::collections::BTreeMap;

type ComponentFactory = Box<dyn FnOnce(Role) -> App + Send>;

/// Named application factories for a binary that can run different components.
///
/// Select one component per process. Only the selected factory is called, so
/// components can build different routers, state, and workers. The selected role
/// controls application listeners and workers. The admin listener remains
/// independently configurable.
///
/// # Example
///
/// ```
/// use servlet::{App, Components, Role};
///
/// let app = Components::new()
///     .component("core", |_| App::new("chimlet").get("/", async || "core"))
///     .component("mcp", |_| App::new("chimlet").get("/", async || "mcp"))
///     .select("mcp", Role::Api)?;
/// # let _ = app;
/// # Ok::<(), servlet::Error>(())
/// ```
#[derive(Default)]
pub struct Components {
    factories: Vec<(String, ComponentFactory)>,
}

impl Components {
    /// Create an empty set of application factories.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a named factory. The selected factory receives the role before
    /// it assembles the application. Names must be nonblank and unique.
    pub fn component<F>(mut self, name: impl Into<String>, factory: F) -> Self
    where
        F: FnOnce(Role) -> App + Send + 'static,
    {
        self.factories.push((name.into(), Box::new(factory)));
        self
    }

    /// Validate the component names and build the selected application.
    ///
    /// An unknown component or invalid registration returns a registration
    /// error before invoking any factory.
    pub fn select(self, name: &str, role: Role) -> Result<App> {
        let mut factories = BTreeMap::new();
        for (component, factory) in self.factories {
            if component.trim().is_empty() || factories.insert(component, factory).is_some() {
                return Err(Error::Registration(
                    "component names must be nonblank and unique".into(),
                ));
            }
        }

        let (component, factory) = factories
            .remove_entry(name)
            .ok_or_else(|| Error::Registration(format!("unknown component: {name}")))?;
        let mut app = factory(role).with_role(role);
        app.registration.component_name = Some(component);
        Ok(app)
    }
}