tilo-rt 0.5.0

The one async runtime model for Tilo processes: an app runtime off the UI thread, bounded daemon runtimes, a CPU pool, a file-I/O pool, named threads, and the host background executors and wake routing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
//! The one async runtime model for Tilo processes.
//!
//! Tokio is the only async runtime in Tilo, and this crate decides how a process runs it,
//! so no app, daemon or CLI builds runtimes of its own: [`app()`] for an app's one
//! current-thread runtime, [`daemon()`] for a bounded multi-thread one, [`block_on`] for a
//! synchronous entry point, [`cpu()`] and [`io`] for bulk work off the async workers,
//! [`background`] for the host's executor and timers, [`spawn_thread`] for a thread of its
//! own and [`sleep`] for a pause. Every thread this crate starts is named.
//!
//! In a browser no thread is started: [`app()`] tasks run on the page's microtask queue,
//! and nothing may block. [`availability`] answers which [`Feature`]s the target has.

#[cfg(not(target_family = "wasm"))]
mod app;
#[cfg(target_family = "wasm")]
#[path = "app_web.rs"]
mod app;
pub mod background;
mod caps;
mod cpu;
#[cfg(not(target_family = "wasm"))]
mod daemon;
pub mod io;
pub mod panic_boundary;
mod pool;
pub mod stall;
mod timer;
pub use tilo_wake as wake;

use std::cell::Cell;
use std::future::Future;

/// Run a future as a task on the page's own turn; a desktop starts a thread instead.
#[cfg(target_family = "wasm")]
pub use app::spawn_task;
pub use app::{AppRuntime, app, try_app};
pub use caps::{Availability, Feature, availability, available};
pub use cpu::{CpuTask, bound_parallel_pool, cpu, cpu_pool};
#[cfg(not(target_family = "wasm"))]
pub use daemon::{Daemon, daemon};
pub use timer::sleep;
#[cfg(not(target_family = "wasm"))]
pub use timer::timer_now;
pub use tokio::runtime::{Handle, Runtime};
pub use tokio::task::JoinHandle;

/// `Send` where the platform has threads; nothing on the web.
///
/// Spawning hands a future, its answer and everything it holds to a task. Natively that task runs
/// on another thread, so they must move there; a page has one thread, and the task a page runs is
/// a turn of its own queue, holding the page's own values (a browser key, a page's storage). Code
/// that spawns takes this bound and stays one path on both targets: it requires `Send` exactly
/// where moving is real.
#[cfg(not(target_family = "wasm"))]
pub trait MaybeSend: Send {}
#[cfg(not(target_family = "wasm"))]
impl<T: Send + ?Sized> MaybeSend for T {}
#[cfg(target_family = "wasm")]
pub trait MaybeSend {}
#[cfg(target_family = "wasm")]
impl<T: ?Sized> MaybeSend for T {}

/// Why a runtime operation was refused.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("could not start the async runtime: {0}")]
    Start(#[from] std::io::Error),
    /// A synchronous wait was requested from a thread that is already driving
    /// async work: blocking there deadlocks or starves the runtime, and
    /// handing the thread to a second runtime panics.
    #[error("cannot block on a future from inside an async runtime; await it instead")]
    InsideRuntime,
    /// A synchronous wait was requested on the UI thread, where it freezes
    /// every frame until the work finishes.
    #[error(
        "cannot block on a future on the UI thread; spawn it and deliver the result to the event loop"
    )]
    UiThread,
    #[error("the task was cancelled or panicked")]
    TaskFailed,
}

thread_local! {
    static UI_THREAD: Cell<bool> = const { Cell::new(false) };
    static DRIVING: Cell<bool> = const { Cell::new(false) };
}

/// Marks the calling thread as driving async tasks until dropped: a runtime
/// worker, the app runtime thread, or a thread inside one of this crate's
/// `block_on`s. Blocking there would stall every task queued behind it.
pub(crate) struct Driving {
    previous: bool,
}

impl Driving {
    pub(crate) fn enter() -> Self {
        Self {
            previous: DRIVING.with(|driving| driving.replace(true)),
        }
    }
}

#[cfg(not(target_family = "wasm"))]
pub(crate) fn mark_driving() {
    DRIVING.with(|driving| driving.set(true));
}

impl Drop for Driving {
    fn drop(&mut self) {
        let previous = self.previous;
        DRIVING.with(|driving| driving.set(previous));
    }
}

pub fn mark_ui_thread() {
    UI_THREAD.with(|ui| ui.set(true));
}

pub fn is_ui_thread() -> bool {
    UI_THREAD.with(Cell::get)
}

