Skip to main content

egui_kit/
remote.rs

1//! Queries and commands: async data and mutations, as easy to start as `tokio::spawn`, inspired
2//! by SvelteKit's [remote functions](https://svelte.dev/docs/kit/remote-functions) and `TanStack`
3//! Query.
4//!
5//! A route's `load` fetches what its page needs before it is shown. Some data doesn't belong to
6//! a route, though: a badge in a layout, an autocomplete, a count that several pages show. And
7//! changing data is often async too (a `POST` to a backend), which a view can't `await`.
8//!
9//! - A [`Query`] is async data: it fetches on its first read, and can be
10//!   [refreshed](Query::refresh), [refetched periodically](Query::refetch_every) and
11//!   [cached](Query::key), so that queries with the same key share one result. A [`Live`]
12//!   makes one from inputs that change.
13//! - A [`Command`] is an async mutation: [run](Command::run) it, and see whether it's pending
14//!   and how it ended. Once it succeeded, it [refreshes](Command::refreshes) the loads and
15//!   queries that depend on what it changed.
16//!
17//! Both are plain values: keep them in the app state, a [`PageState`](crate::extract::PageState)
18//! or any struct of yours. Clones share their state.
19//!
20//! # Example
21//!
22//! A todo list that fetches the todos from a backend, and adds one with a `POST`:
23//!
24//! ```
25//! use std::sync::{Arc, Mutex};
26//!
27//! use egui::Ui;
28//! use egui_kit::remote::{self, Command, Query, QueryState};
29//!
30//! /// The backend. A stand-in for an HTTP client like `reqwest::Client`: cheap to clone, and
31//! /// `Send`, as queries and commands run on other threads.
32//! #[derive(Clone, Default)]
33//! struct Api {
34//!     todos: Arc<Mutex<Vec<String>>>,
35//! }
36//!
37//! impl Api {
38//!     /// `GET /todos`
39//!     async fn todos(&self) -> Result<Vec<String>, String> {
40//!         Ok(self.todos.lock().unwrap().clone())
41//!     }
42//!
43//!     /// `POST /todos`
44//!     async fn add_todo(&self, title: String) -> Result<(), String> {
45//!         if title.is_empty() {
46//!             return Err("a todo needs a title".into());
47//!         }
48//!         self.todos.lock().unwrap().push(title);
49//!         Ok(())
50//!     }
51//! }
52//!
53//! struct TodoList {
54//!     api: Api,
55//!     todos: Query<Vec<String>, String>,
56//!     add: Command<(), String>,
57//!     title: String,
58//! }
59//!
60//! impl TodoList {
61//!     fn new(api: Api) -> Self {
62//!         // The closure is called for every fetch (the first one, refreshes, refetches), and
63//!         // returns a new future each time, with its own clone of the client.
64//!         let todos = remote::query({
65//!             let api = api.clone();
66//!             move || {
67//!                 let api = api.clone();
68//!                 async move { api.todos().await }
69//!             }
70//!         })
71//!         // Every query with this key, anywhere in the app, shares this one's value.
72//!         .key("todos")
73//!         // Refetch when "todos" is invalidated, e.g. by the command below.
74//!         .depends("todos");
75//!
76//!         Self {
77//!             api,
78//!             todos,
79//!             // Invalidates "todos" once a todo was added.
80//!             add: remote::command().refreshes("todos"),
81//!             title: String::new(),
82//!         }
83//!     }
84//!
85//!     fn ui(&mut self, ui: &mut Ui) {
86//!         match self.todos.state() {
87//!             QueryState::Loading => {
88//!                 ui.spinner();
89//!             }
90//!             QueryState::Ready(todos) => {
91//!                 for todo in todos.iter() {
92//!                     ui.label(todo);
93//!                 }
94//!             }
95//!             QueryState::Failed(error) => {
96//!                 ui.label(format!("Couldn't load the todos: {error}"));
97//!             }
98//!         }
99//!
100//!         ui.horizontal(|ui| {
101//!             ui.text_edit_singleline(&mut self.title);
102//!             if ui.add_enabled(!self.add.is_pending(), egui::Button::new("Add")).clicked() {
103//!                 let api = self.api.clone();
104//!                 let title = core::mem::take(&mut self.title);
105//!                 self.add.run(async move { api.add_todo(title).await });
106//!             }
107//!         });
108//!         if let Some(error) = self.add.error() {
109//!             ui.label(&*error);
110//!         }
111//!     }
112//! }
113//! ```
114//!
115//! When the `POST` succeeds, the command invalidates `"todos"`, the query refetches, and the
116//! list shows the new todo. Nothing else has to tell the list that it changed.
117//!
118//! # Keys, dependencies and refreshes
119//!
120//! They answer different questions:
121//!
122//! | | Answers | Set with |
123//! |---|---|---|
124//! | key | *Which* data is this? Queries with the same key are the same data. | [`Query::key`] |
125//! | dependency | *When* is it outdated? It refetches when one of its dependencies is invalidated. | [`Query::depends`], [`Page::depends`] |
126//! | refresh | *What* did a mutation change? The dependencies it invalidates when it succeeds. | [`Command::refreshes`] |
127//!
128//! A **key** identifies a query's value in the cache. Queries with the same key (and value and
129//! error types) share one state: they fetch once for all of them, and a query created later
130//! finds the value right away, e.g. when a page is opened again. So the key must contain
131//! everything the fetch depends on: `("user", id)`, not `"user"`. A query without a key has a
132//! value of its own, which is dropped with it. The key is only hashed, never kept or printed, so
133//! it may contain secrets, like the session token of per-user data: `("todos", &token)`.
134//!
135//! A **dependency** is a name for some data on the backend, like `"todos"` or `"users"`. It is
136//! the same kind of name as a load's [`Page::depends`]: a single invalidation reruns the loads
137//! and refetches the queries that depend on it, so many queries can depend on one name, and a
138//! query can depend on several. Dependencies are coarser than keys: `("user", 1)` and
139//! `("user", 2)` are two keys that both depend on `"users"`.
140//!
141//! A **refresh** invalidates a dependency once a command succeeded: the command says what it
142//! changed, and doesn't need to know who shows it. Invalidating a dependency directly does the
143//! same, with [`Nav::invalidate`] in a view, or with [`invalidate`] from anywhere on the UI
144//! thread.
145//!
146//! ```
147//! # use egui_kit::remote::{self, Command, Query};
148//! # #[derive(Clone)]
149//! # struct Api;
150//! # impl Api {
151//! #     async fn user(&self, _id: u32) -> Result<String, String> { Ok("Ferris".into()) }
152//! #     async fn rename(&self, _id: u32, _name: String) -> Result<(), String> { Ok(()) }
153//! # }
154//! fn user(api: &Api, id: u32) -> Query<String, String> {
155//!     let api = api.clone();
156//!     remote::query(move || {
157//!         let api = api.clone();
158//!         async move { api.user(id).await }
159//!     })
160//!     .key(("user", id)) // one cache entry per user
161//!     .depends("users") // refetched when any user changes
162//! }
163//!
164//! fn rename(api: &Api, rename: &Command<(), String>, id: u32, name: String) {
165//!     let api = api.clone();
166//!     // `rename` was created with `remote::command().refreshes("users")`: once it succeeded,
167//!     // every user query refetches, and so do the loads with `.depends("users")`.
168//!     rename.run(async move { api.rename(id, name).await });
169//! }
170//! ```
171//!
172//! The [`RouterApp`] applies invalidations at its next frame. A query that is invalidated keeps
173//! its value, and refetches the next time it is read.
174//!
175//! # Queries from changing inputs
176//!
177//! A query is made from its inputs: a date range, a search text, a form to check. A new query
178//! fetches on its first read, so a view can't make one from its current inputs every frame: it
179//! would fetch every frame. Keep a [`Live`] instead and [update](Live::update) it every frame
180//! with the inputs: it makes a new query only when they changed. It can also keep showing the
181//! previous value while the new one loads, and wait for the inputs to settle (a search being
182//! typed) before it asks.
183//!
184//! ```
185//! # use egui_kit::remote::{self, Live, Query};
186//! # #[derive(Clone)]
187//! # struct Api;
188//! # impl Api {
189//! #     async fn week(&self, _monday: u32) -> Result<Vec<String>, String> { Ok(Vec::new()) }
190//! # }
191//! fn week(api: &Api, monday: u32) -> Query<Vec<String>, String> {
192//!     let api = api.clone();
193//!     remote::query(move || {
194//!         let api = api.clone();
195//!         async move { api.week(monday).await }
196//!     })
197//!     .key(("week", monday))
198//! }
199//!
200//! fn calendar(
201//!     ui: &mut egui::Ui,
202//!     api: &Api,
203//!     monday: u32,
204//!     appointments: &mut Live<Vec<String>, String>,
205//! ) {
206//!     // `appointments` is `remote::live().keep_previous()`: the week before stays until the
207//!     // next one arrives.
208//!     if let Some(list) = appointments.update(monday, || week(api, monday)).data() {
209//!         for appointment in list.iter() {
210//!             ui.label(appointment);
211//!         }
212//!     }
213//! }
214//! ```
215//!
216//! # Runtimes
217//!
218//! Natively, queries and commands run on a Tokio runtime, so their futures must be `Send` (see
219//! [`MaybeSend`]). It is the one the app entered if any (a multi-threaded one, as nothing drives
220//! a current-thread runtime between frames), else one that egui-kit starts. [`RouterApp::ui`]
221//! enters it too, so that hooks and loads can use Tokio-based clients like `reqwest`. On the
222//! web, futures run on the browser's event loop and needn't be `Send`.
223//!
224//! A query or command wakes egui up when it finishes, once the app's context is known on this
225//! thread: a [`RouterApp`] sets it at each frame, and [`set_context`] before the router's first
226//! frame (e.g. for a command that checks a stored session before the router is built) or in an
227//! app without a router. Work started earlier wakes egui up too, if the context is known by the
228//! time it finishes. Its result is picked up when it is read.
229//!
230//! # Caching
231//!
232//! A query fetches on its first read, and keeps its value while it refetches. A keyed value
233//! outlives its queries for [a while](Query::cache_for), so that a page opened again shows it
234//! right away. A query reading a cached value for the first time refetches it if it is [older
235//! than `stale_after`](Query::stale_after), showing the cached value meanwhile.
236//!
237//! Dropping a query's state (its last clone, and its cache entry if keyed) aborts its fetch,
238//! like refreshing it aborts the one in progress. Commands always run to completion.
239//!
240//! [`RouterApp`]: crate::RouterApp
241//! [`RouterApp::ui`]: crate::RouterApp::ui
242//! [`Page::depends`]: crate::page::Page::depends
243//! [`Nav::invalidate`]: crate::extract::Nav::invalidate
244
245mod command;
246mod live;
247mod query;
248mod runtime;
249
250use core::any::{Any, TypeId};
251use core::cell::RefCell;
252use core::hash::{BuildHasher as _, Hash};
253use core::time::Duration;
254use std::collections::HashMap;
255use std::hash::RandomState;
256use std::rc::{Rc, Weak};
257use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError};
258
259use web_time::Instant;
260
261pub use command::{Command, command};
262pub use live::{Live, live};
263pub use query::{Query, QueryState, query};
264pub use runtime::MaybeSend;
265pub(crate) use runtime::enter;
266
267use crate::load::Invalidation;
268
269/// A query's state, as the registry sees it.
270trait Entry {
271    /// Marks it for a refetch if `invalidation` hits what it depends on.
272    fn invalidate(&self, invalidation: &Invalidation);
273
274    /// Whether a cache entry no query uses should be dropped.
275    fn expired(&self, now: Instant) -> bool;
276
277    fn as_any(self: Rc<Self>) -> Rc<dyn Any>;
278}
279
280/// The queries and commands of this thread.
281#[derive(Default)]
282struct Registry {
283    /// Every query's state, to invalidate them.
284    entries: Vec<Weak<dyn Entry>>,
285    /// How many entries were left after the dropped ones were last pruned.
286    pruned_len: usize,
287    /// The state of keyed queries, by value type and key.
288    cache: HashMap<(TypeId, u64), Rc<dyn Entry>>,
289    /// The app's context, to wake it up when a query or command finished. Shared with them, so
290    /// that the ones started before it was known wake it up too.
291    ctx: Arc<Mutex<Option<egui::Context>>>,
292    /// Keys to invalidate, from [`invalidate`] and from the commands that succeeded.
293    invalidated: Arc<Mutex<Vec<String>>>,
294}
295
296thread_local! {
297    static REGISTRY: RefCell<Registry> = RefCell::default();
298}
299
300fn with_registry<R>(f: impl FnOnce(&mut Registry) -> R) -> R {
301    REGISTRY.with(|registry| f(&mut registry.borrow_mut()))
302}
303
304impl Registry {
305    /// Forgets the entries of the dropped queries.
306    fn prune(&mut self) {
307        self.entries.retain(|entry| entry.strong_count() > 0);
308        self.pruned_len = self.entries.len();
309    }
310}
311
312fn context() -> Option<egui::Context> {
313    with_registry(|registry| lock(&registry.ctx).clone())
314}
315
316/// The app's context, as it will be when a query or command finishes.
317fn shared_context() -> Arc<Mutex<Option<egui::Context>>> {
318    with_registry(|registry| Arc::clone(&registry.ctx))
319}
320
321/// Wakes the app up, if its context is known.
322fn request_repaint(ctx: &Mutex<Option<egui::Context>>) {
323    let ctx = lock(ctx).clone();
324    if let Some(ctx) = ctx {
325        ctx.request_repaint();
326    }
327}
328
329/// Hashes query keys and [`Live`] inputs, the same way for the whole process.
330fn hash(value: impl Hash) -> u64 {
331    static HASHER: LazyLock<RandomState> = LazyLock::new(RandomState::new);
332    HASHER.hash_one(value)
333}
334
335fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
336    mutex.lock().unwrap_or_else(PoisonError::into_inner)
337}
338
339/// Reruns the loads and queries that depend on `key`, like
340/// [`Nav::invalidate`](crate::extract::Nav::invalidate), from anywhere on the UI thread. The
341/// router applies it at its next frame.
342pub fn invalidate(key: impl Into<String>) {
343    let invalidated = with_registry(|registry| Arc::clone(&registry.invalidated));
344    lock(&invalidated).push(key.into());
345    request_repaint(&shared_context());
346}
347
348/// Sets the app's context on this thread, so that queries and commands wake it up when they
349/// finish, including the ones in progress.
350///
351/// A [`RouterApp`](crate::RouterApp) sets it at the start of each frame. Call it yourself when
352/// queries or commands run before the router's first frame, or in an app without a router,
353/// e.g. in the app's constructor, with eframe's `CreationContext::egui_ctx`:
354///
355/// ```
356/// use egui_kit::remote::{self, Command};
357///
358/// struct Shell {
359///     check_session: Command<bool, String>,
360/// }
361///
362/// impl Shell {
363///     fn new(ctx: &egui::Context) -> Self {
364///         // Without it, a reactive app would show its spinner until the mouse moves.
365///         remote::set_context(ctx);
366///         let check_session = remote::command();
367///         check_session.run(async { Ok(true) });
368///         Self { check_session }
369///     }
370/// }
371/// ```
372pub fn set_context(ctx: &egui::Context) {
373    *lock(&shared_context()) = Some(ctx.clone());
374}
375
376/// The keys [invalidated](invalidate) since the last call.
377pub(crate) fn take_invalidated() -> Vec<String> {
378    let invalidated = with_registry(|registry| Arc::clone(&registry.invalidated));
379    core::mem::take(&mut *lock(&invalidated))
380}
381
382/// Marks the queries that depend on what `invalidation` hits for a refetch.
383pub(crate) fn invalidate_queries(invalidation: &Invalidation) {
384    let entries: Vec<_> = with_registry(|registry| {
385        registry.prune();
386        registry.entries.iter().filter_map(Weak::upgrade).collect()
387    });
388    for entry in entries {
389        entry.invalidate(invalidation);
390    }
391}
392
393/// Drops the cache entries that no query used for long enough, and forgets the dropped
394/// queries.
395pub(crate) fn end_frame() {
396    let now = Instant::now();
397    // Dropped outside of the registry: dropping a query's state aborts its fetch.
398    let _expired: Vec<_> = with_registry(|registry| {
399        // Once the entries doubled, so that pruning takes amortized constant time per query.
400        if registry.entries.len() > (2 * registry.pruned_len).max(PRUNE_AT) {
401            registry.prune();
402        }
403        let keys: Vec<_> = registry
404            .cache
405            .iter()
406            .filter(|(_, entry)| Rc::strong_count(entry) == 1 && entry.expired(now))
407            .map(|(key, _)| *key)
408            .collect();
409        keys.into_iter()
410            .filter_map(|key| registry.cache.remove(&key))
411            .collect()
412    });
413}
414
415/// How many query entries there may be before [`end_frame`] first prunes them.
416const PRUNE_AT: usize = 64;
417
418/// How long a keyed query's value is kept by default once no query uses it.
419const CACHE_FOR: Duration = Duration::from_mins(5);
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424
425    #[test]
426    fn dropped_queries_are_pruned_without_invalidations() {
427        for _ in 0..1000 {
428            drop(query(|| async { Ok::<_, ()>(()) }));
429            end_frame();
430        }
431        let len = with_registry(|registry| registry.entries.len());
432        assert!(len <= PRUNE_AT, "{len} entries");
433    }
434}