use std::sync::Arc;
#[cfg(not(target_family = "wasm"))]
use tokio::runtime::Handle as TokioRuntimeHandle;
#[cfg(not(target_family = "wasm"))]
use tracing::info;
use super::XetCommon;
use super::runtime::XetRuntime;
use crate::config::XetConfig;
use crate::error::RuntimeError;
#[derive(Clone)]
pub struct XetContext {
pub runtime: Arc<XetRuntime>,
pub config: Arc<XetConfig>,
pub common: Arc<XetCommon>,
}
impl XetContext {
pub fn new(config: XetConfig, runtime: Arc<XetRuntime>) -> Self {
let config = Arc::new(config);
let common = Arc::new(XetCommon::new(&config));
Self {
runtime,
config,
common,
}
}
#[allow(clippy::should_implement_trait)]
pub fn default() -> Result<Self, RuntimeError> {
Self::with_config(XetConfig::new())
}
pub fn with_config(config: XetConfig) -> Result<Self, RuntimeError> {
#[cfg(not(target_family = "wasm"))]
let runtime = if let Some(runtime) = XetRuntime::current_if_exists() {
runtime
} else if let Ok(handle) = TokioRuntimeHandle::try_current()
&& Self::handle_meets_requirements(&handle)
{
info!(
"Detected compatible existing Tokio runtime; using external handle instead of creating a new thread pool"
);
XetRuntime::from_external(handle)
} else {
XetRuntime::new(&config)?
};
#[cfg(target_family = "wasm")]
let runtime = XetRuntime::new(&config)?;
Ok(Self::new(config, runtime))
}
#[cfg(not(target_family = "wasm"))]
pub fn from_external(rt_handle: TokioRuntimeHandle, config: XetConfig) -> Self {
Self::new(config, XetRuntime::from_external(rt_handle))
}
#[cfg(not(target_family = "wasm"))]
pub fn handle_meets_requirements(handle: &TokioRuntimeHandle) -> bool {
XetRuntime::handle_meets_requirements(handle)
}
#[inline]
pub fn check_sigint_shutdown(&self) -> Result<(), RuntimeError> {
if self.runtime.in_sigint_shutdown() {
Err(RuntimeError::KeyboardInterrupt)
} else {
Ok(())
}
}
}
impl std::fmt::Debug for XetContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("XetContext")
.field("runtime", &self.runtime)
.field("config", &"...")
.field("common", &"...")
.finish()
}
}