teksilo_tokio/lib.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! # teksilo-tokio — Tokio reactor for Teksilo's async executor
5//!
6//! Thin adapter over [`teksilo-async`](teksilo_async): it installs the same
7//! main-thread executor, but wraps each executor tick in a
8//! [`tokio::runtime::Runtime`] context so **native Tokio futures** (timers,
9//! sockets, `reqwest`, `sqlx`, …) can be `.await`ed directly inside
10//! `ctx.spawn_local(...)` bodies.
11//!
12//! ```ignore
13//! use teksilo_tokio::TeksiloAppBuilderTokioExt;
14//! TeksiloAppBuilder::new().install_async_tokio() /* ... */ .run();
15//!
16//! // inside a handler:
17//! ctx.spawn_local(async move {
18//! tokio::time::sleep(std::time::Duration::from_secs(1)).await;
19//! let body = reqwest::get(url).await?.text().await?;
20//! status.set(body); // resume on the UI thread → set a Signal
21//! })
22//! .detach();
23//! ```
24//!
25//! ## How it works
26//!
27//! The executor polls `!Send` futures on the UI thread. A multi-thread Tokio
28//! runtime runs the reactor / timer driver on background threads. By entering
29//! the runtime context (`runtime.enter()`) around each tick, a Tokio leaf
30//! future polled on the UI thread registers with that background driver — and
31//! crucially registers *our* executor's `Waker`. When the timer/socket is
32//! ready, the background driver wakes our `Waker`, which nudges the event loop
33//! to tick again. No blocking, no second event loop.
34
35use std::future::Future;
36use std::sync::Arc;
37
38use teksilo_app::TeksiloAppBuilder;
39use teksilo_async::AsyncRuntimeHandle;
40
41// Re-export the spawn surface so `use teksilo_tokio::*;` is enough for crate
42// users that don't go through the `teksilo` umbrella prelude.
43pub use teksilo_async::{EventContextAsyncExt, TaskHandle, spawn_blocking};
44
45/// Shared background Tokio runtime, registered in app-state by
46/// [`install_async_tokio`](TeksiloAppBuilderTokioExt::install_async_tokio).
47/// Fetch with `ctx.app_state::<TokioHandle>()` to spawn `Send` tasks on the
48/// background runtime or obtain a [`tokio::runtime::Handle`]. `Clone` shares
49/// the same runtime (`Arc`).
50#[derive(Clone)]
51pub struct TokioHandle {
52 runtime: Arc<tokio::runtime::Runtime>,
53}
54
55impl TokioHandle {
56 /// A cloneable [`tokio::runtime::Handle`] to the background runtime.
57 pub fn handle(&self) -> tokio::runtime::Handle {
58 self.runtime.handle().clone()
59 }
60
61 /// Spawn a `Send` future on the background runtime (off the UI thread).
62 /// For `!Send` UI work that touches `Signal`s, use `ctx.spawn_local(...)`.
63 pub fn spawn<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
64 where
65 F: Future + Send + 'static,
66 F::Output: Send + 'static,
67 {
68 self.runtime.spawn(future)
69 }
70}
71
72/// Adds [`install_async_tokio`](TeksiloAppBuilderTokioExt::install_async_tokio)
73/// to the app builder.
74pub trait TeksiloAppBuilderTokioExt {
75 /// Install the main-thread executor with a background Tokio runtime as its
76 /// reactor. Registers the [`AsyncRuntimeHandle`], its completion registry,
77 /// and a [`TokioHandle`] in app-state, and drives the executor inside the
78 /// runtime context each loop turn. After this, handlers can call
79 /// `ctx.spawn_local(...)` and `.await` native Tokio futures.
80 fn install_async_tokio(self) -> Self;
81}
82
83impl TeksiloAppBuilderTokioExt for TeksiloAppBuilder {
84 fn install_async_tokio(self) -> Self {
85 let runtime = Arc::new(
86 tokio::runtime::Builder::new_multi_thread()
87 .enable_all()
88 .build()
89 .expect("teksilo-tokio: failed to build the Tokio runtime"),
90 );
91 let handle = AsyncRuntimeHandle::new();
92 let poll_source = handle.poll_source();
93 let completions = handle.completions();
94 let tick_handle = handle.clone();
95 let waker_handle = handle.clone();
96 let rt = runtime.clone();
97 self.app_state(handle)
98 .app_state(completions)
99 .app_state(TokioHandle { runtime })
100 .on_loop_tick(poll_source, move || {
101 // Enter the runtime context so Tokio leaf futures polled during
102 // this tick register with the background reactor / timer driver
103 // (and register our executor's Waker as the wake target).
104 let _guard = rt.enter();
105 tick_handle.tick()
106 })
107 // Wire the cross-thread waker at startup, exactly like plain
108 // `install_async`. Without it, a `spawn_blocking` (or any background
109 // task) that completes while the event loop is idle never nudges
110 // the loop to tick, so the result appears to hang until some other
111 // event happens to wake it. The AppEventProxy is itself an
112 // AppEventPoster; `set_poster` is idempotent.
113 .on_ready(move |proxy| waker_handle.set_poster(std::sync::Arc::new(proxy)))
114 }
115}