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