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