servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! Route composition and application-owned worker/cleanup registrations.

use std::future::Future;

use axum::{Router, handler::Handler, routing};

use crate::{
    AppConfig,
    task::{self, Cleanup, Worker, WorkerContext},
};

type ConfigOverride = Box<dyn FnOnce(&mut AppConfig) + Send>;

pub(crate) struct Registration {
    pub name: String,
    pub metrics: crate::metrics::Registry,
    pub config: AppConfig,
    pub environment: bool,
    pub overrides: Vec<ConfigOverride>,
    pub workers: Vec<Worker>,
    pub cleanups: Vec<Cleanup>,
    pub checks: Vec<crate::health::Check>,
    pub http: bool,
    pub startup_error: Option<crate::Error>,
    pub setup: Option<crate::setup::Factory>,
}

/// Builds an application whose routes still need state `S`.
///
/// Only `App<()>` can start. Route collisions retain Axum's construction-time
/// panic behavior. Construction installs no signal handlers or global logging.
pub struct App<S = ()> {
    pub(crate) router: Router<S>,
    pub(crate) registration: Registration,
}

impl<S> App<S>
where
    S: Clone + Send + Sync + 'static,
{
    /// Begin assembling an application with a diagnostic name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            router: Router::new(),
            registration: Registration {
                name: name.into(),
                metrics: crate::metrics::Registry::owned(),
                config: AppConfig::default(),
                environment: true,
                overrides: Vec::new(),
                workers: Vec::new(),
                cleanups: Vec::new(),
                checks: Vec::new(),
                http: false,
                startup_error: None,
                setup: None,
            },
        }
    }

    /// Attach an application-owned registry for prebuilt state and setup instruments.
    ///
    /// Attaching the same registry (including a clone) to another builder fails
    /// startup. Attachment is permanent even if this builder is later dropped.
    /// Registration closes when setup ends; instrument handles remain usable.
    pub fn metrics(mut self, metrics: crate::metrics::Registry) -> Self {
        match metrics.attach() {
            Ok(()) => self.registration.metrics = metrics,
            Err(error) => {
                self.registration.startup_error =
                    Some(crate::Error::Registration(error.to_string()));
            }
        }
        self
    }

    /// Supply a complete explicit configuration, bypassing environment loading.
    pub fn config(mut self, config: AppConfig) -> Self {
        self.registration.config = config;
        self.registration.environment = false;
        self
    }

    /// Apply field overrides after environment loading, at startup.
    pub fn configure(
        mut self,
        override_config: impl FnOnce(&mut AppConfig) + Send + 'static,
    ) -> Self {
        self.registration.overrides.push(Box::new(override_config));
        self
    }

    /// Register a GET route using Axum's native handler types.
    pub fn get<H, T>(mut self, path: &str, handler: H) -> Self
    where
        H: Handler<T, S>,
        T: 'static,
    {
        self.router = self.router.route(path, routing::get(handler));
        self.registration.http = true;
        self
    }

    /// Register a POST route using Axum's native handler types.
    pub fn post<H, T>(mut self, path: &str, handler: H) -> Self
    where
        H: Handler<T, S>,
        T: 'static,
    {
        self.router = self.router.route(path, routing::post(handler));
        self.registration.http = true;
        self
    }

    /// Merge an ordinary Axum router with the same missing state.
    pub fn http(mut self, router: Router<S>) -> Self {
        self.router = self.router.merge(router);
        self.registration.http = true;
        self
    }

    /// Supply route state, producing an application that can start.
    pub fn state(self, state: S) -> App<()> {
        App {
            router: self.router.with_state(state),
            registration: self.registration,
        }
    }

    /// Register a required, long-running worker. Returning early is a failure.
    pub fn worker<F, Fut>(mut self, name: impl Into<String>, factory: F) -> Self
    where
        F: FnOnce(WorkerContext) -> Fut + Send + 'static,
        Fut: Future<Output = task::Result> + Send + 'static,
    {
        self.registration.workers.push(Worker {
            name: name.into(),
            factory: Box::new(move |context| Box::pin(factory(context))),
        });
        self
    }

    /// Register a cached dependency check. Startup waits for its first success.
    /// Readiness reflects its latest result, which can fail before startup ends.
    pub fn readiness<F, Fut>(
        mut self,
        name: impl Into<String>,
        policy: crate::health::CheckPolicy,
        check: F,
    ) -> Self
    where
        F: Fn() -> Fut + Send + 'static,
        Fut: Future<Output = task::Result> + Send + 'static,
    {
        self.registration
            .checks
            .push(crate::health::Check::new(name.into(), policy, check));
        self
    }

    /// Register cleanup, run in reverse order after drain and cancellation.
    pub fn cleanup<F, Fut>(mut self, name: impl Into<String>, factory: F) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = task::Result> + Send + 'static,
    {
        self.registration.cleanups.push(Cleanup {
            name: name.into(),
            factory: Box::new(move || Box::pin(factory())),
        });
        self
    }
}