1use tokio::runtime::{Builder, EnterGuard, Handle, Runtime};
2
3use crate::error::CoreError;
4
5pub struct AsyncRuntime {
10 inner: Runtime,
11}
12
13impl AsyncRuntime {
14 pub fn new() -> Result<Self, CoreError> {
17 let rt = Runtime::new().map_err(|e| CoreError::Runtime(e.to_string()))?;
18 Ok(Self { inner: rt })
19 }
20
21 pub fn multi_thread(num_workers: usize) -> Result<Self, CoreError> {
23 let rt = Builder::new_multi_thread()
24 .worker_threads(num_workers)
25 .enable_all()
26 .build()
27 .map_err(|e| CoreError::Runtime(e.to_string()))?;
28 Ok(Self { inner: rt })
29 }
30
31 pub fn current_thread() -> Result<Self, CoreError> {
33 let rt = Builder::new_current_thread()
34 .enable_all()
35 .build()
36 .map_err(|e| CoreError::Runtime(e.to_string()))?;
37 Ok(Self { inner: rt })
38 }
39
40 pub fn handle(&self) -> Handle {
42 self.inner.handle().clone()
43 }
44
45 pub fn block_on<F: std::future::Future>(&self, future: F) -> F::Output {
47 self.inner.block_on(future)
48 }
49
50 pub fn spawn<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
52 where
53 F: std::future::Future + Send + 'static,
54 F::Output: Send + 'static,
55 {
56 self.inner.spawn(future)
57 }
58
59 pub fn enter(&self) -> EnterGuard<'_> {
61 self.inner.enter()
62 }
63}