tilo_rt/lib.rs
1//! The one async runtime model for Tilo processes.
2//!
3//! Tokio is the only async runtime in Tilo, and this crate decides how a process runs it,
4//! so no app, daemon or CLI builds runtimes of its own: [`app()`] for an app's one
5//! current-thread runtime, [`daemon()`] for a bounded multi-thread one, [`block_on`] for a
6//! synchronous entry point, [`cpu()`] and [`io`] for bulk work off the async workers,
7//! [`background`] for the host's executor and timers, [`spawn_thread`] for a thread of its
8//! own and [`sleep`] for a pause. Every thread this crate starts is named.
9//!
10//! In a browser no thread is started: [`app()`] tasks run on the page's microtask queue,
11//! and nothing may block. [`availability`] answers which [`Feature`]s the target has.
12
13#[cfg(not(target_family = "wasm"))]
14mod app;
15#[cfg(target_family = "wasm")]
16#[path = "app_web.rs"]
17mod app;
18pub mod background;
19mod caps;
20mod cpu;
21#[cfg(not(target_family = "wasm"))]
22mod daemon;
23pub mod io;
24pub mod panic_boundary;
25mod pool;
26pub mod stall;
27mod timer;
28pub use tilo_wake as wake;
29
30use std::cell::Cell;
31use std::future::Future;
32
33/// Run a future as a task on the page's own turn; a desktop starts a thread instead.
34#[cfg(target_family = "wasm")]
35pub use app::spawn_task;
36pub use app::{AppRuntime, app, try_app};
37pub use caps::{Availability, Feature, availability, available};
38pub use cpu::{CpuTask, bound_parallel_pool, cpu, cpu_pool};
39#[cfg(not(target_family = "wasm"))]
40pub use daemon::{Daemon, daemon};
41pub use timer::sleep;
42#[cfg(not(target_family = "wasm"))]
43pub use timer::timer_now;
44pub use tokio::runtime::{Handle, Runtime};
45pub use tokio::task::JoinHandle;
46
47/// `Send` where the platform has threads; nothing on the web.
48///
49/// Spawning hands a future, its answer and everything it holds to a task. Natively that task runs
50/// on another thread, so they must move there; a page has one thread, and the task a page runs is
51/// a turn of its own queue, holding the page's own values (a browser key, a page's storage). Code
52/// that spawns takes this bound and stays one path on both targets: it requires `Send` exactly
53/// where moving is real.
54#[cfg(not(target_family = "wasm"))]
55pub trait MaybeSend: Send {}
56#[cfg(not(target_family = "wasm"))]
57impl<T: Send + ?Sized> MaybeSend for T {}
58#[cfg(target_family = "wasm")]
59pub trait MaybeSend {}
60#[cfg(target_family = "wasm")]
61impl<T: ?Sized> MaybeSend for T {}
62
63/// Why a runtime operation was refused.
64#[derive(Debug, thiserror::Error)]
65pub enum Error {
66 #[error("could not start the async runtime: {0}")]
67 Start(#[from] std::io::Error),
68 /// A synchronous wait was requested from a thread that is already driving
69 /// async work: blocking there deadlocks or starves the runtime, and
70 /// handing the thread to a second runtime panics.
71 #[error("cannot block on a future from inside an async runtime; await it instead")]
72 InsideRuntime,
73 /// A synchronous wait was requested on the UI thread, where it freezes
74 /// every frame until the work finishes.
75 #[error(
76 "cannot block on a future on the UI thread; spawn it and deliver the result to the event loop"
77 )]
78 UiThread,
79 #[error("the task was cancelled or panicked")]
80 TaskFailed,
81}
82
83thread_local! {
84 static UI_THREAD: Cell<bool> = const { Cell::new(false) };
85 static DRIVING: Cell<bool> = const { Cell::new(false) };
86}
87
88/// Marks the calling thread as driving async tasks until dropped: a runtime
89/// worker, the app runtime thread, or a thread inside one of this crate's
90/// `block_on`s. Blocking there would stall every task queued behind it.
91pub(crate) struct Driving {
92 previous: bool,
93}
94
95impl Driving {
96 pub(crate) fn enter() -> Self {
97 Self {
98 previous: DRIVING.with(|driving| driving.replace(true)),
99 }
100 }
101}
102
103#[cfg(not(target_family = "wasm"))]
104pub(crate) fn mark_driving() {
105 DRIVING.with(|driving| driving.set(true));
106}
107
108impl Drop for Driving {
109 fn drop(&mut self) {
110 let previous = self.previous;
111 DRIVING.with(|driving| driving.set(previous));
112 }
113}
114
115pub fn mark_ui_thread() {
116 UI_THREAD.with(|ui| ui.set(true));
117}
118
119pub fn is_ui_thread() -> bool {
120 UI_THREAD.with(Cell::get)
121}
122
123/// Mark a call that waits — on the session, the device, a service — and so
124/// may take seconds. A debug build panics when it runs on a window's thread:
125/// the window would stop drawing and answering for as long as it waits, so
126/// a test or a development build that reaches it there fails instead.
127#[track_caller]
128pub fn off_ui_thread() {
129 debug_assert!(
130 !is_ui_thread(),
131 "a call that waits ran on a window's thread; run it off that thread and take its answer \
132 when it lands"
133 );
134}
135
136/// Whether the calling thread is inside a tokio runtime context: a runtime
137/// worker, the thread in a `block_on`, a blocking-pool thread, or a thread
138/// that entered a handle.
139pub fn in_runtime() -> bool {
140 Handle::try_current().is_ok()
141}
142
143/// Whether the calling thread drives async tasks of a runtime from this
144/// crate: a worker, the app runtime thread, or a thread inside one of its
145/// `block_on`s. Blocking-pool threads do not count; their thread exists to
146/// block, though they are inside a runtime all the same ([`in_runtime`]).
147pub fn in_async_context() -> bool {
148 DRIVING.with(Cell::get)
149}
150
151/// Refuse a wait on a thread that must not wait at all: the UI thread, which
152/// would freeze the frame, and a thread driving this crate's runtimes, which
153/// would stall the tasks queued behind it.
154///
155/// For callers that poll the future on their own thread instead of handing
156/// the thread to tokio, so that a thread inside another runtime's context —
157/// where tokio panics — still waits: [`AppRuntime::block_on`].
158pub(crate) fn check_not_a_driver() -> Result<(), Error> {
159 if is_ui_thread() {
160 return Err(Error::UiThread);
161 }
162 if in_async_context() {
163 return Err(Error::InsideRuntime);
164 }
165 Ok(())
166}
167
168/// Refuse a wait that hands the calling thread to a runtime: on a UI thread,
169/// on a thread driving this crate's runtimes, or in any runtime context at
170/// all — another crate's runtime, or a test's own — where tokio refuses to
171/// start or block a runtime and panics.
172fn check_may_block() -> Result<(), Error> {
173 check_not_a_driver()?;
174 if in_runtime() {
175 return Err(Error::InsideRuntime);
176 }
177 Ok(())
178}
179
180/// Run `future` to completion on the calling thread.
181///
182/// For synchronous entry points only: a CLI's `main`, a test, a dedicated
183/// worker thread that owns no runtime. The runtime lives for this call; a
184/// process that waits on async work repeatedly should keep a runtime (the
185/// [`app()`] runtime, or one built with [`daemon()`]) and use its handle.
186///
187/// A thread already inside a runtime context — a worker, a `block_on`, a
188/// blocking-pool thread, or code that entered a handle — is refused: it
189/// cannot hand this thread to a second runtime, and tokio panics when it
190/// tries. Await the future there instead, or [`AppRuntime::block_on`], which
191/// polls on the calling thread.
192///
193/// # Errors
194///
195/// [`Error::UiThread`] on a UI thread, [`Error::InsideRuntime`] inside any
196/// runtime context, [`Error::Start`] when the runtime cannot be built.
197pub fn block_on<F: Future>(future: F) -> Result<F::Output, Error> {
198 check_may_block()?;
199 panic_boundary::abort_outside_boundaries_in_release();
200 // A browser page's one thread is its UI thread, and it cannot park.
201 if cfg!(target_family = "wasm") {
202 return Err(Error::UiThread);
203 }
204 let runtime = tokio::runtime::Builder::new_current_thread()
205 .enable_all()
206 .thread_name("tilo-rt-block-on")
207 .max_blocking_threads(pool::BLOCK_ON_BLOCKING_THREADS)
208 .build()?;
209 let _driving = Driving::enter();
210 Ok(runtime.block_on(future))
211}
212
213/// Run `future` on `runtime` and wait for its output on the calling thread.
214///
215/// The one way synchronous code calls into a runtime it does not drive — a
216/// daemon's network, a service's host — from a thread of its own: the
217/// future runs as a task of `runtime`, and the caller waits on a plain
218/// channel, outside any runtime. Unlike `Runtime::block_on` on a shared
219/// handle, the caller's thread never enters `runtime`, so it may be any
220/// thread that owns no runtime. Async code awaits the future instead.
221///
222/// # Errors
223///
224/// [`Error::UiThread`] on a UI thread, [`Error::InsideRuntime`] in any
225/// runtime context (a worker of this crate's runtime or of another one,
226/// `runtime`'s own included, where waiting would stall the tasks queued
227/// behind the caller, or deadlock a runtime with one worker), and
228/// [`Error::TaskFailed`] when the task panicked or `runtime` shut down
229/// before it finished.
230pub fn wait_on<F>(runtime: &Handle, future: F) -> Result<F::Output, Error>
231where
232 F: Future + Send + 'static,
233 F::Output: Send + 'static,
234{
235 check_may_block()?;
236 if cfg!(target_family = "wasm") {
237 return Err(Error::UiThread);
238 }
239 let (answer, answered) = std::sync::mpsc::sync_channel(1);
240 runtime.spawn(async move {
241 let _ = answer.send(future.await);
242 });
243 answered.recv().map_err(|_| Error::TaskFailed)
244}
245
246/// Park the calling thread for `duration`: the sanctioned replacement for
247/// `std::thread::sleep`. Async code awaits [`sleep`] instead.
248///
249/// For desktop-only waits — a headless capture pumping a decoder, a device
250/// poller on its own thread. A browser page has one thread and cannot park;
251/// there this returns at once with an error, where `std::thread::sleep`
252/// panics.
253///
254/// # Errors
255///
256/// [`Error::UiThread`] on the web.
257pub fn sleep_thread(duration: std::time::Duration) -> Result<(), Error> {
258 if cfg!(target_family = "wasm") {
259 return Err(Error::UiThread);
260 }
261 std::thread::sleep(duration);
262 Ok(())
263}
264
265/// Start a named OS thread: the sanctioned replacement for
266/// `std::thread::spawn` and `std::thread::Builder::spawn`.
267///
268/// For work that owns its thread for a long time — an event loop, a device
269/// poller, a blocking protocol client. Short jobs belong on [`cpu()`], the
270/// [`io`] pool, [`background`], or a runtime's blocking pool instead.
271///
272/// Unlike `std::thread::spawn`, this never panics: where
273/// [`Feature::Threads`] is unsupported (a browser page) it returns an error,
274/// and the caller degrades — skips optional work, or runs a short step
275/// inline.
276///
277/// # Errors
278///
279/// Returns the OS error when the thread cannot be created, and
280/// [`std::io::ErrorKind::Unsupported`] on a target without threads.
281pub fn spawn_thread<T, F>(
282 name: impl Into<String>,
283 body: F,
284) -> std::io::Result<std::thread::JoinHandle<T>>
285where
286 F: FnOnce() -> T + Send + 'static,
287 T: Send + 'static,
288{
289 panic_boundary::abort_outside_boundaries_in_release();
290 std::thread::Builder::new().name(name.into()).spawn(body)
291}
292
293/// Run `body` on a worker thread where the target has them, and inline where
294/// it has none (a browser page). A caller that owns one long-lived loop for
295/// its own work keeps one shape on every target without selecting by target
296/// itself.
297///
298/// # Errors
299///
300/// As [`spawn_thread`]; the inline path has none.
301#[cfg(not(target_family = "wasm"))]
302pub fn spawn_worker<F>(name: impl Into<String>, body: F) -> std::io::Result<()>
303where
304 F: FnOnce() + Send + 'static,
305{
306 spawn_thread(name, body).map(|_| ())
307}
308
309/// Run `body` inline: this target has no threads.
310///
311/// # Errors
312///
313/// Never; the signature answers as the target that has threads does.
314#[cfg(target_family = "wasm")]
315#[allow(
316 clippy::unnecessary_wraps,
317 reason = "it answers as the target that has threads does, so a caller compiles once"
318)]
319pub fn spawn_worker<F>(_name: impl Into<String>, body: F) -> std::io::Result<()>
320where
321 F: FnOnce(),
322{
323 body();
324 Ok(())
325}
326
327/// How far below an ordinary thread [`spawn_background_thread`] runs, as a
328/// Linux nice value.
329pub const BACKGROUND_NICE: i32 = 10;
330
331/// [`spawn_thread`] for work a person does not wait on frame by frame —
332/// rasterising pages ahead of a scroll, decoding, indexing — that must never
333/// take a CPU from the thread drawing the window. On Linux the thread runs
334/// [`BACKGROUND_NICE`] steps below its spawner, so on a machine with one or
335/// two slow cores the UI thread is scheduled first and the work fills the
336/// time it leaves; elsewhere it is an ordinary thread.
337///
338/// # Errors
339///
340/// As [`spawn_thread`].
341pub fn spawn_background_thread<T, F>(
342 name: impl Into<String>,
343 body: F,
344) -> std::io::Result<std::thread::JoinHandle<T>>
345where
346 F: FnOnce() -> T + Send + 'static,
347 T: Send + 'static,
348{
349 spawn_thread(name, move || {
350 lower_current_thread_priority();
351 body()
352 })
353}
354
355/// Lower the calling thread (only it: Linux keeps a nice value per thread)
356/// to [`BACKGROUND_NICE`]. Failure leaves it as it was, which is only slower.
357pub fn lower_current_thread_priority() {
358 #[cfg(target_os = "linux")]
359 {
360 // SAFETY: `gettid` takes nothing and returns this thread's id.
361 let Ok(tid) = libc::id_t::try_from(unsafe { libc::gettid() }) else {
362 return;
363 };
364 // SAFETY: `getpriority`/`setpriority` take and return plain integers;
365 // PRIO_PROCESS with a thread id changes that thread alone on Linux.
366 unsafe {
367 let current = libc::getpriority(libc::PRIO_PROCESS, tid);
368 libc::setpriority(
369 libc::PRIO_PROCESS,
370 tid,
371 current.saturating_add(BACKGROUND_NICE).min(19),
372 );
373 }
374 }
375}
376
377#[must_use]
378pub fn thread_cpu_time() -> Option<std::time::Duration> {
379 // macOS has kept the clock since 10.12.
380 #[cfg(any(target_os = "linux", target_vendor = "apple"))]
381 {
382 let mut now = libc::timespec {
383 tv_sec: 0,
384 tv_nsec: 0,
385 };
386 // SAFETY: `now` is a valid, writable timespec for the call.
387 let status = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &raw mut now) };
388 if status != 0 {
389 return None;
390 }
391 Some(std::time::Duration::new(
392 u64::try_from(now.tv_sec).ok()?,
393 u32::try_from(now.tv_nsec).ok()?,
394 ))
395 }
396 #[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
397 {
398 None
399 }
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405
406 #[test]
407 fn a_background_thread_runs_below_its_spawner() {
408 #[cfg(target_os = "linux")]
409 {
410 // SAFETY: plain integer syscalls on this process's own threads.
411 let nice = || unsafe {
412 libc::getpriority(
413 libc::PRIO_PROCESS,
414 libc::id_t::try_from(libc::gettid()).unwrap(),
415 )
416 };
417 let spawner = nice();
418 let background = spawn_background_thread("nice-test", nice)
419 .unwrap()
420 .join()
421 .unwrap();
422 assert_eq!(background, (spawner + BACKGROUND_NICE).min(19));
423 }
424 }
425
426 #[test]
427 #[cfg(any(target_os = "linux", target_vendor = "apple"))]
428 fn a_threads_cpu_clock_counts_its_work_and_not_its_sleep() {
429 let start = thread_cpu_time().expect("the thread's CPU clock");
430 std::thread::sleep(std::time::Duration::from_millis(200));
431 let slept = thread_cpu_time().unwrap().saturating_sub(start);
432 assert!(slept < std::time::Duration::from_millis(100), "{slept:?}");
433 let busy = std::time::Instant::now();
434 let mut spin = 0_u64;
435 while busy.elapsed() < std::time::Duration::from_millis(50) {
436 spin = std::hint::black_box(spin.wrapping_add(1));
437 }
438 assert!(thread_cpu_time().unwrap() > start.saturating_add(slept));
439 }
440
441 tilo_test_env::scenario! {
442 fn synchronous_waits_run_the_future_and_refuse_runtime_and_ui_threads;
443
444 phase wait_on_runs_on_the_runtime_and_refuses_its_drivers;
445 {
446 let runtime = daemon("wait-on-test").workers(1).build().unwrap();
447 {
448 let value = wait_on(runtime.handle(), async {
449 tokio::time::sleep(std::time::Duration::from_millis(1)).await;
450 tokio::spawn(async { 3 }).await.unwrap()
451 })
452 .unwrap();
453 assert_eq!(value, 3);
454 }
455 {
456 let handle = runtime.handle().clone();
457 let nested = wait_on(
458 runtime.handle(),
459 async move { wait_on(&handle, async { 4 }) },
460 )
461 .unwrap();
462 assert!(matches!(nested, Err(Error::InsideRuntime)));
463 }
464 {
465 let other = daemon("wait-on-other").workers(1).build().unwrap();
466 let handle = runtime.handle().clone();
467 let nested =
468 wait_on(other.handle(), async move { wait_on(&handle, async { 5 }) }).unwrap();
469 assert!(matches!(nested, Err(Error::InsideRuntime)));
470 }
471 {
472 // A blocking-pool thread is a thread of its runtime, not a thread
473 // that owns none: it asks that runtime instead of building a
474 // second one, which tokio refuses and this guard names.
475 let handle = runtime.handle().clone();
476 let inner = wait_on(runtime.handle(), async move {
477 tokio::task::spawn_blocking(move || wait_on(&handle, async { 6 }))
478 .await
479 .unwrap()
480 })
481 .unwrap();
482 assert!(matches!(inner, Err(Error::InsideRuntime)));
483 }
484 {
485 let handle = runtime.handle().clone();
486 let result = spawn_thread("ui-wait-on-test", move || {
487 mark_ui_thread();
488 wait_on(&handle, async { 1 })
489 })
490 .unwrap()
491 .join()
492 .unwrap();
493 assert!(matches!(result, Err(Error::UiThread)));
494 }
495 {
496 let handle = runtime.handle().clone();
497 runtime.shutdown_background();
498 assert!(matches!(
499 wait_on(&handle, async { 2 }),
500 Err(Error::TaskFailed)
501 ));
502 }
503 }
504
505 phase block_on_drives_timers_but_refuses_runtime_and_ui_threads;
506 {
507 {
508 let value = block_on(async {
509 tokio::time::sleep(std::time::Duration::from_millis(1)).await;
510 7
511 })
512 .unwrap();
513 assert_eq!(value, 7);
514 }
515 {
516 let nested = block_on(async { block_on(async {}) }).unwrap();
517 assert!(matches!(nested, Err(Error::InsideRuntime)));
518 }
519 {
520 let foreign = tokio::runtime::Builder::new_current_thread()
521 .enable_all()
522 .build()
523 .unwrap();
524 let nested = foreign.block_on(async { block_on(async {}) });
525 assert!(matches!(nested, Err(Error::InsideRuntime)));
526 }
527 {
528 let inner = block_on(async {
529 tokio::task::spawn_blocking(|| app().block_on(async { 9 }))
530 .await
531 .unwrap()
532 })
533 .unwrap();
534 assert_eq!(inner.unwrap(), 9);
535 }
536 {
537 let result = spawn_thread("ui-test", || {
538 mark_ui_thread();
539 block_on(async { 1 })
540 })
541 .unwrap()
542 .join()
543 .unwrap();
544 assert!(matches!(result, Err(Error::UiThread)));
545 }
546 }
547 }
548}