servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Process-owned telemetry and executor lifetime share one explicit bootstrap.

use std::{
    future::Future,
    panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
    time::Duration,
};

use crate::{
    Error,
    telemetry::{self, TelemetryConfig},
};

/// Configure process telemetry before polling the entry point.
/// Use [`Self::host_telemetry`] when the host already owns a subscriber.
/// Embedded [`crate::App::start`] never installs a global subscriber.
pub struct Bootstrap {
    telemetry: Option<TelemetryConfig>,
}

impl Default for Bootstrap {
    fn default() -> Self {
        Self::new()
    }
}

impl Bootstrap {
    /// Own an INFO-level JSON subscriber and a new Tokio executor.
    pub fn new() -> Self {
        Self {
            telemetry: Some(TelemetryConfig::default()),
        }
    }

    /// Install these logging/tracing settings together before application startup.
    /// An existing process subscriber is an error; it is never replaced.
    pub fn telemetry(mut self, config: TelemetryConfig) -> Self {
        self.telemetry = Some(config);
        self
    }

    /// Leave subscriber ownership and flushing entirely to the host.
    pub fn host_telemetry(mut self) -> Self {
        self.telemetry = None;
        self
    }

    /// Run an entry point with process telemetry flushed before executor teardown.
    ///
    /// Explicitly configured traces use their declared flush allowance first.
    /// Logging then has 250 ms and executor teardown at most one second,
    /// all in addition to the application's shutdown budget. Unwinding uses the
    /// same teardown order. Started blocking work may outlive this call.
    /// Installation errors return before polling the entry point. Nesting inside
    /// an existing Tokio runtime is rejected before installing any telemetry.
    pub fn block_on<F, T, E>(self, future: F) -> std::result::Result<T, E>
    where
        F: Future<Output = std::result::Result<T, E>>,
        E: From<Error>,
    {
        if tokio::runtime::Handle::try_current().is_ok() {
            return Err(Error::Registration(
                "process bootstrap cannot nest inside a Tokio runtime".into(),
            )
            .into());
        }
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .map_err(|error| Error::Io("build executor", error))?;
        let result = catch_unwind(AssertUnwindSafe(|| {
            let _entered = runtime.enter();
            let _telemetry = self.telemetry.map(telemetry::install).transpose()?;
            runtime.block_on(future)
        }));
        runtime.shutdown_timeout(Duration::from_secs(1));
        match result {
            Ok(result) => result,
            Err(panic) => resume_unwind(panic),
        }
    }
}

#[cfg(test)]
#[path = "bootstrap_test.rs"]
mod bootstrap_test;