vortex_io/
session.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Debug;
5
6use vortex_error::VortexExpect;
7use vortex_session::SessionExt;
8
9use crate::runtime::Handle;
10
11/// Session state for Vortex async runtimes.
12pub struct RuntimeSession {
13    handle: Option<Handle>,
14}
15
16impl Default for RuntimeSession {
17    fn default() -> Self {
18        Self {
19            handle: Handle::find(),
20        }
21    }
22}
23
24impl Debug for RuntimeSession {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        f.debug_struct("RuntimeSession").finish_non_exhaustive()
27    }
28}
29
30/// Extension trait for accessing runtime session data.
31pub trait RuntimeSessionExt: SessionExt {
32    /// Returns a handle for this session's runtime.
33    fn handle(&self) -> Handle {
34        self.get::<RuntimeSession>().handle
35                .as_ref()
36                .vortex_expect("Runtime handle not configured in Vortex session. Please setup a `CurrentThreadRuntime`, or configure the session for `with_tokio`.")
37                .clone()
38    }
39
40    /// Configure the runtime session to use the application's Tokio runtime.
41    ///
42    /// For example, if the application is launched using `#[tokio::main]`.
43    #[cfg(feature = "tokio")]
44    fn with_tokio(self) -> Self {
45        self.get_mut::<RuntimeSession>().handle =
46            Some(crate::runtime::tokio::TokioRuntime::current());
47        self
48    }
49
50    /// Configure the runtime session to use a specific Vortex runtime handle.
51    fn with_handle(self, handle: Handle) -> Self {
52        self.get_mut::<RuntimeSession>().handle = Some(handle);
53        self
54    }
55}
56impl<S: SessionExt> RuntimeSessionExt for S {}