use std::cell::RefCell;
use std::io;
use std::sync::Arc;
use crate::thread::ThreadBinding;
pub use tokio::runtime::Runtime;
type ThreadCallback = Arc<dyn Fn() + Send + Sync>;
thread_local! {
static BINDING: RefCell<Option<ThreadBinding>> = const { RefCell::new(None) };
}
pub struct Builder {
inner: tokio::runtime::Builder,
on_thread_start: Option<ThreadCallback>,
on_thread_stop: Option<ThreadCallback>,
}
impl Builder {
fn new(inner: tokio::runtime::Builder) -> Self {
Self {
inner,
on_thread_start: None,
on_thread_stop: None,
}
}
pub fn new_multi_thread() -> Self {
Self::new(tokio::runtime::Builder::new_multi_thread())
}
pub fn new_current_thread() -> Self {
Self::new(tokio::runtime::Builder::new_current_thread())
}
pub fn worker_threads(&mut self, threads: usize) -> &mut Self {
self.inner.worker_threads(threads);
self
}
pub fn max_blocking_threads(&mut self, limit: usize) -> &mut Self {
self.inner.max_blocking_threads(limit);
self
}
pub fn thread_name(&mut self, name: impl Into<String>) -> &mut Self {
self.inner.thread_name(name);
self
}
pub fn thread_stack_size(&mut self, bytes: usize) -> &mut Self {
self.inner.thread_stack_size(bytes);
self
}
pub fn enable_all(&mut self) -> &mut Self {
self.inner.enable_all();
self
}
pub fn on_thread_start<F>(&mut self, callback: F) -> &mut Self
where
F: Fn() + Send + Sync + 'static,
{
self.on_thread_start = Some(Arc::new(callback));
self
}
pub fn on_thread_stop<F>(&mut self, callback: F) -> &mut Self
where
F: Fn() + Send + Sync + 'static,
{
self.on_thread_stop = Some(Arc::new(callback));
self
}
pub fn build(&mut self) -> io::Result<Runtime> {
let started = self.on_thread_start.clone();
let stopping = self.on_thread_stop.clone();
self.inner.on_thread_start(move || {
BINDING.with(|binding| *binding.borrow_mut() = Some(ThreadBinding::bind()));
if let Some(callback) = started.as_ref() {
callback();
}
});
self.inner.on_thread_stop(move || {
if let Some(callback) = stopping.as_ref() {
callback();
}
BINDING.with(|binding| {
let released = binding.borrow_mut().take();
drop(released);
});
});
self.inner.build()
}
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use super::*;
#[test]
fn runs_tasks_when_the_host_hooks_are_absent() {
let runtime = Builder::new_multi_thread()
.worker_threads(2)
.thread_name("sdk-absent-hooks")
.build()
.unwrap();
assert_eq!(runtime.block_on(async { 6 * 7 }), 42);
drop(runtime);
}
#[test]
fn user_callbacks_still_run_without_a_host() {
let calls: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
let started = calls.clone();
let stopping = calls.clone();
let runtime = Builder::new_multi_thread()
.worker_threads(1)
.on_thread_start(move || started.lock().unwrap().push("start"))
.on_thread_stop(move || stopping.lock().unwrap().push("stop"))
.build()
.unwrap();
assert_eq!(runtime.block_on(async { 42 }), 42);
drop(runtime);
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let calls = calls.lock().unwrap();
let starts = calls.iter().filter(|&&c| c == "start").count();
let stops = calls.iter().filter(|&&c| c == "stop").count();
if starts > 0 && starts == stops {
break;
}
assert!(
Instant::now() < deadline,
"runtime threads never stopped: {calls:?}"
);
drop(calls);
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn current_thread_runtime_binds_its_blocking_threads() {
let calls: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
let started = calls.clone();
let stopping = calls.clone();
let runtime = Builder::new_current_thread()
.thread_name("sdk-current-thread")
.on_thread_start(move || started.lock().unwrap().push("start"))
.on_thread_stop(move || stopping.lock().unwrap().push("stop"))
.build()
.unwrap();
let value =
runtime.block_on(async { tokio::task::spawn_blocking(|| 21 * 2).await.unwrap() });
assert_eq!(value, 42);
drop(runtime);
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let calls = calls.lock().unwrap();
if calls.iter().filter(|&&c| c == "start").count() > 0
&& calls.iter().filter(|&&c| c == "stop").count() > 0
{
break;
}
assert!(
Instant::now() < deadline,
"blocking thread callbacks never fired: {calls:?}"
);
drop(calls);
std::thread::sleep(Duration::from_millis(20));
}
}
}