xet_runtime/core/
context.rs1use std::sync::Arc;
2
3#[cfg(not(target_family = "wasm"))]
4use tokio::runtime::Handle as TokioRuntimeHandle;
5#[cfg(not(target_family = "wasm"))]
6use tracing::info;
7
8use super::XetCommon;
9use super::runtime::XetRuntime;
10use crate::config::XetConfig;
11use crate::error::RuntimeError;
12
13#[derive(Clone)]
19pub struct XetContext {
20 pub runtime: Arc<XetRuntime>,
21 pub config: Arc<XetConfig>,
22 pub common: Arc<XetCommon>,
23}
24
25impl XetContext {
26 pub fn new(mut config: XetConfig, runtime: Arc<XetRuntime>) -> Self {
35 config.reconstruction.normalize();
36 let config = Arc::new(config);
37 let common = Arc::new(XetCommon::new(&config));
38 Self {
39 runtime,
40 config,
41 common,
42 }
43 }
44
45 #[allow(clippy::should_implement_trait)]
51 pub fn default() -> Result<Self, RuntimeError> {
52 Self::with_config(XetConfig::new())
53 }
54
55 pub fn with_config(config: XetConfig) -> Result<Self, RuntimeError> {
60 #[cfg(not(target_family = "wasm"))]
61 let runtime = if let Some(runtime) = XetRuntime::current_if_exists() {
62 runtime
63 } else if let Ok(handle) = TokioRuntimeHandle::try_current()
64 && Self::handle_meets_requirements(&handle)
65 {
66 info!(
67 "Detected compatible existing Tokio runtime; using external handle instead of creating a new thread pool"
68 );
69 XetRuntime::from_external(handle)
70 } else {
71 XetRuntime::new(&config)?
72 };
73
74 #[cfg(target_family = "wasm")]
75 let runtime = XetRuntime::new(&config)?;
76
77 Ok(Self::new(config, runtime))
78 }
79
80 #[cfg(not(target_family = "wasm"))]
82 pub fn from_external(rt_handle: TokioRuntimeHandle, config: XetConfig) -> Self {
83 Self::new(config, XetRuntime::from_external(rt_handle))
84 }
85
86 #[cfg(not(target_family = "wasm"))]
88 pub fn handle_meets_requirements(handle: &TokioRuntimeHandle) -> bool {
89 XetRuntime::handle_meets_requirements(handle)
90 }
91
92 #[inline]
94 pub fn check_sigint_shutdown(&self) -> Result<(), RuntimeError> {
95 if self.runtime.in_sigint_shutdown() {
96 Err(RuntimeError::KeyboardInterrupt)
97 } else {
98 Ok(())
99 }
100 }
101}
102
103impl std::fmt::Debug for XetContext {
104 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105 f.debug_struct("XetContext")
106 .field("runtime", &self.runtime)
107 .field("config", &"...")
108 .field("common", &"...")
109 .finish()
110 }
111}