servlet 1.2.0

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

use std::{
    future::Future,
    sync::{Arc, OnceLock},
};

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

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

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

pub(crate) struct Registration {
    pub name: String,
    pub role: Role,
    pub component_name: Option<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 http_wrapper: Option<crate::web::HttpWrapper>,
    pub streaming: Vec<crate::web::StreamingGroup>,
    pub startup_error: Option<crate::Error>,
    pub rejection_formatter: Option<crate::web::RejectionFormatter>,
    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,
    pub(super) task_state: Option<Arc<OnceLock<S>>>,
}

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(),
            task_state: None,
            registration: Registration {
                name: name.into(),
                role: Role::default(),
                component_name: None,
                metrics: crate::metrics::Registry::owned(),
                config: AppConfig::default(),
                environment: true,
                overrides: Vec::new(),
                workers: Vec::new(),
                cleanups: Vec::new(),
                checks: Vec::new(),
                http: false,
                http_wrapper: None,
                streaming: Vec::new(),
                startup_error: None,
                rejection_formatter: None,
                setup: None,
            },
        }
    }

    /// Select the application work to start. The default is [Role::All].
    ///
    /// Setup can read the role to initialize the resources this process needs.
    /// The configured admin listener is available in every role.
    pub fn with_role(mut self, role: Role) -> Self {
        self.registration.role = role;
        self
    }

    /// 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
    }

    /// Format Servlet's pre-handler HTTP rejections as application problem JSON.
    ///
    /// The callback receives safe rejection facts and returns an optional
    /// serialized problem body, up to 16 KiB. It must return promptly. Servlet
    /// owns the status, correlation header, transport, and metrics. Returning
    /// no body, exceeding the limit, or panicking uses the default problem.
    pub fn format_runtime_rejections(
        mut self,
        formatter: impl for<'a> Fn(crate::web::RuntimeRejection<'a>) -> Option<crate::web::Bytes>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.registration.rejection_formatter = Some(Arc::new(formatter));
        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
    }

    /// Wrap the complete application router after setup binds state.
    ///
    /// Use this for middleware that needs the final Axum response, including
    /// routing headers. The callback runs once, before workers start and the
    /// application listener admits requests. It must return promptly.
    /// Only the application listener uses this wrapper. Registering another
    /// wrapper replaces the previous one.
    pub fn wrap_http(
        mut self,
        wrap: impl FnOnce(Router) -> std::result::Result<Router, task::BoxError> + Send + 'static,
    ) -> Self {
        self.registration.http_wrapper = Some(Box::new(wrap));
        self
    }

    /// Mount a native Axum router at a dedicated streaming prefix.
    ///
    /// The prefix reserves the whole subtree, including unmatched requests.
    /// The router's paths are relative to the prefix, following Axum nesting.
    /// Register any middleware the streaming routes need on that router.
    /// Prefixes are disjoint, static, absolute paths such as `"/api/sync"`.
    ///
    /// This group's exchange slots are separate from ordinary request slots.
    /// All HTTP connections still share the application's connection ceiling.
    /// Leave headroom below that ceiling across the enabled streaming groups
    /// so active streams alone cannot occupy every connection.
    ///
    /// The group uses its policy from admission onward, including route
    /// handling and response transfer. The listener's header deadline and the
    /// application's request body limit still apply.
    ///
    /// ```
    /// use servlet::{App, web::{Router, StreamPolicy, routing::get}};
    /// use std::time::Duration;
    ///
    /// let app: App = App::new("events").streaming_routes(
    ///     "/events",
    ///     StreamPolicy {
    ///         max_in_flight: 32,
    ///         max_duration: Duration::from_secs(120),
    ///         idle_timeout: Duration::from_secs(15),
    ///     },
    ///     Router::new().route("/", get(|| async { "mounted at /events" })),
    /// );
    /// ```
    pub fn streaming_routes(
        mut self,
        prefix: &str,
        policy: crate::web::StreamPolicy,
        router: Router<S>,
    ) -> Self {
        let group = match crate::web::StreamingGroup::new(prefix, policy) {
            Ok(group) => group,
            Err(error) => {
                self.registration.startup_error.get_or_insert(error);
                return self;
            }
        };
        if self
            .registration
            .streaming
            .iter()
            .any(|other| group.overlaps(other))
        {
            self.registration.startup_error.get_or_insert_with(|| {
                crate::Error::Registration("streaming prefixes must not overlap".into())
            });
            return self;
        }
        self.router = self.router.nest(prefix, router);
        self.registration.streaming.push(group);
        self.registration.http = true;
        self
    }

    /// Supply state for routes and state-aware tasks so the application can start.
    pub fn state(self, state: S) -> App<()> {
        App {
            router: Self::router_with_state(self.router, self.task_state, state),
            registration: self.registration,
            task_state: None,
        }
    }

    pub(super) fn router_with_state(
        router: Router<S>,
        task_state: Option<Arc<OnceLock<S>>>,
        state: S,
    ) -> Router {
        if let Some(task_state) = task_state {
            task_state.get_or_init(|| state.clone());
        }
        router.with_state(state)
    }

    /// Register a required, long-running worker for [`Role::All`] and [`Role::Worker`].
    /// Returning early is a failure.
    pub fn worker<F, Fut>(self, name: impl Into<String>, factory: F) -> Self
    where
        F: FnOnce(WorkerContext) -> Fut + Send + 'static,
        Fut: Future<Output = task::Result> + Send + 'static,
    {
        self.register_task(name, factory, false)
    }

    /// Register a worker that receives a clone of the initialized state.
    ///
    /// Register before [`Self::setup`] or [`Self::state`] to receive typed state.
    /// The factory runs after successful setup in the same roles as [`Self::worker`].
    pub fn worker_with_state<F, Fut>(self, name: impl Into<String>, factory: F) -> Self
    where
        F: FnOnce(S, WorkerContext) -> Fut + Send + 'static,
        Fut: Future<Output = task::Result> + Send + 'static,
    {
        self.register_stateful_task(name, factory, false)
    }

    /// Register a required, long-running service that starts in every role.
    ///
    /// Services start after setup. They share task names, startup readiness,
    /// failure handling, and shutdown with [`Self::worker`]. Call
    /// [`WorkerContext::ready`] when a service is ready. Returning early is a
    /// failure.
    pub fn service<F, Fut>(self, name: impl Into<String>, factory: F) -> Self
    where
        F: FnOnce(WorkerContext) -> Fut + Send + 'static,
        Fut: Future<Output = task::Result> + Send + 'static,
    {
        self.register_task(name, factory, true)
    }

    /// Register a service that receives a clone of the initialized state.
    ///
    /// Register before [`Self::setup`] or [`Self::state`] to receive typed state.
    /// The factory runs after successful setup in every role, like [`Self::service`].
    pub fn service_with_state<F, Fut>(self, name: impl Into<String>, factory: F) -> Self
    where
        F: FnOnce(S, WorkerContext) -> Fut + Send + 'static,
        Fut: Future<Output = task::Result> + Send + 'static,
    {
        self.register_stateful_task(name, factory, true)
    }

    fn register_stateful_task<F, Fut>(
        mut self,
        name: impl Into<String>,
        factory: F,
        runs_in_api: bool,
    ) -> Self
    where
        F: FnOnce(S, WorkerContext) -> Fut + Send + 'static,
        Fut: Future<Output = task::Result> + Send + 'static,
    {
        let task_state = self
            .task_state
            .get_or_insert_with(|| Arc::new(OnceLock::new()))
            .clone();
        self.register_task(
            name,
            move |context| {
                let state = task_state
                    .get()
                    .expect("application state is initialized before tasks start")
                    .clone();
                factory(state, context)
            },
            runs_in_api,
        )
    }

    fn register_task<F, Fut>(
        mut self,
        name: impl Into<String>,
        factory: F,
        runs_in_api: bool,
    ) -> 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))),
            runs_in_api,
        });
        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
    }
}