servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Cancellation-safe ownership is established before startup begins.

use std::net::SocketAddr;

use axum::Router;
use tokio::sync::oneshot;

use crate::{Error, Result, app::Registration};

use super::{AppHandle, Running, Shared, driver::Driver};

pub(crate) fn launch(
    registration: Registration,
    router: Router,
) -> Result<(Running, oneshot::Receiver<Option<SocketAddr>>)> {
    let runtime = tokio::runtime::Handle::try_current().map_err(|_| Error::NoRuntime)?;
    let shared = Shared::with_metrics(registration.name.clone(), registration.metrics.clone());
    let (ready, receiver) = oneshot::channel();
    let driver = Driver::new(registration, router, shared.clone(), ready);
    let coordinator = runtime.spawn(driver.run());
    let running = Running {
        handle: AppHandle {
            shared,
            address: None,
        },
        coordinator: Some(coordinator),
    };
    Ok((running, receiver))
}

pub(crate) async fn start(registration: Registration, router: Router) -> Result<Running> {
    let (mut running, ready) = launch(registration, router)?;
    match ready.await {
        Ok(address) => {
            running.handle.address = address;
            Ok(running)
        }
        Err(_) => {
            running.wait().await?;
            Err(Error::Registration(
                "startup ended without readiness".into(),
            ))
        }
    }
}