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