1use std::future::Future;
4use std::sync::OnceLock;
5use std::thread::ThreadId;
6
7use tokio::runtime::Handle;
8use tokio::task::JoinHandle;
9
10use crate::{Error, pool};
11
12pub(crate) const APP_THREAD: &str = "tilo-rt";
13
14#[derive(Debug)]
24pub struct AppRuntime {
25 handle: Handle,
26 thread: ThreadId,
27}
28
29static APP: OnceLock<Result<AppRuntime, String>> = OnceLock::new();
30
31#[allow(
32 clippy::panic,
33 reason = "a process that cannot start one thread cannot run an app; try_app reports it"
34)]
35pub fn app() -> &'static AppRuntime {
36 match try_app() {
37 Ok(runtime) => runtime,
38 Err(error) => panic!("{error}"),
39 }
40}
41
42pub fn try_app() -> Result<&'static AppRuntime, Error> {
43 APP.get_or_init(|| AppRuntime::start().map_err(|error| error.to_string()))
44 .as_ref()
45 .map_err(|message| Error::Start(std::io::Error::other(message.clone())))
46}
47
48impl AppRuntime {
49 fn start() -> std::io::Result<Self> {
50 let runtime = tokio::runtime::Builder::new_current_thread()
51 .enable_all()
52 .thread_name("tilo-rt-blocking")
53 .max_blocking_threads(pool::APP_BLOCKING_THREADS)
54 .build()?;
55 let handle = runtime.handle().clone();
56 let driver = crate::spawn_thread(APP_THREAD, move || {
57 let _driving = crate::Driving::enter();
58 runtime.block_on(std::future::pending::<()>());
59 })?;
60 Ok(Self {
61 handle,
62 thread: driver.thread().id(),
63 })
64 }
65
66 pub const fn handle(&self) -> &Handle {
67 &self.handle
68 }
69
70 pub const fn thread_id(&self) -> ThreadId {
71 self.thread
72 }
73
74 pub fn is_runtime_thread(&self) -> bool {
75 std::thread::current().id() == self.thread
76 }
77
78 pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
81 where
82 F: Future + Send + 'static,
83 F::Output: Send + 'static,
84 {
85 self.handle.spawn(future)
86 }
87
88 pub fn spawn_then<F, D>(&self, future: F, deliver: D) -> JoinHandle<()>
94 where
95 F: Future + Send + 'static,
96 F::Output: Send + 'static,
97 D: FnOnce(F::Output) + Send + 'static,
98 {
99 self.handle.spawn(async move { deliver(future.await) })
100 }
101
102 pub fn spawn_pinned<M, F>(&self, make: M) -> JoinHandle<F::Output>
107 where
108 M: FnOnce() -> F + Send + 'static,
109 F: Future + 'static,
110 F::Output: Send + 'static,
111 {
112 let handle = self.handle.clone();
113 self.handle.spawn_blocking(move || {
114 let _driving = crate::Driving::enter();
115 handle.block_on(make())
116 })
117 }
118
119 pub fn spawn_blocking<F, R>(&self, call: F) -> JoinHandle<R>
121 where
122 F: FnOnce() -> R + Send + 'static,
123 R: Send + 'static,
124 {
125 self.handle.spawn_blocking(call)
126 }
127
128 pub fn block_on<F: Future>(&self, future: F) -> Result<F::Output, Error> {
150 crate::check_not_a_driver()?;
151 let _driving = crate::Driving::enter();
152 if Handle::try_current().is_ok() {
153 let _app = self.handle.enter();
154 return Ok(park_on(future));
155 }
156 Ok(self.handle.block_on(future))
157 }
158}
159
160fn park_on<F: Future>(future: F) -> F::Output {
161 use std::sync::Arc;
162 use std::task::{Context, Poll, Wake, Waker};
163 use std::thread::Thread;
164
165 struct Unpark(Thread);
166 impl Wake for Unpark {
167 fn wake(self: Arc<Self>) {
168 self.0.unpark();
169 }
170 fn wake_by_ref(self: &Arc<Self>) {
171 self.0.unpark();
172 }
173 }
174
175 let waker = Waker::from(Arc::new(Unpark(std::thread::current())));
176 let mut context = Context::from_waker(&waker);
177 let mut future = std::pin::pin!(future);
178 loop {
179 if let Poll::Ready(output) = future.as_mut().poll(&mut context) {
180 return output;
181 }
182 std::thread::park();
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189 use std::sync::mpsc;
190
191 use std::time::Duration;
192
193 tilo_test_env::scenario! {
194 fn the_app_runtime_drives_tasks_on_its_own_thread_and_blocks_only_callers_off_it;
195
196 phase the_app_runtime_runs_on_its_own_thread_and_drives_spawned_tasks;
197 {
198 {
199 let runtime = app();
200 let caller = std::thread::current().id();
201 let (tx, rx) = mpsc::channel();
202 runtime.spawn(async move {
203 let current = std::thread::current();
204 tx.send((current.id(), current.name().map(str::to_owned)))
205 .unwrap();
206 });
207 let (ran_on, name) = tilo_test_env::recv("the task's thread and name", &rx);
208 assert_ne!(ran_on, caller);
209 assert_eq!(ran_on, runtime.thread_id());
210 assert_eq!(name.as_deref(), Some(APP_THREAD));
211 assert!(!runtime.is_runtime_thread());
212 }
213 {
214 let runtime = app();
215 let _task = runtime.spawn(async {});
216 assert!(!crate::in_runtime());
217 }
218 {
219 let (tx, rx) = mpsc::channel();
220 app().spawn_then(
221 async {
222 tokio::time::sleep(Duration::from_millis(5)).await;
223 "slept"
224 },
225 move |out| tx.send(out).unwrap(),
226 );
227 assert_eq!(tilo_test_env::recv("the slept task's output", &rx), "slept");
228 }
229 {
230 let (tx, rx) = mpsc::channel();
231 app().spawn_pinned(move || async move {
232 let pinned = std::rc::Rc::new(4);
233 tokio::time::sleep(Duration::from_millis(2)).await;
234 tx.send(*pinned + 1).unwrap();
235 });
236 assert_eq!(tilo_test_env::recv("the pinned task's value", &rx), 5);
237 }
238 }
239
240 phase blocking_is_allowed_off_the_runtime_thread_only;
241 {
242 {
243 let runtime = app();
244 assert_eq!(runtime.block_on(async { 3 }).unwrap(), 3);
245 let nested = runtime
246 .block_on(async { app().block_on(async {}) })
247 .unwrap();
248 assert!(matches!(nested, Err(Error::InsideRuntime)));
249 }
250 {
251 let label = String::from("borrowed");
252 let seen = app()
253 .block_on(async {
254 tokio::time::sleep(Duration::from_millis(2)).await;
255 label.len()
256 })
257 .unwrap();
258 assert_eq!(seen, label.len());
259 }
260 {
261 let runtime = app();
262 let (release, check) = mpsc::channel::<()>();
263 let blocked = runtime.spawn_blocking(move || check.recv().unwrap());
264 assert_eq!(runtime.block_on(async { 5 }).unwrap(), 5);
267 release.send(()).unwrap();
268 runtime.block_on(blocked).unwrap().unwrap();
269 }
270 }
271
272 phase a_caller_inside_another_runtime_waits_with_the_app_drivers;
273 {
274 {
275 let foreign = tokio::runtime::Builder::new_current_thread()
276 .enable_all()
277 .build()
278 .unwrap();
279 let seen = foreign.block_on(async {
280 app().block_on(async {
281 tokio::time::sleep(Duration::from_millis(2)).await;
282 7
283 })
284 });
285 assert_eq!(seen.unwrap(), 7);
286 }
287 {
288 fn radios() -> u32 {
289 app()
290 .block_on(async {
291 tokio::time::sleep(Duration::from_millis(2)).await;
292 11
293 })
294 .unwrap()
295 }
296 let foreign = tokio::runtime::Builder::new_current_thread()
297 .enable_all()
298 .build()
299 .unwrap();
300 let seen = tokio::task::LocalSet::new().block_on(&foreign, async { radios() });
301 assert_eq!(seen, 11);
302 }
303 {
304 let foreign = tokio::runtime::Builder::new_current_thread()
305 .enable_all()
306 .build()
307 .unwrap();
308 let seen = foreign.block_on(async {
309 app().block_on(async {
310 let task = app().spawn(async {
311 tokio::time::sleep(Duration::from_millis(2)).await;
312 5
313 });
314 task.await.unwrap()
315 })
316 });
317 assert_eq!(seen.unwrap(), 5);
318 }
319 {
320 let entered = app().handle().enter();
321 let seen = app().block_on(async { 13 }).unwrap();
322 drop(entered);
323 assert_eq!(seen, 13);
324 }
325 {
326 let foreign = tokio::runtime::Builder::new_current_thread()
327 .enable_all()
328 .build()
329 .unwrap();
330 let nested = foreign
331 .block_on(async { app().block_on(async { app().block_on(async {}) }) })
332 .unwrap();
333 assert!(matches!(nested, Err(Error::InsideRuntime)));
334 }
335 }
336
337 phase a_ui_thread_inside_another_runtime_is_refused;
338 {
339 let result = crate::spawn_thread("ui-app-block-on", || {
340 crate::mark_ui_thread();
341 let foreign = tokio::runtime::Builder::new_current_thread()
342 .enable_all()
343 .build()
344 .unwrap();
345 foreign.block_on(async { app().block_on(async { 1 }) })
346 })
347 .unwrap()
348 .join()
349 .unwrap();
350 assert!(matches!(result, Err(Error::UiThread)));
351 }
352 }
353}