use std::future::Future;
use std::pin::Pin;
use std::sync::OnceLock;
use std::task::{Context, Poll};
use tokio::sync::oneshot;
use crate::Error;
#[allow(
clippy::expect_used,
reason = "a process that cannot start its compute threads cannot do the work it was asked for"
)]
pub fn cpu_pool() -> &'static rayon::ThreadPool {
static POOL: OnceLock<rayon::ThreadPool> = OnceLock::new();
POOL.get_or_init(|| {
crate::panic_boundary::abort_outside_boundaries_in_release();
let builder = rayon::ThreadPoolBuilder::new();
#[cfg(target_family = "wasm")]
let builder = builder.num_threads(1).use_current_thread();
builder
.thread_name(|index| format!("tilo-cpu-{index}"))
.build()
.expect("start the CPU pool")
})
}
const LIBRARY_THREADS: usize = 16;
pub fn bound_parallel_pool() {
static POOL: std::sync::Once = std::sync::Once::new();
POOL.call_once(|| {
let threads = std::thread::available_parallelism()
.map_or(1, std::num::NonZero::get)
.min(LIBRARY_THREADS);
let _ = rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.thread_name(|index| format!("tilo-parallel-{index}"))
.build_global();
});
}
pub fn cpu<R, F>(work: F) -> CpuTask<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let (tx, rx) = oneshot::channel();
let job = move || {
if tx.is_closed() {
return;
}
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work));
let _ = tx.send(outcome.ok());
};
#[cfg(not(target_family = "wasm"))]
cpu_pool().spawn(job);
#[cfg(target_family = "wasm")]
crate::app::spawn_job(job);
CpuTask(rx)
}
#[derive(Debug)]
pub struct CpuTask<R>(oneshot::Receiver<Option<R>>);
impl<R> Future for CpuTask<R> {
type Output = Result<R, Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.0)
.poll(cx)
.map(|received| received.ok().flatten().ok_or(Error::TaskFailed))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cpu_work_runs_on_the_pool_and_reports_panics() {
{
let (name, in_runtime) = crate::block_on(cpu(|| {
(
std::thread::current().name().map(str::to_owned),
crate::in_runtime(),
)
}))
.unwrap()
.unwrap();
assert!(name.unwrap().starts_with("tilo-cpu-"));
assert!(!in_runtime);
}
{
let result = crate::block_on(cpu(|| -> u8 { panic!("job failure") })).unwrap();
assert!(matches!(result, Err(Error::TaskFailed)));
}
}
}