g3_cache/client/hook.rs
1use super::{
2 EPOCH, STALE, config, invalidate_cached_key, now_ms, persist, remember, remembered, restore,
3};
4use crate::{CacheKey, CacheableFn};
5use dioxus::prelude::{
6 CopyValue, ReadableExt, ReadableRef, Result, Signal, WritableExt, use_hook, use_resource,
7 use_signal,
8};
9use serde::{Serialize, de::DeserializeOwned};
10use std::{future::Future, pin::Pin, rc::Rc};
11
12/// Per-read settings for [`use_cached_with`] and [`use_cached_key_with`].
13#[derive(Clone, Copy, Debug)]
14pub struct CacheOptions {
15 persist: bool,
16}
17
18impl Default for CacheOptions {
19 fn default() -> Self {
20 Self { persist: true }
21 }
22}
23
24impl CacheOptions {
25 /// Keeps this read in memory only, never in the persistent store. For
26 /// data that should not sit on the device's disk, or that is worthless
27 /// on a cold start (a one-time token, a live status).
28 pub fn memory_only(mut self) -> Self {
29 self.persist = false;
30 self
31 }
32}
33
34type Fetch<T> = Rc<dyn Fn() -> Pin<Box<dyn Future<Output = Result<T>>>>>;
35
36/// A cached read's current answer, returned by [`use_cached`].
37/// `Copy`, like a signal.
38pub struct Cached<T: 'static> {
39 data: Signal<Option<Result<T>>>,
40 key: Signal<CacheKey>,
41 pending: Signal<bool>,
42}
43
44impl<T> Clone for Cached<T> {
45 fn clone(&self) -> Self {
46 *self
47 }
48}
49
50impl<T> Copy for Cached<T> {}
51
52impl<T: 'static> Cached<T> {
53 /// What to show: `None` until there is something, then a remembered,
54 /// stored or fetched value. `Some(Err(_))` only when a fetch failed and
55 /// there was nothing to show instead; while offline, the last value
56 /// stays.
57 pub fn read(&self) -> ReadableRef<'_, Signal<Option<Result<T>>>> {
58 self.data.read()
59 }
60
61 /// [`read`](Self::read) without subscribing: for an event handler, which
62 /// wants the value now and must not rerender when it changes.
63 pub fn peek(&self) -> ReadableRef<'_, Signal<Option<Result<T>>>> {
64 self.data.peek()
65 }
66
67 /// Refetches now, keeping the current value on screen meanwhile. For a
68 /// pull-to-refresh or a retry button.
69 pub fn refresh(&self) {
70 invalidate_cached_key(&self.key.peek());
71 }
72
73 /// Whether a fetch is in flight, whether or not there is a value on
74 /// screen meanwhile. For a pull-to-refresh spinner, or a "refreshing"
75 /// hint over a list that is already showing.
76 pub fn pending(&self) -> bool {
77 (self.pending)()
78 }
79}
80
81/// Reads a server function through the client cache. **This is the hook to
82/// use for data a screen shows when it opens.**
83///
84/// ```ignore
85/// let media = use_cached(get_media, (id.clone(),));
86/// let bookmarks = use_cached(get_bookmarks, ());
87/// let reviews = use_cached(get_media_reviews, (id.clone(), 0, 21));
88///
89/// match &*media.read() {
90/// Some(Ok(media)) => rsx! { MediaView { media: media.clone() } },
91/// Some(Err(_)) => rsx! { ErrorState {} },
92/// None => rsx! { Loading {} },
93/// }
94/// ```
95///
96/// Pass the function itself and its arguments as a tuple: the pair is the
97/// cache key, so the key always matches what is fetched. When the
98/// arguments change between renders (new props), it reads the new key.
99///
100/// A read is answered, in order, from
101///
102/// 1. memory, for anything fetched this session, then
103/// 2. the persistent store, for anything fetched in an earlier session
104/// (see [`set_cache_owner`](crate::set_cache_owner)), so a cold start shows the last
105/// known data at once, then
106/// 3. the server, every time the screen opens, unless the same read
107/// finished within [`CacheConfig::share_for`](crate::CacheConfig::share_for). Its
108/// answer replaces what was showing.
109///
110/// A mounted screen refetches after [`invalidate_cached`](crate::invalidate_cached) and
111/// when the app regains focus (see [`CacheConfig`](crate::CacheConfig)).
112///
113/// # When not to use it
114///
115/// - **Reads that change with every keystroke** (search boxes, pickers):
116/// use `use_resource`. Every value is thrown away a moment later.
117/// - **Handlers that must see current server state before acting**: call
118/// the server function directly. A cache answers with what it last saw.
119/// - **Closures.** `use_cached(|| get_media(id), ())` panics: see
120/// [`CacheableFn`]. For a read that is not one server function call, use
121/// [`use_cached_key`] with a named key.
122///
123/// On the server (the `server` feature) nothing is cached: every render
124/// fetches.
125pub fn use_cached<F, Args>(server_fn: F, args: Args) -> Cached<F::Output>
126where
127 F: CacheableFn<Args>,
128 Args: Serialize + Clone + 'static,
129 F::Output: Serialize + DeserializeOwned + Clone + PartialEq + 'static,
130{
131 use_cached_with(server_fn, args, CacheOptions::default())
132}
133
134/// [`use_cached`] with per-read [`CacheOptions`].
135pub fn use_cached_with<F, Args>(
136 server_fn: F,
137 args: Args,
138 options: CacheOptions,
139) -> Cached<F::Output>
140where
141 F: CacheableFn<Args>,
142 Args: Serialize + Clone + 'static,
143 F::Output: Serialize + DeserializeOwned + Clone + PartialEq + 'static,
144{
145 let key = CacheKey::of(&server_fn, &args);
146 use_cached_key_with(key, options, move || server_fn.call_with(args.clone()))
147}
148
149/// Reads through the client cache under a key you name. Use it for a read
150/// that is not one server function call: several calls combined, or data
151/// from somewhere else. Prefer [`use_cached`] otherwise.
152///
153/// `key` must name everything `fetch` depends on. A changed key is what
154/// makes it refetch, and two reads with the same key share one entry.
155///
156/// ```ignore
157/// let shelves = use_cached_key(CacheKey::new("home_shelves").with(media_type), move || async move {
158/// let (trending, new) = futures::join!(get_trending(media_type), get_new_releases(media_type));
159/// Ok(Shelves { trending: trending?, new: new? })
160/// });
161/// ```
162///
163/// Invalidate it with [`invalidate_cached_name`](crate::invalidate_cached_name) or
164/// [`invalidate_cached_key`](crate::invalidate_cached_key).
165pub fn use_cached_key<T, F, Fut>(key: CacheKey, fetch: F) -> Cached<T>
166where
167 T: Serialize + DeserializeOwned + Clone + PartialEq + 'static,
168 F: Fn() -> Fut + 'static,
169 Fut: Future<Output = Result<T>> + 'static,
170{
171 use_cached_key_with(key, CacheOptions::default(), fetch)
172}
173
174/// [`use_cached_key`] with per-read [`CacheOptions`].
175pub fn use_cached_key_with<T, F, Fut>(key: CacheKey, options: CacheOptions, fetch: F) -> Cached<T>
176where
177 T: Serialize + DeserializeOwned + Clone + PartialEq + 'static,
178 F: Fn() -> Fut + 'static,
179 Fut: Future<Output = Result<T>> + 'static,
180{
181 let mut data = use_signal(|| remembered::<T>(&key).map(|(value, _)| Ok(value)));
182 let mut current_key = use_signal(|| key.clone());
183 let mut pending = use_signal(|| false);
184 if *current_key.peek() != key {
185 current_key.set(key);
186 }
187
188 // The newest closure, since it captures this render's props.
189 let mut latest = use_hook(|| CopyValue::new(None::<Fetch<T>>));
190 latest.set(Some(Rc::new(move || Box::pin(fetch()))));
191
192 // The key this hook last loaded. A rerun for that same key comes from
193 // `EPOCH`, and refetches only if its entry was invalidated.
194 let mut loaded = use_hook(|| CopyValue::new(None::<CacheKey>));
195
196 use_resource(move || {
197 let key = current_key();
198 let _ = EPOCH();
199 let fetch = latest.peek().clone();
200 async move {
201 let Some(fetch) = fetch else { return };
202 let opening = loaded.peek().as_ref() != Some(&key);
203 match remembered::<T>(&key) {
204 Some((value, fetched_at)) => {
205 show(&mut data, value);
206 let current = if opening {
207 let share_for = i64::try_from(config().share_for.as_millis()).unwrap_or(0);
208 now_ms().saturating_sub(fetched_at) < share_for
209 } else {
210 fetched_at != STALE
211 };
212 if current {
213 loaded.set(Some(key));
214 // A rerun can cancel an earlier one mid-fetch.
215 if *pending.peek() {
216 pending.set(false);
217 }
218 return;
219 }
220 }
221 None => match options.persist.then(|| restore::<T>(&key)) {
222 Some(restoring) => match restoring.await {
223 Some(value) => {
224 remember(&key, value.clone(), STALE);
225 show(&mut data, value);
226 }
227 None => data.set(None),
228 },
229 None => data.set(None),
230 },
231 }
232
233 // Cleared by whichever run finishes last: a rerun cancels this one
234 // mid-fetch, and sets it again itself.
235 pending.set(true);
236 let result = fetch().await;
237 pending.set(false);
238 if *current_key.peek() != key {
239 // The screen moved on to another key while this was in flight.
240 return;
241 }
242 loaded.set(Some(key.clone()));
243 match result {
244 Ok(value) => {
245 remember(&key, value.clone(), now_ms());
246 show(&mut data, value.clone());
247 if options.persist {
248 persist(&key, &value).await;
249 }
250 }
251 // Offline or failing: keep showing what we had, if anything.
252 Err(err) if data.peek().as_ref().is_none_or(Result::is_err) => {
253 data.set(Some(Err(err)));
254 }
255 Err(_) => {}
256 }
257 }
258 });
259
260 Cached {
261 data,
262 key: current_key,
263 pending,
264 }
265}
266
267/// Sets `data` only when `value` differs, so an unchanged refetch doesn't
268/// re-render the screen.
269fn show<T: PartialEq + 'static>(data: &mut Signal<Option<Result<T>>>, value: T) {
270 let unchanged = matches!(&*data.peek(), Some(Ok(current)) if *current == value);
271 if !unchanged {
272 data.set(Some(Ok(value)));
273 }
274}