/// Mark a call that waits — on the session, the device, a service — and so
/// may take seconds. A debug build panics when it runs on a window's thread:
/// the window would stop drawing and answering for as long as it waits, so
/// a test or a development build that reaches it there fails instead.
#[track_caller]
pub fn off_ui_thread() {
    debug_assert!(
        !is_ui_thread(),
        "a call that waits ran on a window's thread; run it off that thread and take its answer \
         when it lands"
    );
}

/// Whether the calling thread is inside a tokio runtime context: a runtime
/// worker, the thread in a `block_on`, a blocking-pool thread, or a thread
/// that entered a handle.
pub fn in_runtime() -> bool {
    Handle::try_current().is_ok()
}

/// Whether the calling thread drives async tasks of a runtime from this
/// crate: a worker, the app runtime thread, or a thread inside one of its
/// `block_on`s. Blocking-pool threads do not count; their thread exists to
/// block, though they are inside a runtime all the same ([`in_runtime`]).
pub fn in_async_context() -> bool {
    DRIVING.with(Cell::get)
}

/// Refuse a wait on a thread that must not wait at all: the UI thread, which
/// would freeze the frame, and a thread driving this crate's runtimes, which
/// would stall the tasks queued behind it.
///
/// For callers that poll the future on their own thread instead of handing
/// the thread to tokio, so that a thread inside another runtime's context —
/// where tokio panics — still waits: [`AppRuntime::block_on`].
pub(crate) fn check_not_a_driver() -> Result<(), Error> {
    if is_ui_thread() {
        return Err(Error::UiThread);
    }
    if in_async_context() {
        return Err(Error::InsideRuntime);
    }
    Ok(())
}

/// Refuse a wait that hands the calling thread to a runtime: on a UI thread,
/// on a thread driving this crate's runtimes, or in any runtime context at
/// all — another crate's runtime, or a test's own — where tokio refuses to
/// start or block a runtime and panics.
fn check_may_block() -> Result<(), Error> {
    check_not_a_driver()?;
    if in_runtime() {
        return Err(Error::InsideRuntime);
    }
    Ok(())
}

/// Run `future` to completion on the calling thread.
///
/// For synchronous entry points only: a CLI's `main`, a test, a dedicated
/// worker thread that owns no runtime. The runtime lives for this call; a
/// process that waits on async work repeatedly should keep a runtime (the
/// [`app()`] runtime, or one built with [`daemon()`]) and use its handle.
///
/// A thread already inside a runtime context — a worker, a `block_on`, a
/// blocking-pool thread, or code that entered a handle — is refused: it
/// cannot hand this thread to a second runtime, and tokio panics when it
/// tries. Await the future there instead, or [`AppRuntime::block_on`], which
/// polls on the calling thread.
///
/// # Errors
///
/// [`Error::UiThread`] on a UI thread, [`Error::InsideRuntime`] inside any
/// runtime context, [`Error::Start`] when the runtime cannot be built.
pub fn block_on<F: Future>(future: F) -> Result<F::Output, Error> {
    check_may_block()?;
    panic_boundary::abort_outside_boundaries_in_release();
    // A browser page's one thread is its UI thread, and it cannot park.
    if cfg!(target_family = "wasm") {
        return Err(Error::UiThread);
    }
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .thread_name("tilo-rt-block-on")
        .max_blocking_threads(pool::BLOCK_ON_BLOCKING_THREADS)
        .build()?;
    let _driving = Driving::enter();
    Ok(runtime.block_on(future))
}

/// Run `future` on `runtime` and wait for its output on the calling thread.
///
/// The one way synchronous code calls into a runtime it does not drive — a
/// daemon's network, a service's host — from a thread of its own: the
/// future runs as a task of `runtime`, and the caller waits on a plain
/// channel, outside any runtime. Unlike `Runtime::block_on` on a shared
/// handle, the caller's thread never enters `runtime`, so it may be any
/// thread that owns no runtime. Async code awaits the future instead.
///
/// # Errors
///
/// [`Error::UiThread`] on a UI thread, [`Error::InsideRuntime`] in any
/// runtime context (a worker of this crate's runtime or of another one,
/// `runtime`'s own included, where waiting would stall the tasks queued
/// behind the caller, or deadlock a runtime with one worker), and
/// [`Error::TaskFailed`] when the task panicked or `runtime` shut down
/// before it finished.
pub fn wait_on<F>(runtime: &Handle, future: F) -> Result<F::Output, Error>
where
    F: Future + Send + 'static,
    F::Output: Send + 'static,
{
    check_may_block()?;
    if cfg!(target_family = "wasm") {
        return Err(Error::UiThread);
    }
    let (answer, answered) = std::sync::mpsc::sync_channel(1);
    runtime.spawn(async move {
        let _ = answer.send(future.await);
    });
    answered.recv().map_err(|_| Error::TaskFailed)
}

