git_xet_filter/runtime.rs
1//! Dedicated runtime for XET filter async operations
2//!
3//! Provides a safe way to run async operations from synchronous C callbacks
4
5use crate::error::{Result, XetError, XetErrorKind};
6use std::future::Future;
7use std::mem::ManuallyDrop;
8use std::time::Duration;
9use tokio::runtime::{Builder, Runtime};
10
11/// Dedicated runtime for XET filter operations
12///
13/// This runtime is created once per filter initialization and used
14/// for all async operations. It's single-threaded to avoid complexity
15/// and is separate from any user-created runtimes.
16pub struct XetRuntime {
17 // Use ManuallyDrop to control when the runtime is dropped
18 // This prevents tokio from panicking when dropped in async context
19 runtime: ManuallyDrop<Runtime>,
20 timeout: Duration,
21}
22
23impl XetRuntime {
24 /// Create a new dedicated runtime
25 ///
26 /// NOTE: This should NOT be called from within an existing Tokio runtime context.
27 /// Instead, use the handle-based approach or spawn_blocking.
28 pub fn new() -> Result<Self> {
29 // Check if we're already in a runtime context
30 if tokio::runtime::Handle::try_current().is_ok() {
31 return Err(XetError::new(
32 XetErrorKind::RuntimeError,
33 "Cannot create XetRuntime from within existing async context. \
34 XetRuntime creates its own runtime and cannot be nested."
35 .to_owned(),
36 ));
37 }
38
39 let runtime = Builder::new_current_thread()
40 .thread_name("xet-filter")
41 .enable_all()
42 .build()
43 .map_err(|e| {
44 XetError::new(
45 XetErrorKind::RuntimeError,
46 format!("Failed to create runtime: {e}"),
47 )
48 })?;
49
50 Ok(Self {
51 runtime: ManuallyDrop::new(runtime),
52 timeout: Duration::from_secs(300), // 5 minute timeout
53 })
54 }
55
56 /// Block on a future with timeout
57 ///
58 /// This is safe to call from C callbacks because we own the runtime
59 /// and don't rely on Handle::current()
60 pub fn block_on<F>(&self, future: F) -> Result<F::Output>
61 where
62 F: Future,
63 {
64 // Use our dedicated runtime, not current
65 self.runtime.block_on(async {
66 tokio::time::timeout(self.timeout, future)
67 .await
68 .map_err(|_| XetError::new(XetErrorKind::RuntimeError, "Operation timed out"))
69 })
70 }
71
72 /// Block on a future without timeout (use sparingly)
73 pub fn block_on_unchecked<F>(&self, future: F) -> F::Output
74 where
75 F: Future,
76 {
77 self.runtime.block_on(future)
78 }
79}
80
81impl Drop for XetRuntime {
82 fn drop(&mut self) {
83 // Shutdown the runtime in a blocking context to avoid panics
84 // SAFETY: We're in Drop, so this is the last use of the runtime
85 unsafe {
86 // If we're in an async context, spawn a thread to drop the runtime
87 // Otherwise, drop it directly
88 if tokio::runtime::Handle::try_current().is_ok() {
89 // We're in an async context - need to drop in a separate thread
90 let runtime = ManuallyDrop::take(&mut self.runtime);
91 std::thread::spawn(move || {
92 drop(runtime);
93 });
94 } else {
95 // Safe to drop directly
96 ManuallyDrop::drop(&mut self.runtime);
97 }
98 }
99 }
100}
101
102// Safety: Runtime is Send + Sync
103unsafe impl Send for XetRuntime {}
104unsafe impl Sync for XetRuntime {}