servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! The only owner of listeners, workers, connections, and shutdown sequencing.

use std::{collections::BTreeSet, net::SocketAddr, sync::Arc};

use axum::Router;
use tokio::{
    sync::{mpsc, oneshot},
    time::Instant,
};

use super::{Shared, shared::CompletionGuard};
use crate::{
    AppConfig, Error, Failure, FailureKind, Result,
    app::Registration,
    task::{Supervisor, WorkerContext},
};

pub(super) struct Driver {
    pub registration: Registration,
    pub(super) router: Router,
    pub shared: Arc<Shared>,
    pub tasks: Supervisor,
    pub(super) resources: crate::setup::Resources,
    ready: Option<oneshot::Sender<Option<SocketAddr>>>,
    started_at: Instant,
}

impl Driver {
    pub(super) fn new(
        registration: Registration,
        router: Router,
        shared: Arc<Shared>,
        ready: oneshot::Sender<Option<SocketAddr>>,
    ) -> Self {
        Self {
            registration,
            router,
            shared,
            tasks: Supervisor::new(),
            resources: crate::setup::Resources::new(),
            ready: Some(ready),
            started_at: Instant::now(),
        }
    }

    pub(super) fn startup_deadline(&self) -> Instant {
        self.started_at + self.registration.config.startup_timeout
    }

    pub(super) async fn run(mut self) -> Result<()> {
        let _completion = CompletionGuard(self.shared.clone());
        let mut failures = Vec::new();
        match self.initialize().await {
            Ok(mut listener) => {
                if let Err(failure) = self.run_setup(&mut listener).await {
                    self.tasks.abort_all();
                    failures.extend(failure);
                } else if let Err(failure) = self.workers_ready(&mut listener).await {
                    failures.extend(failure);
                } else if self.shared.begin_running() {
                    let address = listener
                        .application
                        .as_ref()
                        .and_then(|listener| listener.local_addr().ok());
                    if let Some(ready) = self.ready.take() {
                        let _ = ready.send(address);
                    }
                    failures.extend(self.serve(listener).await);
                } else {
                    failures.push(Failure {
                        component: "startup".into(),
                        kind: FailureKind::StartupCancelled,
                    });
                }
            }
            Err(error) => failures.extend(error.into_failures("startup")),
        }
        self.shared.app_metrics.seal();
        // Keep the startup sender alive through rollback so start() awaits cleanup.
        self.finish(&mut failures).await;
        tracing::info!(application = %self.registration.name, failures = failures.len(), "application stopped");
        if failures.is_empty() {
            Ok(())
        } else {
            Err(Error::Lifecycle(failures))
        }
    }

    async fn initialize(&mut self) -> Result<super::listeners::Listeners> {
        if let Some(error) = self.registration.startup_error.take() {
            return Err(error);
        }
        if self.registration.environment {
            self.registration.config = AppConfig::load_environment()?;
        }
        for change in self.registration.overrides.drain(..) {
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                change(&mut self.registration.config)
            }))
            .map_err(|_| Error::Registration("configuration override panicked".into()))?;
        }
        let role = self.registration.role;
        self.registration.config.validate_for_role(role)?;
        if !role.includes_api() {
            self.registration.http = false;
            self.router = Router::new();
        }
        if !role.includes_workers() {
            self.registration
                .workers
                .retain(|worker| worker.runs_in_api);
        }
        crate::health::prepare(&mut self.registration, &self.shared)?;
        if self.registration.name.trim().is_empty() {
            return Err(Error::Registration(
                "application name must not be empty".into(),
            ));
        }
        for names in [
            self.registration
                .workers
                .iter()
                .map(|worker| worker.name.as_str())
                .collect::<Vec<_>>(),
            self.registration
                .cleanups
                .iter()
                .map(|cleanup| cleanup.name.as_str())
                .collect::<Vec<_>>(),
        ] {
            let mut unique = BTreeSet::new();
            for name in names {
                if name.trim().is_empty() || !unique.insert(name) {
                    return Err(Error::Registration(
                        "task and cleanup names must be nonempty and unique within their category"
                            .into(),
                    ));
                }
            }
        }
        self.bind_listeners().await
    }

    async fn workers_ready(
        &mut self,
        listeners: &mut super::listeners::Listeners,
    ) -> std::result::Result<(), Vec<Failure>> {
        self.shared.app_metrics.seal();
        self.registration
            .checks
            .extend(self.resources.take_checks());
        crate::health::prepare(&mut self.registration, &self.shared)
            .map_err(|error| error.into_failures("setup"))?;
        let mut pending: BTreeSet<String> = self
            .registration
            .workers
            .iter()
            .map(|worker| worker.name.clone())
            .collect();
        let (ready, mut receiver) = mpsc::channel(pending.len().max(1));
        for worker in self.registration.workers.drain(..) {
            tracing::info!(worker = %worker.name, "worker starting");
            let context = WorkerContext::new(
                worker.name.clone(),
                ready.clone(),
                self.shared.shutdown.clone(),
            );
            self.tasks
                .worker(worker.name, self.shared.clone(), async move {
                    (worker.factory)(context).await
                });
        }
        drop(ready);
        let deadline = self.startup_deadline();
        while !pending.is_empty() {
            tokio::select! {
                biased;
                failure = self.tasks.next(), if !self.tasks.is_empty() => {
                    if let Some(failure) = failure { return Err(vec![failure]); }
                }
                () = self.shared.shutdown.cancelled() => {
                    return Err(vec![Failure { component: "startup".into(), kind: FailureKind::StartupCancelled }]);
                }
                () = tokio::time::sleep_until(deadline) => {
                    return Err(pending.into_iter().map(|component| Failure { component, kind: FailureKind::StartupTimeout }).collect());
                }
                Some(name) = receiver.recv() => { pending.remove(&name); }
                accepted = super::listeners::accept(&mut listeners.admin) => {
                    if let Err(failure) = self.accept_admin(accepted, listeners) { return Err(vec![failure]); }
                }
            }
        }
        if Instant::now() >= deadline {
            return Err(vec![Failure {
                component: "startup".into(),
                kind: FailureKind::StartupTimeout,
            }]);
        }
        Ok(())
    }

    pub(super) fn shutdown_config(&self) -> AppConfig {
        // Invalid startup settings must still permit bounded rollback of registered cleanup.
        if self
            .registration
            .config
            .validate_for_role(self.registration.role)
            .is_ok()
        {
            self.registration.config.clone()
        } else {
            AppConfig::default()
        }
    }
}