1use std::future::Future;
4use std::pin::Pin;
5use std::sync::OnceLock;
6use std::task::{Context, Poll};
7
8use tokio::sync::oneshot;
9
10use crate::Error;
11
12#[allow(
25 clippy::expect_used,
26 reason = "a process that cannot start its compute threads cannot do the work it was asked for"
27)]
28pub fn cpu_pool() -> &'static rayon::ThreadPool {
29 static POOL: OnceLock<rayon::ThreadPool> = OnceLock::new();
30 POOL.get_or_init(|| {
31 crate::panic_boundary::abort_outside_boundaries_in_release();
32 let builder = rayon::ThreadPoolBuilder::new();
33 #[cfg(target_family = "wasm")]
34 let builder = builder.num_threads(1).use_current_thread();
35 builder
36 .thread_name(|index| format!("tilo-cpu-{index}"))
37 .build()
38 .expect("start the CPU pool")
39 })
40}
41
42const LIBRARY_THREADS: usize = 16;
43
44pub fn bound_parallel_pool() {
52 static POOL: std::sync::Once = std::sync::Once::new();
53 POOL.call_once(|| {
54 let threads = std::thread::available_parallelism()
55 .map_or(1, std::num::NonZero::get)
56 .min(LIBRARY_THREADS);
57 let _ = rayon::ThreadPoolBuilder::new()
58 .num_threads(threads)
59 .thread_name(|index| format!("tilo-parallel-{index}"))
60 .build_global();
61 });
62}
63
64pub fn cpu<R, F>(work: F) -> CpuTask<R>
74where
75 F: FnOnce() -> R + Send + 'static,
76 R: Send + 'static,
77{
78 let (tx, rx) = oneshot::channel();
79 let job = move || {
80 if tx.is_closed() {
81 return;
82 }
83 let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(work));
84 let _ = tx.send(outcome.ok());
85 };
86 #[cfg(not(target_family = "wasm"))]
87 cpu_pool().spawn(job);
88 #[cfg(target_family = "wasm")]
89 crate::app::spawn_job(job);
90 CpuTask(rx)
91}
92
93#[derive(Debug)]
94pub struct CpuTask<R>(oneshot::Receiver<Option<R>>);
95
96impl<R> Future for CpuTask<R> {
97 type Output = Result<R, Error>;
98
99 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
100 Pin::new(&mut self.0)
101 .poll(cx)
102 .map(|received| received.ok().flatten().ok_or(Error::TaskFailed))
103 }
104}
105
106#[cfg(test)]
107mod tests {
108 use super::*;
109
110 #[test]
111 fn cpu_work_runs_on_the_pool_and_reports_panics() {
112 {
113 let (name, in_runtime) = crate::block_on(cpu(|| {
114 (
115 std::thread::current().name().map(str::to_owned),
116 crate::in_runtime(),
117 )
118 }))
119 .unwrap()
120 .unwrap();
121 assert!(name.unwrap().starts_with("tilo-cpu-"));
122 assert!(!in_runtime);
123 }
124 {
125 let result = crate::block_on(cpu(|| -> u8 { panic!("job failure") })).unwrap();
126 assert!(matches!(result, Err(Error::TaskFailed)));
127 }
128 }
129}