Skip to main content

XetRuntime

Struct XetRuntime 

Source
pub struct XetRuntime { /* private fields */ }
Expand description

This module provides a simple wrapper around Tokio’s runtime to create a thread pool with some default settings. It is intended to be used as a singleton thread pool for the entire application.

The ThreadPool struct encapsulates a Tokio runtime and provides methods to run futures to completion, spawn new tasks, and get a handle to the runtime.

§Example

use xet_runtime::core::XetRuntime;

let pool = XetRuntime::new().expect("Error initializing runtime.");

let result = pool
    .bridge_sync(async {
        // Your async code here
        42
    })
    .expect("Task Error.");

assert_eq!(result, 42);

§Panics

The new_threadpool function will intentionally panic if the Tokio runtime cannot be created. This is because the application should not continue running without a functioning thread pool.

§Settings

The thread pool is configured with the following settings:

  • 4 worker threads
  • Thread names prefixed with “hf-xet-”
  • 8MB stack size per thread (default is 2MB)
  • Maximum of 100 blocking threads
  • All Tokio features enabled (IO, Timer, Signal, Reactor)

§Structs

  • ThreadPool: The main struct that encapsulates the Tokio runtime.

Implementations§

Source§

impl XetRuntime

Source

pub fn current() -> Arc<Self>

Return the current threadpool that the current worker thread uses. Will fail if
called from a thread that is not spawned from the current runtime.

Source

pub fn current_if_exists() -> Option<Arc<Self>>

Source

pub fn new() -> Result<Arc<Self>, RuntimeError>

Creates a new runtime with the default configuration.

Source

pub fn new_with_config(config: XetConfig) -> Result<Arc<Self>, RuntimeError>

Creates a new runtime with the given configuration.

Source

pub fn from_validated_external( rt_handle: TokioRuntimeHandle, config: XetConfig, ) -> Result<Arc<Self>, RuntimeError>

Wrap a caller-provided tokio handle after validating that it meets requirements.

§Errors

Not available on WASM targets.

Source

pub fn from_external_with_config( rt_handle: TokioRuntimeHandle, config: XetConfig, ) -> Result<Arc<Self>, RuntimeError>

Wrap an existing tokio TokioRuntimeHandle with a XetRuntime using the provided XetConfig. No new thread pool is created; spawn() calls will schedule work on the runtime that owns rt_handle.

The resulting XetRuntime is registered in EXTERNAL_RUNTIME_REGISTRY so that XetRuntime::current() called from tasks running on rt_handle’s threads will return this instance (with the correct config and shared XetCommon) rather than a default throwaway. The entry is removed when the last Arc<XetRuntime> is dropped.

§Errors
  • RuntimeError::ExternalAlreadyAttached — a live XetRuntime is already registered for rt_handle’s tokio runtime ID (i.e. the same handle was wrapped twice while the first is still alive). Drop the existing XetRuntime first, or use a different handle.
Source

pub fn from_external(rt_handle: TokioRuntimeHandle) -> Arc<Self>

Wrap an existing tokio TokioRuntimeHandle with a XetRuntime using a default XetConfig. Prefer from_external_with_config when you have a config available.

Unlike from_external_with_config, this function does not register the runtime in EXTERNAL_RUNTIME_REGISTRY and therefore performs no duplicate-handle check. It is intended for lightweight, short-lived wrapping where registry lookup via XetRuntime::current() is not required.

Source

pub fn handle(&self) -> TokioRuntimeHandle

Source

pub fn common(&self) -> &XetCommon

Returns a reference to the shared XetCommon state.

Source

pub fn get_or_create_reqwest_client<F>(tag: String, f: F) -> Result<Client>
where F: FnOnce() -> Result<Client, Error>,

Gets or creates a reqwest client, using a tag to identify the client type.

§Arguments
  • tag - A string identifier for the client (e.g., “tcp” for regular, socket path for UDS)
  • f - A function that creates the client if needed
§Returns

Returns a clone of the cached client if the tag matches and we’re in a runtime, or creates a new client otherwise. This allows creating high-level clients outside a runtime, like in tests.

Source

pub fn num_worker_threads(&self) -> usize

Source

pub fn external_executor_count(&self) -> usize

Gives the number of concurrent sync bridge callers (external_run_async_task and bridge_sync).

Source

pub fn perform_sigint_shutdown(&self)

Cancels and shuts down the runtime. All tasks currently running will be aborted.

A concurrent bridge_sync or in-flight bridge_async may still hold a cloned Arc to the tokio runtime until that call returns, so teardown of the reactor may complete only after those finish.

Source

pub fn discard_runtime(&self)

Discards the runtime without shutdown; to be used after fork-exec or spawn.

Source

pub fn in_sigint_shutdown(&self) -> bool

Returns true if we’re in the middle of a sigint shutdown, and false otherwise.

Source

pub fn external_run_async_task<F>( &self, future: F, ) -> Result<F::Output, RuntimeError>
where F: Future + Send + 'static, F::Output: Send + 'static,

This function should ONLY be used by threads outside of tokio; it should not be called from within a task running on the runtime worker pool. Doing so can lead to deadlocking.

Source

pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
where F: Future + Send + 'static, F::Output: Send + 'static,

Spawn an async task to run in the background on the current pool of worker threads.

Source

pub async fn bridge_async<T, F>( &self, task_name: &'static str, fut: F, ) -> Result<T, RuntimeError>
where F: Future<Output = T> + Send + 'static, T: Send + 'static,

Run a future on the appropriate runtime for this XetRuntime.

  • External mode: the future is awaited directly on the caller’s executor.
  • Owned mode: the future is spawned onto the owned thread pool and the result is delivered via a oneshot channel (compatible with any executor).

This is the primary async entry point. Session-level async methods should call self.runtime.bridge_async(...).

Source

pub fn bridge_sync<F>(&self, future: F) -> Result<F::Output, RuntimeError>
where F: Future + Send + 'static, F::Output: Send + 'static,

Run an async future synchronously, blocking the calling thread until completion.

Only supported on Owned runtimes. Returns RuntimeError::InvalidRuntime when called on an External-mode runtime.

The caller must not be on a tokio worker thread (calling from spawn_blocking threads, OS threads, or the main thread is fine).

This is the primary sync entry point. Session-level _blocking methods should simply call self.runtime.bridge_sync(...).

Source

pub fn spawn_blocking<F, R>(self: &Arc<Self>, f: F) -> JoinHandle<R>
where F: FnOnce() -> R + Send + 'static, R: Send + 'static,

Spawn a blocking task on the runtime’s blocking thread pool. The task runs with this runtime stored in thread-local storage so XetRuntime::current() works inside f.

The receiver must be an Arc<XetRuntime> so the runtime can be installed in the blocking thread (e.g. rt.spawn_blocking(|| { ... }) where rt: Arc<XetRuntime>).

Source

pub fn config(&self) -> &Arc<XetConfig>

Returns a reference to the primary configuration struct.

Source

pub fn mode(&self) -> RuntimeMode

Returns the runtime mode (Owned or External).

Source

pub fn handle_meets_requirements(handle: &TokioRuntimeHandle) -> bool

Not available on WASM targets (WASM always uses current_thread).

Trait Implementations§

Source§

impl Debug for XetRuntime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for XetRuntime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for XetRuntime

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> DropFlavorWrapper<T> for T

Source§

type Flavor = MayDrop

The DropFlavor that wraps T into Self
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T> ToStringFallible for T
where T: Display,

Source§

fn try_to_string(&self) -> Result<String, TryReserveError>

ToString::to_string, but without panic on OOM.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<E> ResultError for E
where E: Send + Debug + Sync,