1use std::cell::RefCell;
15use std::collections::{BinaryHeap, VecDeque};
16use std::marker::PhantomData;
17use std::rc::Rc;
18use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError};
19
20use tilo_clock::time::{Duration, Instant};
21
22use crate::wake::WakeHandle;
23use tilo_lock::MutexRecover as _;
24
25pub type Job = Box<dyn FnOnce() + Send + 'static>;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
28#[error("background work is not available on this host")]
29pub struct Unsupported;
30
31pub trait Executor: Send + Sync + 'static {
32 fn spawn(&self, name: &'static str, job: Job) -> Result<(), Unsupported>;
41
42 fn wake_at(&self, deadline: Instant, wake: WakeHandle);
43
44 fn now(&self) -> Instant {
45 tilo_clock::now()
46 }
47
48 fn park(&self, deadline: Instant);
52}
53
54thread_local! {
55 static CURRENT: RefCell<Option<Background>> = const { RefCell::new(None) };
56}
57
58#[derive(Clone)]
59pub struct Background(Arc<dyn Executor>);
60
61impl std::fmt::Debug for Background {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 f.debug_struct("Background").finish_non_exhaustive()
64 }
65}
66
67impl Default for Background {
68 fn default() -> Self {
69 Self::current()
70 }
71}
72
73impl Background {
74 pub fn new(executor: impl Executor) -> Self {
75 Self(Arc::new(executor))
76 }
77
78 pub fn current() -> Self {
79 CURRENT
80 .with(|current| current.borrow().clone())
81 .unwrap_or_else(native_default)
82 }
83
84 #[must_use = "the executor stays current only while the guard lives"]
87 pub fn enter(&self) -> BackgroundGuard {
88 let previous = CURRENT.with(|current| current.replace(Some(self.clone())));
89 BackgroundGuard {
90 previous,
91 thread_affinity: PhantomData,
92 }
93 }
94
95 pub fn spawn(
96 &self,
97 name: &'static str,
98 job: impl FnOnce() + Send + 'static,
99 ) -> Result<(), Unsupported> {
100 self.0.spawn(name, Box::new(job))
101 }
102
103 pub fn wake_at(&self, deadline: Instant, wake: WakeHandle) {
104 self.0.wake_at(deadline, wake);
105 }
106
107 pub fn wake_after(&self, delay: Duration, wake: WakeHandle) {
108 let now = self.now();
109 self.0.wake_at(now.checked_add(delay).unwrap_or(now), wake);
110 }
111
112 pub fn now(&self) -> Instant {
113 self.0.now()
114 }
115
116 pub fn park(&self, deadline: Instant) {
117 self.0.park(deadline);
118 }
119}
120
121pub struct BackgroundGuard {
122 previous: Option<Background>,
123 thread_affinity: PhantomData<Rc<()>>,
124}
125
126impl Drop for BackgroundGuard {
127 fn drop(&mut self) {
128 let previous = self.previous.take();
129 CURRENT.with(|current| {
130 current.replace(previous);
131 });
132 }
133}
134
135fn native_default() -> Background {
136 static DEFAULT: OnceLock<Background> = OnceLock::new();
137 #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
138 let make = || Background::new(ThreadPool::new(ThreadPool::default_threads()));
139 #[cfg(all(target_family = "wasm", target_os = "unknown"))]
140 let make = || Background::new(PageExecutor);
141 DEFAULT.get_or_init(make).clone()
142}
143
144#[cfg(all(target_family = "wasm", target_os = "unknown"))]
150#[derive(Clone, Copy, Debug, Default)]
151pub struct PageExecutor;
152
153#[cfg(all(target_family = "wasm", target_os = "unknown"))]
154impl PageExecutor {
155 const MAX_TIMEOUT_MS: u128 = 0x7fff_ffff;
157
158 #[allow(
159 clippy::future_not_send,
160 reason = "awaits a JavaScript promise on the page's only thread"
161 )]
162 async fn sleep(delay: Duration) {
163 use wasm_bindgen::JsCast as _;
164 let millis = delay.as_millis().min(Self::MAX_TIMEOUT_MS);
165 #[allow(
166 clippy::cast_precision_loss,
167 reason = "bounded by MAX_TIMEOUT_MS, exact in an f64"
168 )]
169 let millis = wasm_bindgen::JsValue::from_f64(millis as f64);
170 let timer = js_sys::Promise::new(&mut |resolve, _reject| {
171 let global = js_sys::global();
172 let armed = js_sys::Reflect::get(&global, &"setTimeout".into())
173 .ok()
174 .and_then(|f| f.dyn_into::<js_sys::Function>().ok())
175 .is_some_and(|set_timeout| set_timeout.call2(&global, &resolve, &millis).is_ok());
176 if !armed {
177 let _ = resolve.call0(&wasm_bindgen::JsValue::NULL);
178 }
179 });
180 let _ = wasm_bindgen_futures::JsFuture::from(timer).await;
181 }
182}
183
184#[cfg(all(target_family = "wasm", target_os = "unknown"))]
185impl Executor for PageExecutor {
186 fn spawn(&self, name: &'static str, job: Job) -> Result<(), Unsupported> {
187 wasm_bindgen_futures::spawn_local(async move { run_job(name, job) });
188 Ok(())
189 }
190
191 fn wake_at(&self, deadline: Instant, wake: WakeHandle) {
192 wasm_bindgen_futures::spawn_local(async move {
193 loop {
194 let now = tilo_clock::now();
195 if deadline <= now {
196 break;
197 }
198 Self::sleep(deadline.saturating_duration_since(now)).await;
199 }
200 wake.wake();
201 });
202 }
203
204 fn park(&self, _deadline: Instant) {}
205}
206
207fn run_job(name: &'static str, job: Job) {
208 if std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)).is_err() {
209 tracing::warn!(job = name, "background job panicked");
210 }
211}
212
213struct Timer {
214 deadline: Instant,
215 sequence: u64,
216 wake: WakeHandle,
217}
218
219impl PartialEq for Timer {
220 fn eq(&self, other: &Self) -> bool {
221 self.deadline == other.deadline && self.sequence == other.sequence
222 }
223}
224impl Eq for Timer {}
225impl PartialOrd for Timer {
226 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
227 Some(self.cmp(other))
228 }
229}
230impl Ord for Timer {
231 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
232 (other.deadline, other.sequence).cmp(&(self.deadline, self.sequence))
233 }
234}
235
236#[derive(Default)]
237struct Timers {
238 heap: BinaryHeap<Timer>,
239 sequence: u64,
240}
241
242impl Timers {
243 fn push(&mut self, deadline: Instant, wake: WakeHandle) {
244 self.sequence = self.sequence.wrapping_add(1);
245 self.heap.push(Timer {
246 deadline,
247 sequence: self.sequence,
248 wake,
249 });
250 }
251
252 fn pop_due(&mut self, now: Instant) -> Option<WakeHandle> {
253 if self.heap.peek().is_some_and(|timer| timer.deadline <= now) {
254 self.heap.pop().map(|timer| timer.wake)
255 } else {
256 None
257 }
258 }
259
260 fn next_deadline(&self) -> Option<Instant> {
261 self.heap.peek().map(|timer| timer.deadline)
262 }
263}
264
265#[derive(Default)]
266struct PoolState {
267 queue: VecDeque<(&'static str, Job)>,
268 threads: usize,
269 idle: usize,
270 timers: Timers,
271 timer_thread: bool,
272 progress: u64,
273 parked: std::collections::HashMap<std::thread::ThreadId, u64>,
278}
279
280struct PoolShared {
281 state: Mutex<PoolState>,
282 work: Condvar,
283 timer: Condvar,
284 progress: Condvar,
285 max_threads: usize,
286}
287
288#[derive(Clone)]
289pub struct ThreadPool {
290 shared: Arc<PoolShared>,
291}
292
293impl ThreadPool {
294 pub fn new(max_threads: usize) -> Self {
295 Self {
296 shared: Arc::new(PoolShared {
297 state: Mutex::new(PoolState::default()),
298 work: Condvar::new(),
299 timer: Condvar::new(),
300 progress: Condvar::new(),
301 max_threads: max_threads.max(1),
302 }),
303 }
304 }
305
306 pub fn default_threads() -> usize {
309 std::thread::available_parallelism()
310 .map_or(4, std::num::NonZeroUsize::get)
311 .clamp(4, 16)
312 }
313
314 fn worker(shared: &PoolShared) {
315 let mut state = shared.state.lock_recover();
316 loop {
317 if let Some((name, job)) = state.queue.pop_front() {
318 drop(state);
319 run_job(name, job);
320 state = shared.state.lock_recover();
321 state.progress = state.progress.wrapping_add(1);
322 shared.progress.notify_all();
323 continue;
324 }
325 state.idle = state.idle.saturating_add(1);
326 state = shared
327 .work
328 .wait(state)
329 .unwrap_or_else(PoisonError::into_inner);
330 state.idle = state.idle.saturating_sub(1);
331 }
332 }
333
334 fn timer_loop(shared: &PoolShared) {
335 let mut state = shared.state.lock_recover();
336 loop {
337 let now = tilo_clock::now();
338 let mut fired = Vec::new();
339 while let Some(wake) = state.timers.pop_due(now) {
340 fired.push(wake);
341 }
342 if !fired.is_empty() {
343 state.progress = state.progress.wrapping_add(1);
344 shared.progress.notify_all();
345 drop(state);
346 for wake in fired {
348 wake.wake();
349 }
350 state = shared.state.lock_recover();
351 continue;
352 }
353 state = match state.timers.next_deadline() {
354 Some(deadline) => {
355 let timeout = deadline.saturating_duration_since(now);
356 shared
357 .timer
358 .wait_timeout(state, timeout)
359 .unwrap_or_else(PoisonError::into_inner)
360 .0
361 }
362 None => shared
363 .timer
364 .wait(state)
365 .unwrap_or_else(PoisonError::into_inner),
366 };
367 }
368 }
369}
370
371impl Executor for ThreadPool {
372 #[allow(
373 clippy::significant_drop_tightening,
374 reason = "the pool's lock stays held across the spawn so the thread count and queue agree"
375 )]
376 fn spawn(&self, name: &'static str, job: Job) -> Result<(), Unsupported> {
377 crate::panic_boundary::abort_outside_boundaries_in_release();
378 let mut state = self.shared.state.lock_recover();
379 state.queue.push_back((name, job));
380 if state.idle >= state.queue.len() || state.threads >= self.shared.max_threads {
381 self.shared.work.notify_one();
382 return Ok(());
383 }
384 let index = state.threads;
385 let shared = Arc::clone(&self.shared);
386 let spawned = std::thread::Builder::new()
387 .name(format!("ui-background-{index}"))
388 .spawn(move || Self::worker(&shared));
389 if spawned.is_ok() {
390 state.threads = state.threads.saturating_add(1);
391 return Ok(());
392 }
393 if state.threads > 0 {
394 self.shared.work.notify_one();
395 return Ok(());
396 }
397 state.queue.pop_back();
398 Err(Unsupported)
399 }
400
401 fn wake_at(&self, deadline: Instant, wake: WakeHandle) {
402 let mut state = self.shared.state.lock_recover();
403 state.timers.push(deadline, wake);
404 if !state.timer_thread {
405 let shared = Arc::clone(&self.shared);
406 let spawned = std::thread::Builder::new()
407 .name("ui-background-timer".into())
408 .spawn(move || Self::timer_loop(&shared));
409 match spawned {
410 Ok(_) => state.timer_thread = true,
411 Err(error) => {
412 tracing::warn!(%error, "background timer thread unavailable");
415 let due = state.timers.heap.drain().map(|timer| timer.wake);
416 let due: Vec<_> = due.collect();
417 drop(state);
418 for wake in due {
419 wake.wake();
420 }
421 return;
422 }
423 }
424 }
425 self.shared.timer.notify_one();
426 }
427
428 fn park(&self, deadline: Instant) {
429 let thread = std::thread::current().id();
430 let mut state = self.shared.state.lock_recover();
431 let seen = state.parked.get(&thread).copied().unwrap_or(0);
432 let timeout = deadline.saturating_duration_since(tilo_clock::now());
433 state = self
434 .shared
435 .progress
436 .wait_timeout_while(state, timeout, |state| state.progress == seen)
437 .unwrap_or_else(PoisonError::into_inner)
438 .0;
439 let now = state.progress;
440 state.parked.insert(thread, now);
441 }
442}
443
444#[derive(Default)]
445struct PumpedState {
446 queue: VecDeque<(&'static str, Job)>,
447 timers: Timers,
448 now: Option<Instant>,
449}
450
451#[derive(Clone, Default)]
458pub struct Pumped {
459 state: Arc<Mutex<PumpedState>>,
460}
461
462impl Pumped {
463 pub fn new() -> Self {
464 Self::starting_at(tilo_clock::now())
465 }
466
467 pub fn starting_at(now: Instant) -> Self {
468 Self {
469 state: Arc::new(Mutex::new(PumpedState {
470 now: Some(now),
471 ..PumpedState::default()
472 })),
473 }
474 }
475
476 pub fn background(&self) -> Background {
477 Background::new(self.clone())
478 }
479
480 pub fn run_pending(&self) -> usize {
483 let mut ran = 0_usize;
484 loop {
485 let next = self.state.lock_recover().queue.pop_front();
486 let Some((name, job)) = next else {
487 return ran;
488 };
489 run_job(name, job);
490 ran = ran.saturating_add(1);
491 }
492 }
493
494 pub fn advance(&self, by: Duration) {
495 let now = self
496 .state
497 .lock_recover()
498 .now
499 .unwrap_or_else(tilo_clock::now);
500 let target = now.checked_add(by).unwrap_or(now);
501 self.advance_to(target);
502 }
503
504 fn advance_to(&self, target: Instant) {
505 self.run_pending();
506 loop {
507 let wake = {
508 let mut state = self.state.lock_recover();
509 match state.timers.next_deadline() {
510 Some(deadline) if deadline <= target => {
511 if state.now.is_none_or(|now| now < deadline) {
512 state.now = Some(deadline);
513 }
514 state.timers.pop_due(deadline)
515 }
516 _ => None,
517 }
518 };
519 let Some(wake) = wake else { break };
520 wake.wake();
521 self.run_pending();
522 }
523 let mut state = self.state.lock_recover();
524 if state.now.is_none_or(|now| now < target) {
525 state.now = Some(target);
526 }
527 }
528
529 pub fn is_idle(&self) -> bool {
532 self.state.lock_recover().queue.is_empty()
533 }
534
535 pub fn next_deadline(&self) -> Option<Instant> {
536 self.state.lock_recover().timers.next_deadline()
537 }
538
539 pub fn now(&self) -> Instant {
540 let mut state = self.state.lock_recover();
541 *state.now.get_or_insert_with(tilo_clock::now)
542 }
543}
544
545impl Executor for Pumped {
546 fn spawn(&self, name: &'static str, job: Job) -> Result<(), Unsupported> {
547 self.state.lock_recover().queue.push_back((name, job));
548 Ok(())
549 }
550
551 fn wake_at(&self, deadline: Instant, wake: WakeHandle) {
552 self.state.lock_recover().timers.push(deadline, wake);
553 }
554
555 fn now(&self) -> Instant {
556 Self::now(self)
557 }
558
559 fn park(&self, deadline: Instant) {
560 if self.run_pending() > 0 {
561 return;
562 }
563 let target = self
564 .next_deadline()
565 .map_or(deadline, |next| next.min(deadline));
566 self.advance_to(target);
567 }
568}
569
570#[derive(Clone, Copy, Debug, Default)]
574pub struct NoBackground;
575
576impl Executor for NoBackground {
577 fn spawn(&self, _name: &'static str, _job: Job) -> Result<(), Unsupported> {
578 Err(Unsupported)
579 }
580
581 fn wake_at(&self, _deadline: Instant, wake: WakeHandle) {
582 wake.wake();
585 }
586
587 fn park(&self, _deadline: Instant) {}
588}
589
590#[cfg(test)]
591mod tests {
592 use super::*;
593 use crate::wake::WakeScope;
594
595 use std::sync::atomic::{AtomicUsize, Ordering};
596 use std::sync::mpsc;
597
598 fn counting_scope() -> (WakeScope, Arc<AtomicUsize>) {
599 let wakes = Arc::new(AtomicUsize::new(0));
600 let seen = Arc::clone(&wakes);
601 let mut scope = WakeScope::new();
602 scope
603 .bind(move |_| {
604 seen.fetch_add(1, Ordering::SeqCst);
605 })
606 .unwrap();
607 (scope, wakes)
608 }
609
610 #[test]
611 fn thread_pool_runs_named_jobs_survives_panics_and_wakes_timers_in_order() {
612 {
613 let pool = ThreadPool::new(2);
614 let (tx, rx) = mpsc::channel();
615 for _ in 0..4 {
616 let tx = tx.clone();
617 pool.spawn(
618 "test",
619 Box::new(move || {
620 let name = std::thread::current().name().map(str::to_owned);
621 tx.send(name).unwrap();
622 }),
623 )
624 .unwrap();
625 }
626 for _ in 0..4 {
627 let name = tilo_test_env::recv("a worker thread's name", &rx).unwrap();
628 assert!(name.starts_with("ui-background-"), "{name}");
629 }
630 assert!(pool.shared.state.lock_recover().threads <= 2);
631 }
632
633 {
634 let pool = ThreadPool::new(1);
635 pool.spawn("panics", Box::new(|| panic!("job failure")))
636 .unwrap();
637 let (tx, rx) = mpsc::channel();
638 pool.spawn("after", Box::new(move || tx.send(()).unwrap()))
639 .unwrap();
640 tilo_test_env::recv("the task spawned after", &rx);
641 }
642
643 {
644 let pool = ThreadPool::new(1);
645 let (tx, rx) = mpsc::channel();
646 let bound = |label: &'static str| {
647 let tx = tx.clone();
648 let mut scope = WakeScope::new();
649 scope
650 .bind(move |_| {
651 let _ = tx.send(label);
652 })
653 .unwrap();
654 scope
655 };
656 let late = bound("late");
657 let early = bound("early");
658 let start = tilo_clock::now();
659 pool.wake_at(start + Duration::from_millis(60), late.handle());
660 pool.wake_at(start + Duration::from_millis(10), early.handle());
661 assert_eq!(tilo_test_env::recv("the early wake", &rx), "early");
662 assert_eq!(tilo_test_env::recv("the late wake", &rx), "late");
663 }
664
665 {
666 let pool = ThreadPool::new(1);
667 let (release, check) = mpsc::channel::<()>();
668 pool.spawn("guarded", Box::new(move || check.recv().unwrap()))
669 .unwrap();
670 release.send(()).unwrap();
671 let deadline = tilo_clock::now() + tilo_test_env::hang_bound();
672 pool.park(deadline);
673 assert!(
674 tilo_clock::now() < deadline,
675 "park waited for its deadline, not the finished job"
676 );
677 }
678
679 {
680 let pool = ThreadPool::new(1);
681 let (done, finished) = mpsc::channel();
682 pool.spawn("quick", Box::new(move || done.send(()).unwrap()))
683 .unwrap();
684 tilo_test_env::recv("the quick job", &finished);
685 tilo_test_env::wait_until("the pool to count the quick job", || {
686 pool.shared.state.lock_recover().progress > 0
687 });
688 let deadline = tilo_clock::now() + tilo_test_env::hang_bound();
689 pool.park(deadline);
690 assert!(
691 tilo_clock::now() < deadline,
692 "park missed a job that finished before it was called"
693 );
694 }
695 }
696
697 #[test]
698 fn pumped_executor_runs_only_when_pumped_on_a_virtual_clock() {
699 {
700 let pumped = Pumped::new();
701 let ran = Arc::new(AtomicUsize::new(0));
702 let background = pumped.background();
703 let counter = Arc::clone(&ran);
704 let requeue = background.clone();
705 background
706 .spawn("outer", move || {
707 counter.fetch_add(1, Ordering::SeqCst);
708 let inner = Arc::clone(&counter);
709 requeue
710 .spawn("inner", move || {
711 inner.fetch_add(1, Ordering::SeqCst);
712 })
713 .unwrap();
714 })
715 .unwrap();
716 assert_eq!(ran.load(Ordering::SeqCst), 0);
717 assert!(!pumped.is_idle());
718 assert_eq!(
719 pumped.run_pending(),
720 2,
721 "work queued by a job runs in the same pump"
722 );
723 assert!(pumped.is_idle());
724 assert_eq!(ran.load(Ordering::SeqCst), 2);
725 }
726
727 {
728 let start = tilo_clock::now();
729 let pumped = Pumped::starting_at(start);
730 let (scope, wakes) = counting_scope();
731 pumped.wake_at(start + Duration::from_secs(2), scope.handle());
732 pumped.advance(Duration::from_millis(1999));
733 assert_eq!(wakes.load(Ordering::SeqCst), 0);
734 assert_eq!(pumped.next_deadline(), Some(start + Duration::from_secs(2)));
735 pumped.advance(Duration::from_millis(1));
736 assert_eq!(wakes.load(Ordering::SeqCst), 1);
737 assert_eq!(pumped.now(), start + Duration::from_secs(2));
738 assert_eq!(pumped.next_deadline(), None);
739 }
740
741 {
742 let start = tilo_clock::now();
743 let pumped = Pumped::starting_at(start);
744 let (scope, wakes) = counting_scope();
745 pumped.wake_at(start + Duration::from_secs(60), scope.handle());
746 pumped.park(start + Duration::from_secs(3600));
747 assert_eq!(wakes.load(Ordering::SeqCst), 1);
748 assert_eq!(pumped.now(), start + Duration::from_secs(60));
749 pumped.park(start + Duration::from_secs(120));
750 assert_eq!(pumped.now(), start + Duration::from_secs(120));
751 }
752
753 {
754 let pumped = Pumped::new();
755 {
756 let _guard = pumped.background().enter();
757 Background::current().spawn("scoped", || {}).unwrap();
758 {
759 let _inner = Background::new(NoBackground).enter();
760 assert_eq!(
761 Background::current().spawn("refused", || {}),
762 Err(Unsupported)
763 );
764 }
765 Background::current().spawn("scoped", || {}).unwrap();
766 }
767 assert_eq!(pumped.run_pending(), 2);
768 }
769 }
770}