Skip to main content

tilo_rt/
daemon.rs

1//! The daemon profile: one bounded multi-thread runtime per process.
2
3use std::cell::Cell;
4use std::future::Future;
5use std::sync::atomic::{AtomicUsize, Ordering};
6use std::sync::{Arc, Condvar, Mutex, PoisonError};
7
8use tokio::runtime::Runtime;
9
10use crate::{Error, pool};
11use tilo_lock::MutexRecover as _;
12
13/// The environment variable a process sets to ask for a worker count.
14///
15/// The same name tokio's own runtime builder reads, so a harness that sets it
16/// for a child (the room bench's `--host-threads`) reaches [`daemon()`].
17pub const WORKER_THREADS_ENV: &str = "TOKIO_WORKER_THREADS";
18
19#[derive(Clone, Debug)]
20pub struct Daemon {
21    name: &'static str,
22    workers: usize,
23    max_blocking: usize,
24}
25
26/// A multi-thread runtime for the service `name`.
27///
28/// Workers default to [`WORKER_THREADS_ENV`] when it holds a positive integer,
29/// and otherwise to the available parallelism, capped
30/// at [`Daemon::DEFAULT_MAX_WORKERS`]: a service waits on sockets and disks, and
31/// more workers than that only add contention. [`Daemon::workers`] overrides
32/// both. The blocking pool defaults to [`Daemon::DEFAULT_MAX_BLOCKING`]
33/// threads instead of tokio's 512, so a burst of blocking calls queues rather
34/// than spawning hundreds of threads. Threads are named `{name}-rt-N`, workers
35/// and blocking-pool threads alike: tokio hands a new thread whichever job is
36/// queued, so a name given at spawn cannot tell the two apart.
37pub fn daemon(name: &'static str) -> Daemon {
38    Daemon {
39        name,
40        workers: default_workers(
41            std::env::var(WORKER_THREADS_ENV).ok().as_deref(),
42            std::thread::available_parallelism().map_or(2, std::num::NonZeroUsize::get),
43        ),
44        max_blocking: Daemon::DEFAULT_MAX_BLOCKING,
45    }
46}
47
48fn default_workers(asked: Option<&str>, available: usize) -> usize {
49    asked
50        .and_then(|asked| asked.trim().parse::<usize>().ok())
51        .filter(|workers| *workers > 0)
52        .unwrap_or_else(|| available.clamp(1, Daemon::DEFAULT_MAX_WORKERS))
53}
54
55impl Daemon {
56    pub const DEFAULT_MAX_WORKERS: usize = 4;
57    pub const DEFAULT_MAX_BLOCKING: usize = pool::DAEMON_BLOCKING_THREADS;
58
59    #[must_use]
60    pub fn workers(mut self, workers: usize) -> Self {
61        self.workers = workers.max(1);
62        self
63    }
64
65    /// Bound the blocking pool at `threads` (at least one).
66    #[must_use]
67    pub fn max_blocking(mut self, threads: usize) -> Self {
68        self.max_blocking = threads.max(1);
69        self
70    }
71
72    pub fn build(&self) -> std::io::Result<Runtime> {
73        crate::panic_boundary::abort_outside_boundaries_in_release();
74        let name = self.name;
75        let workers = self.workers;
76        let spawned = AtomicUsize::new(0);
77        let parked = Arc::new(ParkedWorkers::default());
78        let on_park = Arc::clone(&parked);
79        let runtime = tokio::runtime::Builder::new_multi_thread()
80            .enable_all()
81            .worker_threads(workers)
82            .max_blocking_threads(self.max_blocking)
83            .thread_name_fn(move || {
84                format!("{name}-rt-{}", spawned.fetch_add(1, Ordering::Relaxed))
85            })
86            // Only workers park and unpark; blocking-pool threads never do.
87            // That is what marks a worker as driving tasks, so it refuses to
88            // block, while blocking-pool threads, which exist to block, may.
89            .on_thread_park(move || on_park.worker_parked())
90            .on_thread_unpark(crate::mark_driving)
91            .build()?;
92        // A new worker finds no work and parks at once. Wait for all of them
93        // so that none runs a task before it is marked.
94        parked.wait_for(workers);
95        Ok(runtime)
96    }
97
98    /// Build the runtime and run `main` on it from the calling thread —
99    /// the replacement for `#[tokio::main]`. The runtime shuts down when
100    /// `main` returns.
101    ///
102    /// # Errors
103    ///
104    /// [`Error::InsideRuntime`] or [`Error::UiThread`] when the caller may
105    /// not block — on the UI thread, or in any runtime context, where the
106    /// thread cannot be handed to a second runtime and tokio would panic —
107    /// and [`Error::Start`] when the runtime cannot be built.
108    pub fn run<F: Future>(&self, main: F) -> Result<F::Output, Error> {
109        crate::check_may_block()?;
110        let runtime = self.build()?;
111        let _driving = crate::Driving::enter();
112        Ok(runtime.block_on(main))
113    }
114}
115
116thread_local! {
117    static COUNTED: Cell<bool> = const { Cell::new(false) };
118}
119
120#[derive(Default)]
121struct ParkedWorkers {
122    count: Mutex<usize>,
123    changed: Condvar,
124}
125
126impl ParkedWorkers {
127    fn worker_parked(&self) {
128        crate::mark_driving();
129        if COUNTED.with(|counted| counted.replace(true)) {
130            return;
131        }
132        let mut count = self.count.lock_recover();
133        *count = count.saturating_add(1);
134        drop(count);
135        self.changed.notify_all();
136    }
137
138    fn wait_for(&self, workers: usize) {
139        let count = self.count.lock_recover();
140        drop(
141            self.changed
142                .wait_while(count, |count| *count < workers)
143                .unwrap_or_else(PoisonError::into_inner),
144        );
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use std::collections::BTreeSet;
152
153    tilo_test_env::scenario! {
154        fn a_daemon_runtime_is_bounded_named_and_refuses_to_block_or_nest;
155
156        phase daemon_threads_are_bounded_and_named;
157        {
158            {
159                let runtime = daemon("probe").workers(2).build().unwrap();
160                assert_eq!(runtime.metrics().num_workers(), 2);
161                let names = runtime.block_on(async {
162                    let mut names = BTreeSet::new();
163                    for _ in 0..16 {
164                        let name =
165                            tokio::spawn(async { std::thread::current().name().map(str::to_owned) })
166                                .await
167                                .unwrap();
168                        names.insert(name.unwrap());
169                    }
170                    names
171                });
172                assert!(
173                    names.iter().all(|name| name.starts_with("probe-rt-")),
174                    "{names:?}"
175                );
176            }
177            {
178                // The runner may set the variable for every test it starts, so
179                // the default is what `default_workers` makes of it here.
180                let runtime = daemon("capped").build().unwrap();
181                let asked = std::env::var(WORKER_THREADS_ENV).ok();
182                let available =
183                    std::thread::available_parallelism().map_or(2, std::num::NonZeroUsize::get);
184                assert_eq!(
185                    runtime.metrics().num_workers(),
186                    default_workers(asked.as_deref(), available)
187                );
188            }
189            {
190                // The environment is read in `default_workers`, which takes its
191                // value as an argument: a test that set the variable would race
192                // every other test's runtime in this process.
193                assert_eq!(default_workers(Some("40"), 16), 40);
194                assert_eq!(default_workers(Some(" 3 "), 16), 3);
195            }
196            {
197                for asked in [None, Some(""), Some("0"), Some("four"), Some("-2")] {
198                    assert_eq!(
199                        default_workers(asked, 16),
200                        Daemon::DEFAULT_MAX_WORKERS,
201                        "{asked:?}"
202                    );
203                    assert_eq!(default_workers(asked, 1), 1, "{asked:?}");
204                }
205            }
206            {
207                // `Daemon::workers` sets the count outright; the environment only
208                // reaches the default, so a caller's choice is never overridden.
209                let runtime = daemon("explicit").workers(2).build().unwrap();
210                assert_eq!(runtime.metrics().num_workers(), 2);
211            }
212            {
213                let runtime = daemon("svc").workers(1).max_blocking(2).build().unwrap();
214                let (name, driving) = runtime
215                    .block_on(async {
216                        tokio::task::spawn_blocking(|| {
217                            (
218                                std::thread::current().name().map(str::to_owned),
219                                crate::in_async_context(),
220                            )
221                        })
222                        .await
223                    })
224                    .unwrap();
225                let name = name.unwrap();
226                assert!(name.starts_with("svc-rt-"), "{name}");
227                assert!(!driving, "{name} is a blocking-pool thread");
228            }
229        }
230
231        phase daemon_workers_refuse_to_block_or_nest;
232        {
233            {
234                let runtime = daemon("guard").workers(1).build().unwrap();
235                let (on_worker, on_blocking) = runtime.block_on(async {
236                    let on_worker = tokio::spawn(async { crate::block_on(async {}) })
237                        .await
238                        .unwrap();
239                    let on_blocking = tokio::task::spawn_blocking(|| crate::block_on(async { 1 }))
240                        .await
241                        .unwrap();
242                    (on_worker, on_blocking)
243                });
244                assert!(matches!(on_worker, Err(Error::InsideRuntime)));
245                assert!(
246                    matches!(on_blocking, Err(Error::InsideRuntime)),
247                    "a blocking-pool thread is already inside the runtime; it cannot start a second one"
248                );
249            }
250            {
251                let foreign = tokio::runtime::Builder::new_current_thread()
252                    .enable_all()
253                    .build()
254                    .unwrap();
255                let nested = foreign.block_on(async { daemon("nested").workers(1).run(async {}) });
256                assert!(matches!(nested, Err(Error::InsideRuntime)));
257            }
258            {
259                let outer = daemon("outer")
260                    .workers(1)
261                    .run(async { daemon("inner").workers(1).run(async {}) });
262                assert!(matches!(outer.unwrap(), Err(Error::InsideRuntime)));
263            }
264        }
265    }
266}