/// Park the calling thread for `duration`: the sanctioned replacement for
/// `std::thread::sleep`. Async code awaits [`sleep`] instead.
///
/// For desktop-only waits — a headless capture pumping a decoder, a device
/// poller on its own thread. A browser page has one thread and cannot park;
/// there this returns at once with an error, where `std::thread::sleep`
/// panics.
///
/// # Errors
///
/// [`Error::UiThread`] on the web.
pub fn sleep_thread(duration: std::time::Duration) -> Result<(), Error> {
    if cfg!(target_family = "wasm") {
        return Err(Error::UiThread);
    }
    std::thread::sleep(duration);
    Ok(())
}

/// Start a named OS thread: the sanctioned replacement for
/// `std::thread::spawn` and `std::thread::Builder::spawn`.
///
/// For work that owns its thread for a long time — an event loop, a device
/// poller, a blocking protocol client. Short jobs belong on [`cpu()`], the
/// [`io`] pool, [`background`], or a runtime's blocking pool instead.
///
/// Unlike `std::thread::spawn`, this never panics: where
/// [`Feature::Threads`] is unsupported (a browser page) it returns an error,
/// and the caller degrades — skips optional work, or runs a short step
/// inline.
///
/// # Errors
///
/// Returns the OS error when the thread cannot be created, and
/// [`std::io::ErrorKind::Unsupported`] on a target without threads.
pub fn spawn_thread<T, F>(
    name: impl Into<String>,
    body: F,
) -> std::io::Result<std::thread::JoinHandle<T>>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    panic_boundary::abort_outside_boundaries_in_release();
    std::thread::Builder::new().name(name.into()).spawn(body)
}

/// Run `body` on a worker thread where the target has them, and inline where
/// it has none (a browser page). A caller that owns one long-lived loop for
/// its own work keeps one shape on every target without selecting by target
/// itself.
///
/// # Errors
///
/// As [`spawn_thread`]; the inline path has none.
#[cfg(not(target_family = "wasm"))]
pub fn spawn_worker<F>(name: impl Into<String>, body: F) -> std::io::Result<()>
where
    F: FnOnce() + Send + 'static,
{
    spawn_thread(name, body).map(|_| ())
}

/// Run `body` inline: this target has no threads.
///
/// # Errors
///
/// Never; the signature answers as the target that has threads does.
#[cfg(target_family = "wasm")]
#[allow(
    clippy::unnecessary_wraps,
    reason = "it answers as the target that has threads does, so a caller compiles once"
)]
pub fn spawn_worker<F>(_name: impl Into<String>, body: F) -> std::io::Result<()>
where
    F: FnOnce(),
{
    body();
    Ok(())
}

/// How far below an ordinary thread [`spawn_background_thread`] runs, as a
/// Linux nice value.
pub const BACKGROUND_NICE: i32 = 10;

/// [`spawn_thread`] for work a person does not wait on frame by frame —
/// rasterising pages ahead of a scroll, decoding, indexing — that must never
/// take a CPU from the thread drawing the window. On Linux the thread runs
/// [`BACKGROUND_NICE`] steps below its spawner, so on a machine with one or
/// two slow cores the UI thread is scheduled first and the work fills the
/// time it leaves; elsewhere it is an ordinary thread.
///
/// # Errors
///
/// As [`spawn_thread`].
pub fn spawn_background_thread<T, F>(
    name: impl Into<String>,
    body: F,
) -> std::io::Result<std::thread::JoinHandle<T>>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    spawn_thread(name, move || {
        lower_current_thread_priority();
        body()
    })
}

/// Lower the calling thread (only it: Linux keeps a nice value per thread)
/// to [`BACKGROUND_NICE`]. Failure leaves it as it was, which is only slower.
pub fn lower_current_thread_priority() {
    #[cfg(target_os = "linux")]
    {
        // SAFETY: `gettid` takes nothing and returns this thread's id.
        let Ok(tid) = libc::id_t::try_from(unsafe { libc::gettid() }) else {
            return;
        };
        // SAFETY: `getpriority`/`setpriority` take and return plain integers;
        // PRIO_PROCESS with a thread id changes that thread alone on Linux.
        unsafe {
            let current = libc::getpriority(libc::PRIO_PROCESS, tid);
            libc::setpriority(
                libc::PRIO_PROCESS,
                tid,
                current.saturating_add(BACKGROUND_NICE).min(19),
            );
        }
    }
}

