#[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;
#[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;
#[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 {}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("could not start the async runtime: {0}")]
Start(#[from] std::io::Error),
#[error("cannot block on a future from inside an async runtime; await it instead")]
InsideRuntime,
#[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) };
}
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)
}
#[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"
);
}
pub fn in_runtime() -> bool {
Handle::try_current().is_ok()
}
pub fn in_async_context() -> bool {
DRIVING.with(Cell::get)
}
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(())
}
fn check_may_block() -> Result<(), Error> {
check_not_a_driver()?;
if in_runtime() {
return Err(Error::InsideRuntime);
}
Ok(())
}
pub fn block_on<F: Future>(future: F) -> Result<F::Output, Error> {
check_may_block()?;
panic_boundary::abort_outside_boundaries_in_release();
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))
}
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)
}
pub fn sleep_thread(duration: std::time::Duration) -> Result<(), Error> {
if cfg!(target_family = "wasm") {
return Err(Error::UiThread);
}
std::thread::sleep(duration);
Ok(())
}
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)
}
#[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(|_| ())
}
#[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(())
}
pub const BACKGROUND_NICE: i32 = 10;
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()
})
}
pub fn lower_current_thread_priority() {
#[cfg(target_os = "linux")]
{
let Ok(tid) = libc::id_t::try_from(unsafe { libc::gettid() }) else {
return;
};
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> {
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
{
let mut now = libc::timespec {
tv_sec: 0,
tv_nsec: 0,
};
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")]
{
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)));
}
{
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)));
}
}
}
}