servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! Deferred typed state is erased to a ready router at the runtime boundary.

use super::App;
use crate::{Error, setup::SetupContext, task};
use axum::Router;
use std::future::Future;

impl<S: Clone + Send + Sync + 'static> App<S> {
    /// Initialize typed state inside the shared startup deadline.
    ///
    /// Runs once after configuration and listeners, before workers and admission.
    /// Cancellation or failure rolls back registered managed resources; cleanup
    /// errors and panics remain visible in the final lifecycle result. Synchronous
    /// blocking work cannot be preempted. Only awaited startup/termination proves
    /// cleanup completed; keep the executor alive after cancelling `start()`.
    ///
    /// ```no_run
    /// # async fn example() -> servlet::Result<()> {
    /// let running = servlet::App::new("deferred")
    ///     .get("/", |servlet::web::State(value): servlet::web::State<String>| async move { value })
    ///     .setup(|_ctx| async { Ok(String::from("ready")) })
    ///     .start().await?;
    /// running.handle().shutdown();
    /// running.wait().await
    /// # }
    /// ```
    pub fn setup<F, Fut>(mut self, factory: F) -> App<()>
    where
        F: FnOnce(SetupContext) -> Fut + Send + 'static,
        Fut: Future<Output = std::result::Result<S, task::BoxError>> + Send + 'static,
    {
        if self.registration.setup.is_some() {
            self.registration.startup_error = Some(Error::Registration(
                "setup can only be registered once".into(),
            ));
        } else {
            let router = self.router;
            self.registration.setup = Some(Box::new(move |context| {
                Box::pin(async move {
                    let state = factory(context).await?;
                    Ok(router.with_state(state))
                })
            }));
        }
        App {
            router: Router::new(),
            registration: self.registration,
        }
    }
}