#[must_use]
pub fn thread_cpu_time() -> Option<std::time::Duration> {
    // macOS has kept the clock since 10.12.
    #[cfg(any(target_os = "linux", target_vendor = "apple"))]
    {
        let mut now = libc::timespec {
            tv_sec: 0,
            tv_nsec: 0,
        };
        // SAFETY: `now` is a valid, writable timespec for the call.
        let status = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &raw mut now) };
        if status != 0 {
            return None;
        }
        Some(std::time::Duration::new(
            u64::try_from(now.tv_sec).ok()?,
            u32::try_from(now.tv_nsec).ok()?,
        ))
    }
    #[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
    {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_background_thread_runs_below_its_spawner() {
        #[cfg(target_os = "linux")]
        {
            // SAFETY: plain integer syscalls on this process's own threads.
            let nice = || unsafe {
                libc::getpriority(
                    libc::PRIO_PROCESS,
                    libc::id_t::try_from(libc::gettid()).unwrap(),
                )
            };
            let spawner = nice();
            let background = spawn_background_thread("nice-test", nice)
                .unwrap()
                .join()
                .unwrap();
            assert_eq!(background, (spawner + BACKGROUND_NICE).min(19));
        }
    }

    #[test]
    #[cfg(any(target_os = "linux", target_vendor = "apple"))]
    fn a_threads_cpu_clock_counts_its_work_and_not_its_sleep() {
        let start = thread_cpu_time().expect("the thread's CPU clock");
        std::thread::sleep(std::time::Duration::from_millis(200));
        let slept = thread_cpu_time().unwrap().saturating_sub(start);
        assert!(slept < std::time::Duration::from_millis(100), "{slept:?}");
        let busy = std::time::Instant::now();
        let mut spin = 0_u64;
        while busy.elapsed() < std::time::Duration::from_millis(50) {
            spin = std::hint::black_box(spin.wrapping_add(1));
        }
        assert!(thread_cpu_time().unwrap() > start.saturating_add(slept));
    }

    tilo_test_env::scenario! {
        fn synchronous_waits_run_the_future_and_refuse_runtime_and_ui_threads;

        phase wait_on_runs_on_the_runtime_and_refuses_its_drivers;
        {
            let runtime = daemon("wait-on-test").workers(1).build().unwrap();
            {
                let value = wait_on(runtime.handle(), async {
                    tokio::time::sleep(std::time::Duration::from_millis(1)).await;
                    tokio::spawn(async { 3 }).await.unwrap()
                })
                .unwrap();
                assert_eq!(value, 3);
            }
            {
                let handle = runtime.handle().clone();
                let nested = wait_on(
                    runtime.handle(),
                    async move { wait_on(&handle, async { 4 }) },
                )
                .unwrap();
                assert!(matches!(nested, Err(Error::InsideRuntime)));
            }
            {
                let other = daemon("wait-on-other").workers(1).build().unwrap();
                let handle = runtime.handle().clone();
                let nested =
                    wait_on(other.handle(), async move { wait_on(&handle, async { 5 }) }).unwrap();
                assert!(matches!(nested, Err(Error::InsideRuntime)));
            }
            {
                // A blocking-pool thread is a thread of its runtime, not a thread
                // that owns none: it asks that runtime instead of building a
                // second one, which tokio refuses and this guard names.
                let handle = runtime.handle().clone();
                let inner = wait_on(runtime.handle(), async move {
                    tokio::task::spawn_blocking(move || wait_on(&handle, async { 6 }))
                        .await
                        .unwrap()
                })
                .unwrap();
                assert!(matches!(inner, Err(Error::InsideRuntime)));
            }
            {
                let handle = runtime.handle().clone();
                let result = spawn_thread("ui-wait-on-test", move || {
                    mark_ui_thread();
                    wait_on(&handle, async { 1 })
                })
                .unwrap()
                .join()
                .unwrap();
                assert!(matches!(result, Err(Error::UiThread)));
            }
            {
                let handle = runtime.handle().clone();
                runtime.shutdown_background();
                assert!(matches!(
                    wait_on(&handle, async { 2 }),
                    Err(Error::TaskFailed)
                ));
            }
        }

        phase block_on_drives_timers_but_refuses_runtime_and_ui_threads;
        {
            {
                let value = block_on(async {
                    tokio::time::sleep(std::time::Duration::from_millis(1)).await;
                    7
                })
                .unwrap();
                assert_eq!(value, 7);
            }
            {
                let nested = block_on(async { block_on(async {}) }).unwrap();
                assert!(matches!(nested, Err(Error::InsideRuntime)));
            }
            {
                let foreign = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .unwrap();
                let nested = foreign.block_on(async { block_on(async {}) });
                assert!(matches!(nested, Err(Error::InsideRuntime)));
            }
            {
                let inner = block_on(async {
                    tokio::task::spawn_blocking(|| app().block_on(async { 9 }))
                        .await
                        .unwrap()
                })
                .unwrap();
                assert_eq!(inner.unwrap(), 9);
            }
            {
                let result = spawn_thread("ui-test", || {
                    mark_ui_thread();
                    block_on(async { 1 })
                })
                .unwrap()
                .join()
                .unwrap();
                assert!(matches!(result, Err(Error::UiThread)));
            }
        }
    }
}