1use serde::Serialize;
5use std::{borrow::Cow, fmt, future::Future};
6
7#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub struct CacheKey {
28 name: Cow<'static, str>,
29 args: String,
30}
31
32impl CacheKey {
33 pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
36 Self {
37 name: name.into(),
38 args: String::new(),
39 }
40 }
41
42 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 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 pub fn name(&self) -> &str {
85 &self.name
86 }
87
88 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
100pub(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
119pub trait CacheableFn<Args>: 'static {
135 type Output;
137 type Future: Future<Output = dioxus::Result<Self::Output>> + 'static;
139
140 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}