Skip to main content

egui_kit/remote/
query.rs

1//! [`Query`]: async data.
2
3use core::any::{Any, TypeId};
4use core::cell::{Cell, Ref, RefCell};
5use core::fmt;
6use core::future::Future;
7use core::hash::Hash;
8use core::time::Duration;
9use std::rc::Rc;
10use std::sync::{Arc, Mutex};
11
12use web_time::Instant;
13
14use super::runtime::{self, Abort, BoxFuture, MaybeSend};
15use super::{
16    CACHE_FOR, Entry, context, hash, lock, request_repaint, shared_context, with_registry,
17};
18use crate::load::Invalidation;
19
20/// Where a fetch puts its result.
21type Slot<T, E> = Arc<Mutex<Option<Result<T, E>>>>;
22
23/// A fetch in progress, aborted when dropped.
24struct Run<T, E> {
25    slot: Slot<T, E>,
26    _task: Abort,
27}
28
29/// The state of a query, shared by its clones and by the queries with the same key.
30struct State<T, E> {
31    value: Option<Rc<T>>,
32    /// Why the last fetch failed.
33    error: Option<Rc<E>>,
34    version: u64,
35    fetched_at: Option<Instant>,
36    run: Option<Run<T, E>>,
37    /// Refetch on the next read.
38    stale: bool,
39    depends: Vec<String>,
40    read_at: Instant,
41    cache_for: Duration,
42}
43
44impl<T: 'static, E: 'static> Entry for RefCell<State<T, E>> {
45    fn invalidate(&self, invalidation: &Invalidation) {
46        let mut state = self.borrow_mut();
47        if invalidation.hits(&state.depends) {
48            state.stale = true;
49            state.run = None;
50        }
51    }
52
53    fn expired(&self, now: Instant) -> bool {
54        let state = self.borrow();
55        now.saturating_duration_since(state.read_at) >= state.cache_for
56    }
57
58    fn as_any(self: Rc<Self>) -> Rc<dyn Any> {
59        self
60    }
61}
62
63/// What a [`Query`] has to show.
64#[derive(Debug)]
65pub enum QueryState<T, E> {
66    /// The first fetch is in progress.
67    Loading,
68    /// The last fetch succeeded. A refetch may be in progress, see [`Query::is_fetching`].
69    Ready(Rc<T>),
70    /// The last fetch failed. [`Query::data`] still has the value before, if any.
71    Failed(Rc<E>),
72}
73
74/// Async data: fetches on its first read, then keeps its value until it refetches.
75///
76/// Create one with [`query`], from a function that returns the future to fetch the data: it is
77/// called for every fetch. Keep it where the views can read it (the app state, a
78/// [`PageState`](crate::extract::PageState)…) and read it every frame you show it. Clones share
79/// its state. See the [module docs](crate::remote).
80///
81/// A new query fetches on its first read, so don't make one every frame: for a query made from
82/// inputs that change, keep a [`Live`](super::Live).
83///
84/// ```
85/// # use egui_kit::remote::{self, Query};
86/// # #[derive(Clone)]
87/// # struct Api;
88/// # impl Api { async fn user(&self, _id: u32) -> Result<String, String> { Ok("Ferris".into()) } }
89/// fn user(api: &Api, id: u32) -> Query<String, String> {
90///     let api = api.clone();
91///     remote::query(move || {
92///         let api = api.clone();
93///         async move { api.user(id).await }
94///     })
95///     .key(("user", id))
96/// }
97/// ```
98pub struct Query<T, E> {
99    state: Rc<RefCell<State<T, E>>>,
100    fetch: Rc<dyn Fn() -> BoxFuture<Result<T, E>>>,
101    refetch_every: Option<Duration>,
102    stale_after: Duration,
103    cache_for: Option<Duration>,
104    /// Whether it (or a clone) was read: until then, it refetches a value older than
105    /// `stale_after`.
106    read: Rc<Cell<bool>>,
107}
108
109/// A [`Query`] that fetches with `fetch`.
110pub fn query<T, E, F, Fut>(fetch: F) -> Query<T, E>
111where
112    T: MaybeSend + 'static,
113    E: MaybeSend + 'static,
114    F: Fn() -> Fut + 'static,
115    Fut: Future<Output = Result<T, E>> + MaybeSend + 'static,
116{
117    Query::new(fetch)
118}
119
120impl<T: MaybeSend + 'static, E: MaybeSend + 'static> Query<T, E> {
121    /// See [`query`].
122    pub fn new<F, Fut>(fetch: F) -> Self
123    where
124        F: Fn() -> Fut + 'static,
125        Fut: Future<Output = Result<T, E>> + MaybeSend + 'static,
126    {
127        let state = Rc::new(RefCell::new(State {
128            value: None,
129            error: None,
130            version: 0,
131            fetched_at: None,
132            run: None,
133            stale: false,
134            depends: Vec::new(),
135            read_at: Instant::now(),
136            cache_for: CACHE_FOR,
137        }));
138        let entry: Rc<dyn Entry> = Rc::clone(&state) as _;
139        with_registry(|registry| registry.entries.push(Rc::downgrade(&entry)));
140        Self {
141            state,
142            fetch: Rc::new(move || Box::pin(fetch())),
143            refetch_every: None,
144            stale_after: Duration::ZERO,
145            cache_for: None,
146            read: Rc::default(),
147        }
148    }
149
150    /// Shares the state of the queries with the same key (and value and error types): they
151    /// fetch once for all of them, and the value is [cached](Self::cache_for). The first
152    /// query with a key fetches with its function, the others use its value.
153    ///
154    /// The key identifies the data, so it must contain everything the fetch uses, like
155    /// `("user", id)`. It is only hashed, so it may contain secrets: pass them as they are, not
156    /// as an [`egui::Id`], which keeps their `Debug` text in debug builds. See
157    /// [Keys, dependencies and refreshes](crate::remote#keys-dependencies-and-refreshes).
158    #[must_use]
159    pub fn key(mut self, key: impl Hash) -> Self {
160        let id = (TypeId::of::<(T, E)>(), hash(key));
161        let shared = with_registry(|registry| {
162            if let Some(entry) = registry.cache.get(&id) {
163                return Rc::clone(entry).as_any().downcast().ok();
164            }
165            registry
166                .cache
167                .insert(id, Rc::clone(&self.state) as Rc<dyn Entry>);
168            None
169        });
170        if let Some(shared) = shared {
171            let depends = core::mem::take(&mut self.state.borrow_mut().depends);
172            self.state = shared;
173            for key in depends {
174                self = self.depends(key);
175            }
176        }
177        self.apply_cache_for();
178        self
179    }
180
181    /// Refetches when the dependency `key` is invalidated: with
182    /// [`Nav::invalidate`](crate::extract::Nav::invalidate), [`invalidate`](super::invalidate), or
183    /// by a command that [refreshes](super::Command::refreshes) it. Loads with the same
184    /// [dependency](crate::page::Page::depends) rerun along. Call it once per dependency.
185    ///
186    /// A dependency names data on the backend (`"users"`), unlike the [key](Self::key) that
187    /// names one value (`("user", 1)`). See [Keys, dependencies and refreshes](crate::remote#keys-dependencies-and-refreshes).
188    #[must_use]
189    pub fn depends(self, key: impl Into<String>) -> Self {
190        let key = key.into();
191        let mut state = self.state.borrow_mut();
192        if !state.depends.contains(&key) {
193            state.depends.push(key);
194        }
195        drop(state);
196        self
197    }
198
199    /// Refetches this long after the last fetch finished, for as long as it is read: for data
200    /// that changes elsewhere, like an inbox.
201    #[must_use]
202    pub fn refetch_every(mut self, every: Duration) -> Self {
203        self.refetch_every = Some(every);
204        self
205    }
206
207    /// How old a [cached](Self::key) value may be for this query to use it without refetching,
208    /// when it first reads it. The cached value is shown while it refetches. Zero by default:
209    /// a new query always refetches.
210    #[must_use]
211    pub fn stale_after(mut self, duration: Duration) -> Self {
212        self.stale_after = duration;
213        self
214    }
215
216    /// How long a [keyed](Self::key) value is kept once no query uses it. 5 minutes by default.
217    #[must_use]
218    pub fn cache_for(mut self, duration: Duration) -> Self {
219        self.cache_for = Some(duration);
220        self.apply_cache_for();
221        self
222    }
223
224    fn apply_cache_for(&self) {
225        if let Some(duration) = self.cache_for {
226            self.state.borrow_mut().cache_for = duration;
227        }
228    }
229
230    /// What to show: loading, the value, or why the last fetch failed.
231    pub fn state(&self) -> QueryState<T, E> {
232        let state = self.read();
233        if let Some(error) = &state.error {
234            QueryState::Failed(Rc::clone(error))
235        } else if let Some(value) = &state.value {
236            QueryState::Ready(Rc::clone(value))
237        } else {
238            QueryState::Loading
239        }
240    }
241
242    /// The last value fetched: while it refetches, or if that failed, the previous one.
243    pub fn data(&self) -> Option<Rc<T>> {
244        self.read().value.clone()
245    }
246
247    /// Why the last fetch failed.
248    pub fn error(&self) -> Option<Rc<E>> {
249        self.read().error.clone()
250    }
251
252    /// Whether the first fetch is in progress: there is no [`data`](Self::data) yet.
253    pub fn is_loading(&self) -> bool {
254        let state = self.read();
255        state.value.is_none() && state.run.is_some()
256    }
257
258    /// Whether a fetch is in progress, the first one or a refetch.
259    pub fn is_fetching(&self) -> bool {
260        self.read().run.is_some()
261    }
262
263    /// Identifies the [data](Self::data): it changes whenever a fetch succeeded, so that a view
264    /// can rebuild what it derives from the value only then. `0` while there is no value.
265    pub fn version(&self) -> u64 {
266        self.read().version
267    }
268
269    /// Refetches, aborting the fetch in progress. The value stays until the new one arrives.
270    pub fn refresh(&self) {
271        let mut state = self.state.borrow_mut();
272        state.stale = true;
273        state.run = None;
274        drop(state);
275        if let Some(ctx) = context() {
276            ctx.request_repaint();
277        }
278    }
279
280    /// Replaces the value, e.g. with what a command returned, or optimistically before a
281    /// command confirms it. A fetch in progress still replaces it when done.
282    pub fn set_data(&self, value: T) {
283        let mut state = self.state.borrow_mut();
284        state.value = Some(Rc::new(value));
285        state.error = None;
286        state.version += 1;
287    }
288
289    /// The value and whether the last fetch failed, without reading it: no fetch starts, and a
290    /// cached value isn't kept longer.
291    pub(super) fn peek(&self) -> (Option<Rc<T>>, bool) {
292        let mut state = self.state.borrow_mut();
293        settle(&mut state, Instant::now());
294        (state.value.clone(), state.error.is_some())
295    }
296
297    /// Picks up a finished fetch, and starts one if due.
298    fn read(&self) -> Ref<'_, State<T, E>> {
299        let now = Instant::now();
300        let mut state = self.state.borrow_mut();
301        state.read_at = now;
302        settle(&mut state, now);
303        if state.run.is_none() && self.due(&state, now) {
304            state.stale = false;
305            state.run = Some(self.start());
306        }
307        drop(state);
308        self.read.set(true);
309        self.state.borrow()
310    }
311
312    fn due(&self, state: &State<T, E>, now: Instant) -> bool {
313        let Some(fetched_at) = state.fetched_at else {
314            return true;
315        };
316        let age = now.saturating_duration_since(fetched_at);
317        if state.stale || (!self.read.get() && age >= self.stale_after) {
318            return true;
319        }
320        match self.refetch_every {
321            Some(every) if age >= every => true,
322            Some(every) => {
323                if let Some(ctx) = context() {
324                    ctx.request_repaint_after(every.saturating_sub(age));
325                }
326                false
327            }
328            None => false,
329        }
330    }
331
332    fn start(&self) -> Run<T, E> {
333        let slot: Slot<T, E> = Arc::default();
334        let future = (self.fetch)();
335        let ctx = shared_context();
336        let task = runtime::spawn({
337            let slot = Arc::clone(&slot);
338            async move {
339                let result = future.await;
340                *lock(&slot) = Some(result);
341                request_repaint(&ctx);
342            }
343        });
344        Run { slot, _task: task }
345    }
346}
347
348/// Picks up a finished fetch.
349fn settle<T, E>(state: &mut State<T, E>, now: Instant) {
350    if let Some(result) = state.run.as_ref().and_then(|run| lock(&run.slot).take()) {
351        state.run = None;
352        state.fetched_at = Some(now);
353        match result {
354            Ok(value) => {
355                state.value = Some(Rc::new(value));
356                state.error = None;
357                state.version += 1;
358            }
359            Err(error) => state.error = Some(Rc::new(error)),
360        }
361    }
362}
363
364impl<T, E> Clone for Query<T, E> {
365    fn clone(&self) -> Self {
366        Self {
367            state: Rc::clone(&self.state),
368            fetch: Rc::clone(&self.fetch),
369            refetch_every: self.refetch_every,
370            stale_after: self.stale_after,
371            cache_for: self.cache_for,
372            read: Rc::clone(&self.read),
373        }
374    }
375}
376
377impl<T: fmt::Debug, E: fmt::Debug> fmt::Debug for Query<T, E> {
378    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
379        let state = self.state.borrow();
380        f.debug_struct("Query")
381            .field("value", &state.value)
382            .field("error", &state.error)
383            .field("version", &state.version)
384            .field("fetching", &state.run.is_some())
385            .finish_non_exhaustive()
386    }
387}