Skip to main content

g3_cache/
key.rs

1//! Naming cached reads: [`CacheKey`], and [`CacheableFn`], which lets a server
2//! function stand for its own key.
3
4use serde::Serialize;
5use std::{borrow::Cow, fmt, future::Future};
6
7/// Names one cached read: a `name` for what is read, plus the arguments its
8/// answer depends on.
9///
10/// You rarely build one yourself. [`use_cached`](crate::use_cached)
11/// and [`invalidate_cached`](crate::invalidate_cached) derive it from the server function
12/// and its arguments, so the key cannot miss an argument. Build one by hand
13/// only for a read that is not a single server function call, for
14/// [`use_cached_key`](crate::use_cached_key):
15///
16/// ```
17/// use g3_cache::CacheKey;
18///
19/// let key = CacheKey::new("home_shelves").with("movie").with(3);
20/// assert_eq!(key.name(), "home_shelves");
21/// ```
22///
23/// [`invalidate_cached_name`](crate::invalidate_cached_name) matches every key with a
24/// given name; [`invalidate_cached_key`](crate::invalidate_cached_key) matches one key
25/// exactly.
26#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct CacheKey {
28    name: Cow<'static, str>,
29    args: String,
30}
31
32impl CacheKey {
33    /// A key with no arguments yet. Add each thing the read depends on with
34    /// [`with`](Self::with).
35    pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
36        Self {
37            name: name.into(),
38            args: String::new(),
39        }
40    }
41
42    /// Adds an argument the read depends on. Any `Serialize` value works;
43    /// it is stored as JSON.
44    ///
45    /// # Panics
46    ///
47    /// If `part` cannot be serialized to JSON (a map with non-string keys,
48    /// for example). That is a bug in the key, not a runtime condition.
49    pub fn with(mut self, part: impl Serialize) -> Self {
50        let json = serde_json::to_string(&part)
51            .unwrap_or_else(|err| panic!("g3-cache: a key argument must serialize to JSON: {err}"));
52        if !self.args.is_empty() {
53            self.args.push(',');
54        }
55        self.args.push_str(&json);
56        self
57    }
58
59    /// The key for calling `server_fn` with `args`: the function's path, and
60    /// the arguments as JSON. Arguments are a tuple, as for
61    /// [`use_cached`](crate::use_cached): `()`, `(id,)`,
62    /// `(id, page)`.
63    ///
64    /// # Panics
65    ///
66    /// If `server_fn` is a closure; see [`CacheableFn`].
67    pub fn of<F, Args>(server_fn: &F, args: &Args) -> Self
68    where
69        F: CacheableFn<Args>,
70        Args: Serialize,
71    {
72        let _ = server_fn;
73        let args = serde_json::to_string(args).unwrap_or_else(|err| {
74            panic!("g3-cache: server function arguments must serialize to JSON: {err}")
75        });
76        Self {
77            name: Cow::Borrowed(fn_name::<F>()),
78            args,
79        }
80    }
81
82    /// What is read: the server function's path, or the name given to
83    /// [`new`](Self::new).
84    pub fn name(&self) -> &str {
85        &self.name
86    }
87
88    /// The single string the persistent store files this key under.
89    pub(crate) fn storage_key(&self) -> String {
90        format!("{}\u{1f}{}", self.name, self.args)
91    }
92}
93
94impl fmt::Debug for CacheKey {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        write!(f, "CacheKey({}({}))", self.name, self.args)
97    }
98}
99
100/// The name of a server function item, used as its cache key's name.
101///
102/// A function item's type name is its path (`my_app::db::get_media`), which
103/// is unique and stable for a build. A closure's is not: every closure in a
104/// module shares `{{closure}}` names that say nothing of what it fetches,
105/// so two different closures could read each other's cached answers. They
106/// are refused, loudly, the first time they are used.
107pub(crate) fn fn_name<F>() -> &'static str {
108    let name = std::any::type_name::<F>();
109    assert!(
110        !name.contains("{{closure}}"),
111        "g3-cache: `{name}` is a closure. Pass the server function itself, with its \
112         arguments as a tuple: `use_cached(get_media, (id,))`, not \
113         `use_cached(|| get_media(id), ())`. For a read that is not one \
114         server function call, use `use_cached_key` with a `CacheKey`."
115    );
116    name
117}
118
119/// A server function (or any `async fn` returning `dioxus::Result`) that can
120/// be passed by name to [`use_cached`](crate::use_cached) and
121/// [`invalidate_cached`](crate::invalidate_cached).
122///
123/// Implemented for functions of up to eight arguments. `Args` is the
124/// arguments as a tuple, which Rust infers from the function:
125///
126/// ```ignore
127/// async fn get_bookmarks() -> dioxus::Result<Vec<Media>>;          // Args = ()
128/// async fn get_media(id: String) -> dioxus::Result<Media>;          // Args = (String,)
129/// async fn get_reviews(id: String, page: u32) -> dioxus::Result<_>; // Args = (String, u32)
130/// ```
131///
132/// Only pass function *items*. A closure compiles, but panics on first use:
133/// its type name cannot tell two different reads apart.
134pub trait CacheableFn<Args>: 'static {
135    /// The `Ok` value.
136    type Output;
137    /// The future the function returns.
138    type Future: Future<Output = dioxus::Result<Self::Output>> + 'static;
139
140    /// Calls the function with its arguments as a tuple.
141    fn call_with(&self, args: Args) -> Self::Future;
142}
143
144macro_rules! impl_server_fn {
145    ($($arg:ident),*) => {
146        impl<F, Fut, T, $($arg),*> CacheableFn<($($arg,)*)> for F
147        where
148            F: Fn($($arg),*) -> Fut + 'static,
149            Fut: Future<Output = dioxus::Result<T>> + 'static,
150        {
151            type Output = T;
152            type Future = Fut;
153
154            #[allow(non_snake_case)]
155            fn call_with(&self, ($($arg,)*): ($($arg,)*)) -> Fut {
156                (self)($($arg),*)
157            }
158        }
159    };
160}
161
162impl_server_fn!();
163impl_server_fn!(A);
164impl_server_fn!(A, B);
165impl_server_fn!(A, B, C);
166impl_server_fn!(A, B, C, D);
167impl_server_fn!(A, B, C, D, E);
168impl_server_fn!(A, B, C, D, E, G);
169impl_server_fn!(A, B, C, D, E, G, H);
170impl_server_fn!(A, B, C, D, E, G, H, I);
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    async fn get_bookmarks() -> dioxus::Result<Vec<u8>> {
177        Ok(vec![])
178    }
179
180    async fn get_media(_id: String) -> dioxus::Result<u8> {
181        Ok(1)
182    }
183
184    async fn get_reviews(_id: String, _offset: u32, _limit: u32) -> dioxus::Result<u8> {
185        Ok(1)
186    }
187
188    #[test]
189    fn server_fns_name_their_own_keys() {
190        let key = CacheKey::of(&get_bookmarks, &());
191        assert!(key.name().ends_with("tests::get_bookmarks"));
192
193        let a = CacheKey::of(&get_media, &("tt1".to_string(),));
194        let b = CacheKey::of(&get_media, &("tt2".to_string(),));
195        assert_eq!(a.name(), b.name());
196        assert_ne!(a, b);
197
198        let reviews = CacheKey::of(&get_reviews, &("tt1".to_string(), 0, 21));
199        assert_eq!(reviews.args, r#"["tt1",0,21]"#);
200    }
201
202    #[test]
203    fn different_functions_never_share_a_key() {
204        let media = CacheKey::of(&get_media, &("tt1".to_string(),));
205        let reviews = CacheKey::of(&get_reviews, &("tt1".to_string(), 0, 21));
206        assert_ne!(media.name(), reviews.name());
207    }
208
209    #[test]
210    #[should_panic(expected = "is a closure")]
211    fn closures_are_refused() {
212        let id = "tt1".to_string();
213        let closure = move || get_media(id.clone());
214        let _ = CacheKey::of(&closure, &());
215    }
216
217    #[test]
218    fn hand_built_keys_add_arguments_in_order() {
219        let key = CacheKey::new("shelf").with("movie").with(Some(3));
220        assert_eq!(key.args, r#""movie",3"#);
221        assert_ne!(key, CacheKey::new("shelf").with(Some(3)).with("movie"));
222    }
223}