use std::{
fmt,
future::Future,
sync::{Arc, OnceLock},
};
use futures_util::{FutureExt as _, future::BoxFuture};
use crate::{Error, Result};
type Spawn = dyn Fn(BoxFuture<'static, ()>) + Send + Sync;
type Prepare = dyn Fn() -> Result<()> + Send + Sync;
#[derive(Clone)]
pub struct Executor {
spawn: Arc<Spawn>,
prepare: Arc<Prepare>,
}
impl Executor {
pub fn new<F>(spawn: F) -> Self
where
F: Fn(BoxFuture<'static, ()>) + Send + Sync + 'static,
{
Self {
spawn: Arc::new(spawn),
prepare: Arc::new(|| Ok(())),
}
}
pub(crate) fn prepare(&self) -> Result<()> {
(self.prepare)()
}
pub(crate) fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
(self.spawn)(future.boxed());
}
}
impl Default for Executor {
fn default() -> Self {
Self {
spawn: Arc::new(|future| {
if let Ok(executor) = shared() {
executor.spawn(future).detach();
}
}),
prepare: Arc::new(|| {
shared()
.map(|_| ())
.map_err(|()| Error::request("client connection executor could not start"))
}),
}
}
}
impl fmt::Debug for Executor {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_struct("Executor").finish_non_exhaustive()
}
}
impl<F> hyper::rt::Executor<F> for Executor
where
F: Future<Output = ()> + Send + 'static,
{
fn execute(&self, future: F) {
self.spawn(future);
}
}
fn shared() -> std::result::Result<&'static async_executor::Executor<'static>, ()> {
static SHARED: OnceLock<std::result::Result<&'static async_executor::Executor<'static>, ()>> =
OnceLock::new();
*SHARED.get_or_init(|| {
let executor: &'static async_executor::Executor<'static> =
Box::leak(Box::new(async_executor::Executor::new()));
let driver = executor;
std::thread::Builder::new()
.name("tez-runtime".to_owned())
.spawn(move || {
async_io::block_on(driver.run(futures_util::future::pending::<()>()));
})
.map(|_| executor)
.map_err(|_| ())
})
}
#[cfg(test)]
mod tests {
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use super::*;
#[test]
fn default_executor_drives_detached_connections() {
let completed = Arc::new(AtomicBool::new(false));
let task_completed = Arc::clone(&completed);
Executor::default().spawn(async move {
task_completed.store(true, Ordering::Release);
});
for _ in 0..100 {
if completed.load(Ordering::Acquire) {
return;
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
assert!(completed.load(Ordering::Acquire));
}
}