use std::future::Future;
use std::sync::Arc;
use std::sync::OnceLock;
use tokio::runtime::{Builder, Handle, RuntimeFlavor};
use tokio::task::JoinHandle;
static FALLBACK_HANDLE: OnceLock<Handle> = OnceLock::new();
use crate::error::{NodeError, Result};
pub const OWNED_WORKER_THREADS: usize = 2;
#[derive(Debug)]
pub struct OwnedRuntime(Option<tokio::runtime::Runtime>);
impl OwnedRuntime {
fn handle(&self) -> Option<&Handle> {
self.0.as_ref().map(tokio::runtime::Runtime::handle)
}
fn block_on<F: Future>(&self, future: F) -> Option<F::Output> {
self.0.as_ref().map(|runtime| runtime.block_on(future))
}
}
impl Drop for OwnedRuntime {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
}
}
}
#[derive(Debug, Clone)]
pub enum NodeRuntime {
Owned(Arc<OwnedRuntime>),
Borrowed(Handle),
}
impl NodeRuntime {
pub fn acquire() -> Result<Self> {
match Handle::try_current() {
Ok(handle) => Ok(Self::Borrowed(handle)),
Err(_) => Self::owned(),
}
}
pub fn owned() -> Result<Self> {
let runtime = Builder::new_multi_thread()
.worker_threads(OWNED_WORKER_THREADS)
.thread_name("astrs-node")
.enable_all()
.build()
.map_err(|error| NodeError::Runtime(error.to_string()))?;
Ok(Self::Owned(Arc::new(OwnedRuntime(Some(runtime)))))
}
#[must_use]
pub const fn is_owned(&self) -> bool {
matches!(self, Self::Owned(_))
}
#[must_use]
pub fn handle(&self) -> &Handle {
match self {
Self::Owned(runtime) => runtime.handle().unwrap_or_else(|| self.fallback_handle()),
Self::Borrowed(handle) => handle,
}
}
fn fallback_handle(&self) -> &Handle {
match self {
Self::Borrowed(handle) => handle,
Self::Owned(_) => FALLBACK_HANDLE.get_or_init(|| {
Builder::new_current_thread()
.build()
.map_or_else(|_| Handle::current(), |runtime| runtime.handle().clone())
}),
}
}
pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
self.handle().spawn(future)
}
#[must_use]
pub fn can_block(&self) -> bool {
match Handle::try_current() {
Ok(handle) => handle.runtime_flavor() != RuntimeFlavor::CurrentThread,
Err(_) => true,
}
}
pub fn block_on<F: Future>(
&self,
method: &'static str,
alternative: &'static str,
future: F,
) -> Result<F::Output> {
match Handle::try_current() {
Ok(handle) => match handle.runtime_flavor() {
RuntimeFlavor::CurrentThread => Err(NodeError::BlockingInAsync {
method,
alternative,
}),
_ => Ok(tokio::task::block_in_place(|| handle.block_on(future))),
},
Err(_) => match self {
Self::Owned(runtime) => runtime
.block_on(future)
.ok_or_else(|| NodeError::Runtime("the node runtime is gone".to_owned())),
Self::Borrowed(handle) => Ok(handle.block_on(future)),
},
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn outside_a_runtime_one_is_built_and_blocking_works() {
let runtime = NodeRuntime::acquire().unwrap();
assert!(runtime.is_owned());
assert!(runtime.can_block());
let value = runtime
.block_on("test", "test_async", async { 7_u32 })
.unwrap();
assert_eq!(value, 7);
}
#[test]
fn an_owned_runtime_drives_spawned_tasks_without_a_block_on() {
let runtime = NodeRuntime::owned().unwrap();
let (tx, rx) = std::sync::mpsc::channel();
let _task = runtime.spawn(async move {
let _ = tx.send(11_u32);
});
assert_eq!(
rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(),
11
);
}
#[tokio::test(flavor = "current_thread")]
async fn a_current_thread_runtime_refuses_to_be_blocked() {
let runtime = NodeRuntime::acquire().unwrap();
assert!(!runtime.is_owned());
assert!(!runtime.can_block());
let error = runtime
.block_on("EventStream::recv", "EventStream::recv_async", async {})
.unwrap_err();
assert!(matches!(
error,
NodeError::BlockingInAsync {
method: "EventStream::recv",
alternative: "EventStream::recv_async"
}
));
assert!(error.is_usage_error());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_multi_thread_runtime_is_borrowed_and_can_block() {
let runtime = NodeRuntime::acquire().unwrap();
assert!(!runtime.is_owned());
assert!(runtime.can_block());
let value = runtime
.block_on("test", "test_async", async { 3_u8 })
.unwrap();
assert_eq!(value, 3);
}
#[test]
fn an_owned_runtime_can_be_dropped_from_an_async_context() {
let runtime = NodeRuntime::owned().unwrap();
runtime.block_on("test", "test", async {}).unwrap();
let inner = NodeRuntime::owned().unwrap();
inner
.block_on("test", "test", async move {
drop(runtime);
})
.unwrap();
}
#[test]
fn the_worker_count_is_documented() {
assert_eq!(OWNED_WORKER_THREADS, 2);
}
}