use std::{
future::Future,
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
time::Duration,
};
use crate::{
Error,
telemetry::{self, TelemetryConfig},
};
pub struct Bootstrap {
telemetry: Option<TelemetryConfig>,
}
impl Default for Bootstrap {
fn default() -> Self {
Self::new()
}
}
impl Bootstrap {
pub fn new() -> Self {
Self {
telemetry: Some(TelemetryConfig::default()),
}
}
pub fn telemetry(mut self, config: TelemetryConfig) -> Self {
self.telemetry = Some(config);
self
}
pub fn host_telemetry(mut self) -> Self {
self.telemetry = None;
self
}
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;