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.
12//! - A [`Command`] is an async mutation: [run](Command::run) it, and see whether it's pending
13//!   and how it ended. Once it succeeded, it [refreshes](Command::refreshes) the loads and
14//!   queries that depend on what it changed.
15//!
16//! Both are plain values: keep them in the app state, a [`PageState`](crate::extract::PageState)
17//! or any struct of yours. Clones share their state.
18//!
19//! # Example
20//!
21//! A todo list that fetches the todos from a backend, and adds one with a `POST`:
22//!
23//! ```
24//! use std::sync::{Arc, Mutex};
25//!
26//! use egui::Ui;
27//! use egui_kit::remote::{self, Command, Query, QueryState};
28//!
29//! /// The backend. A stand-in for an HTTP client like `reqwest::Client`: cheap to clone, and
30//! /// `Send`, as queries and commands run on other threads.
31//! #[derive(Clone, Default)]
32//! struct Api {
33//!     todos: Arc<Mutex<Vec<String>>>,
34//! }
35//!
36//! impl Api {
37//!     /// `GET /todos`
38//!     async fn todos(&self) -> Result<Vec<String>, String> {
39//!         Ok(self.todos.lock().unwrap().clone())
40//!     }
41//!
42//!     /// `POST /todos`
43//!     async fn add_todo(&self, title: String) -> Result<(), String> {
44//!         if title.is_empty() {
45//!             return Err("a todo needs a title".into());
46//!         }
47//!         self.todos.lock().unwrap().push(title);
48//!         Ok(())
49//!     }
50//! }
51//!
52//! struct TodoList {
53//!     api: Api,
54//!     todos: Query<Vec<String>, String>,
55//!     add: Command<(), String>,
56//!     title: String,
57//! }
58//!
59//! impl TodoList {
60//!     fn new(api: Api) -> Self {
61//!         // The closure is called for every fetch (the first one, refreshes, refetches), and
62//!         // returns a new future each time, with its own clone of the client.
63//!         let todos = remote::query({
64//!             let api = api.clone();
65//!             move || {
66//!                 let api = api.clone();
67//!                 async move { api.todos().await }
68//!             }
69//!         })
70//!         // Every query with this key, anywhere in the app, shares this one's value.
71//!         .key("todos")
72//!         // Refetch when "todos" is invalidated, e.g. by the command below.
73//!         .depends("todos");
74//!
75//!         Self {
76//!             api,
77//!             todos,
78//!             // Invalidates "todos" once a todo was added.
79//!             add: remote::command().refreshes("todos"),
80//!             title: String::new(),
81//!         }
82//!     }
83//!
84//!     fn ui(&mut self, ui: &mut Ui) {
85//!         match self.todos.state() {
86//!             QueryState::Loading => {
87//!                 ui.spinner();
88//!             }
89//!             QueryState::Ready(todos) => {
90//!                 for todo in todos.iter() {
91//!                     ui.label(todo);
92//!                 }
93//!             }
94//!             QueryState::Failed(error) => {
95//!                 ui.label(format!("Couldn't load the todos: {error}"));
96//!             }
97//!         }
98//!
99//!         ui.horizontal(|ui| {
100//!             ui.text_edit_singleline(&mut self.title);
101//!             if ui.add_enabled(!self.add.is_pending(), egui::Button::new("Add")).clicked() {
102//!                 let api = self.api.clone();
103//!                 let title = core::mem::take(&mut self.title);
104//!                 self.add.run(async move { api.add_todo(title).await });
105//!             }
106//!         });
107//!         if let Some(error) = self.add.error() {
108//!             ui.label(&*error);
109//!         }
110//!     }
111//! }
112//! ```
113//!
114//! When the `POST` succeeds, the command invalidates `"todos"`, the query refetches, and the
115//! list shows the new todo. Nothing else has to tell the list that it changed.
116//!
117//! # Keys, dependencies and refreshes
118//!
119//! They answer different questions:
120//!
121//! | | Answers | Set with |
122//! |---|---|---|
123//! | key | *Which* data is this? Queries with the same key are the same data. | [`Query::key`] |
124//! | dependency | *When* is it outdated? It refetches when one of its dependencies is invalidated. | [`Query::depends`], [`Page::depends`] |
125//! | refresh | *What* did a mutation change? The dependencies it invalidates when it succeeds. | [`Command::refreshes`] |
126//!
127//! A **key** identifies a query's value in the cache. Queries with the same key (and value and
128//! error types) share one state: they fetch once for all of them, and a query created later
129//! finds the value right away, e.g. when a page is opened again. So the key must contain
130//! everything the fetch depends on: `("user", id)`, not `"user"`. A query without a key has a
131//! value of its own, which is dropped with it.
132//!
133//! A **dependency** is a name for some data on the backend, like `"todos"` or `"users"`. It is
134//! the same kind of name as a load's [`Page::depends`]: a single invalidation reruns the loads
135//! and refetches the queries that depend on it, so many queries can depend on one name, and a
136//! query can depend on several. Dependencies are coarser than keys: `("user", 1)` and
137//! `("user", 2)` are two keys that both depend on `"users"`.
138//!
139//! A **refresh** invalidates a dependency once a command succeeded: the command says what it
140//! changed, and doesn't need to know who shows it. Invalidating a dependency directly does the
141//! same, with [`Nav::invalidate`] in a view, or with [`invalidate`] from anywhere on the UI
142//! thread.
143//!
144//! ```
145//! # use egui_kit::remote::{self, Command, Query};
146//! # #[derive(Clone)]
147//! # struct Api;
148//! # impl Api {
149//! #     async fn user(&self, _id: u32) -> Result<String, String> { Ok("Ferris".into()) }
150//! #     async fn rename(&self, _id: u32, _name: String) -> Result<(), String> { Ok(()) }
151//! # }
152//! fn user(api: &Api, id: u32) -> Query<String, String> {
153//!     let api = api.clone();
154//!     remote::query(move || {
155//!         let api = api.clone();
156//!         async move { api.user(id).await }
157//!     })
158//!     .key(("user", id)) // one cache entry per user
159//!     .depends("users") // refetched when any user changes
160//! }
161//!
162//! fn rename(api: &Api, rename: &Command<(), String>, id: u32, name: String) {
163//!     let api = api.clone();
164//!     // `rename` was created with `remote::command().refreshes("users")`: once it succeeded,
165//!     // every user query refetches, and so do the loads with `.depends("users")`.
166//!     rename.run(async move { api.rename(id, name).await });
167//! }
168//! ```
169//!
170//! The [`RouterApp`] applies invalidations at its next frame. A query that is invalidated keeps
171//! its value, and refetches the next time it is read.
172//!
173//! # Runtimes
174//!
175//! Natively, queries and commands run on a Tokio runtime, so their futures must be `Send` (see
176//! [`MaybeSend`]). It is the one the app entered if any (a multi-threaded one, as nothing drives
177//! a current-thread runtime between frames), else one that egui-kit starts. [`RouterApp::ui`]
178//! enters it too, so that hooks and loads can use Tokio-based clients like `reqwest`. On the
179//! web, futures run on the browser's event loop and needn't be `Send`.
180//!
181//! A query or command wakes egui up when it finishes, once a [`RouterApp`] drew a frame on
182//! this thread. Its result is picked up when it is read.
183//!
184//! # Caching
185//!
186//! A query fetches on its first read, and keeps its value while it refetches. A keyed value
187//! outlives its queries for [a while](Query::cache_for), so that a page opened again shows it
188//! right away. A query reading a cached value for the first time refetches it if it is [older
189//! than `stale_after`](Query::stale_after), showing the cached value meanwhile.
190//!
191//! Dropping a query's state (its last clone, and its cache entry if keyed) aborts its fetch,
192//! like refreshing it aborts the one in progress. Commands always run to completion.
193//!
194//! [`RouterApp`]: crate::RouterApp
195//! [`RouterApp::ui`]: crate::RouterApp::ui
196//! [`Page::depends`]: crate::page::Page::depends
197//! [`Nav::invalidate`]: crate::extract::Nav::invalidate
198
199mod command;
200mod query;
201mod runtime;
202
203use core::any::{Any, TypeId};
204use core::cell::RefCell;
205use core::time::Duration;
206use std::collections::HashMap;
207use std::rc::{Rc, Weak};
208use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
209
210use egui::Id;
211use web_time::Instant;
212
213pub use command::{Command, command};
214pub use query::{Query, QueryState, query};
215pub use runtime::MaybeSend;
216pub(crate) use runtime::enter;
217
218use crate::load::Invalidation;
219
220/// A query's state, as the registry sees it.
221trait Entry {
222    /// Marks it for a refetch if `invalidation` hits what it depends on.
223    fn invalidate(&self, invalidation: &Invalidation);
224
225    /// Whether a cache entry no query uses should be dropped.
226    fn expired(&self, now: Instant) -> bool;
227
228    fn as_any(self: Rc<Self>) -> Rc<dyn Any>;
229}
230
231/// The queries and commands of this thread.
232#[derive(Default)]
233struct Registry {
234    /// Every query's state, to invalidate them.
235    entries: Vec<Weak<dyn Entry>>,
236    /// The state of keyed queries, by value type and key.
237    cache: HashMap<(TypeId, Id), Rc<dyn Entry>>,
238    /// The app's context, to wake it up when a query or command finished.
239    ctx: Option<egui::Context>,
240    /// Keys to invalidate, from [`invalidate`] and from the commands that succeeded.
241    invalidated: Arc<Mutex<Vec<String>>>,
242}
243
244thread_local! {
245    static REGISTRY: RefCell<Registry> = RefCell::default();
246}
247
248fn with_registry<R>(f: impl FnOnce(&mut Registry) -> R) -> R {
249    REGISTRY.with(|registry| f(&mut registry.borrow_mut()))
250}
251
252fn context() -> Option<egui::Context> {
253    with_registry(|registry| registry.ctx.clone())
254}
255
256fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
257    mutex.lock().unwrap_or_else(PoisonError::into_inner)
258}
259
260/// Pushes `keys` to the invalidations and wakes the app up.
261fn push_invalidated(
262    invalidated: &Mutex<Vec<String>>,
263    ctx: Option<&egui::Context>,
264    keys: impl IntoIterator<Item = String>,
265) {
266    lock(invalidated).extend(keys);
267    if let Some(ctx) = ctx {
268        ctx.request_repaint();
269    }
270}
271
272/// Reruns the loads and queries that depend on `key`, like
273/// [`Nav::invalidate`](crate::extract::Nav::invalidate), from anywhere on the UI thread. The
274/// router applies it at its next frame.
275pub fn invalidate(key: impl Into<String>) {
276    let (invalidated, ctx) =
277        with_registry(|registry| (Arc::clone(&registry.invalidated), registry.ctx.clone()));
278    push_invalidated(&invalidated, ctx.as_ref(), [key.into()]);
279}
280
281/// Remembers the app's context, at the start of its frame.
282pub(crate) fn begin_frame(ctx: &egui::Context) {
283    with_registry(|registry| registry.ctx = Some(ctx.clone()));
284}
285
286/// The keys [invalidated](invalidate) since the last call.
287pub(crate) fn take_invalidated() -> Vec<String> {
288    let invalidated = with_registry(|registry| Arc::clone(&registry.invalidated));
289    core::mem::take(&mut *lock(&invalidated))
290}
291
292/// Marks the queries that depend on what `invalidation` hits for a refetch.
293pub(crate) fn invalidate_queries(invalidation: &Invalidation) {
294    let entries: Vec<_> = with_registry(|registry| {
295        registry.entries.retain(|entry| entry.strong_count() > 0);
296        registry.entries.iter().filter_map(Weak::upgrade).collect()
297    });
298    for entry in entries {
299        entry.invalidate(invalidation);
300    }
301}
302
303/// Drops the cache entries that no query used for long enough.
304pub(crate) fn end_frame() {
305    let now = Instant::now();
306    // Dropped outside of the registry: dropping a query's state aborts its fetch.
307    let _expired: Vec<_> = with_registry(|registry| {
308        let keys: Vec<_> = registry
309            .cache
310            .iter()
311            .filter(|(_, entry)| Rc::strong_count(entry) == 1 && entry.expired(now))
312            .map(|(key, _)| *key)
313            .collect();
314        keys.into_iter()
315            .filter_map(|key| registry.cache.remove(&key))
316            .collect()
317    });
318}
319
320/// How long a keyed query's value is kept by default once no query uses it.
321const CACHE_FOR: Duration = Duration::from_mins(5);