Skip to main content

hydracache_db/
query.rs

1use std::error::Error;
2use std::fmt;
3use std::future::Future;
4use std::marker::PhantomData;
5use std::time::Duration;
6
7use hydracache::{CacheKeyBuilder, CacheOptions, HydraCache, PostcardCodec, TagSet};
8use hydracache_core::CacheCodec;
9use serde::{de::DeserializeOwned, Serialize};
10
11use crate::{DbCacheError, Result};
12
13/// A database-oriented view over a [`HydraCache`] instance.
14///
15/// `DbCache` groups query result keys under a namespace while keeping all
16/// cache storage, single-flight, tags, TTL, and stats in the shared local cache.
17///
18/// # Example
19///
20/// ```rust
21/// use std::time::Duration;
22///
23/// use hydracache::HydraCache;
24/// use hydracache_db::DbCache;
25/// use serde::{Deserialize, Serialize};
26///
27/// #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28/// struct User {
29///     id: i64,
30///     name: String,
31/// }
32///
33/// # #[tokio::main]
34/// # async fn main() -> hydracache_db::Result<()> {
35/// let local = HydraCache::local().build();
36/// let queries = DbCache::new(local, "db");
37///
38/// let user = queries
39///     .entity::<User>("user", 42)
40///     // Later, invalidate_tag("user:42") removes this result.
41///     .collection_tag("users")
42///     .ttl(Duration::from_secs(60))
43///     .fetch_with(|| async {
44///         // Replace this block with code from sqlx, diesel, sea-orm, or any
45///         // other database client. It is called only when the cache does not
46///         // already contain "db:user:42" or when the cached value has expired.
47///         Ok::<_, std::io::Error>(User {
48///             id: 42,
49///             name: "Ada".to_owned(),
50///         })
51///     })
52///     .await?;
53///
54/// assert_eq!(user.id, 42);
55/// # Ok(())
56/// # }
57/// ```
58pub struct DbCache<C = PostcardCodec>
59where
60    C: CacheCodec,
61{
62    cache: HydraCache<C>,
63    namespace: String,
64}
65
66impl<C> Clone for DbCache<C>
67where
68    C: CacheCodec,
69{
70    fn clone(&self) -> Self {
71        Self {
72            cache: self.cache.clone(),
73            namespace: self.namespace.clone(),
74        }
75    }
76}
77
78impl<C> fmt::Debug for DbCache<C>
79where
80    C: CacheCodec,
81{
82    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
83        formatter
84            .debug_struct("DbCache")
85            .field("namespace", &self.namespace)
86            .finish_non_exhaustive()
87    }
88}
89
90impl<C> DbCache<C>
91where
92    C: CacheCodec,
93{
94    /// Create a database query cache adapter over an existing local cache.
95    pub fn new(cache: HydraCache<C>, namespace: impl Into<String>) -> Self {
96        Self {
97            cache,
98            namespace: namespace.into(),
99        }
100    }
101
102    /// Return the namespace used for physical cache keys.
103    pub fn namespace(&self) -> &str {
104        &self.namespace
105    }
106
107    /// Return the underlying local cache.
108    pub fn cache(&self) -> &HydraCache<C> {
109        &self.cache
110    }
111
112    /// Start describing a cacheable database-loaded value.
113    ///
114    /// This is the preferred entry point when the query is already visible
115    /// inside the `fetch_with` loader through a database client, ORM, or
116    /// repository method.
117    pub fn cached<T>(&self) -> DbQuery<T, C> {
118        DbQuery {
119            cache: self.cache.clone(),
120            namespace: self.namespace.clone(),
121            name: None,
122            key: None,
123            tags: TagSet::new(),
124            ttl: None,
125            value: PhantomData,
126        }
127    }
128
129    /// Start describing an entity-shaped cached value.
130    ///
131    /// This is a convenience layer over [`DbCache::cached`] that sets both the
132    /// logical key and the entity invalidation tag from escaped key segments.
133    /// For example, `entity::<User>("user", 42)` creates key `user:42` and tag
134    /// `user:42`; with namespace `db`, the physical cache key is `db:user:42`.
135    ///
136    /// # Example
137    ///
138    /// ```rust
139    /// use hydracache::HydraCache;
140    /// use hydracache_db::DbCache;
141    /// use serde::{Deserialize, Serialize};
142    ///
143    /// #[derive(Debug, Clone, Serialize, Deserialize)]
144    /// struct User {
145    ///     id: i64,
146    /// }
147    ///
148    /// let queries = DbCache::new(HydraCache::local().build(), "db");
149    /// let query = queries.entity::<User>("user", 42);
150    ///
151    /// assert_eq!(query.key_value(), Some("user:42"));
152    /// assert_eq!(query.tags_value(), &["user:42".to_owned()]);
153    /// assert_eq!(query.physical_key(), Some("db:user:42".to_owned()));
154    /// ```
155    pub fn entity<T>(&self, kind: impl ToString, id: impl ToString) -> DbQuery<T, C> {
156        self.cached::<T>().for_entity(kind, id)
157    }
158
159    /// Start describing a collection-shaped cached value.
160    ///
161    /// This sets both the logical key and the collection invalidation tag to
162    /// the escaped collection name. For example, `collection::<User>("users")`
163    /// creates key `users` and tag `users`.
164    ///
165    /// # Example
166    ///
167    /// ```rust
168    /// use hydracache::HydraCache;
169    /// use hydracache_db::DbCache;
170    /// use serde::{Deserialize, Serialize};
171    ///
172    /// #[derive(Debug, Clone, Serialize, Deserialize)]
173    /// struct User {
174    ///     id: i64,
175    /// }
176    ///
177    /// let queries = DbCache::new(HydraCache::local().build(), "db");
178    /// let query = queries.collection::<User>("users:active");
179    ///
180    /// assert_eq!(query.key_value(), Some("users%3Aactive"));
181    /// assert_eq!(query.tags_value(), &["users%3Aactive".to_owned()]);
182    /// assert_eq!(query.physical_key(), Some("db:users%3Aactive".to_owned()));
183    /// ```
184    pub fn collection<T>(&self, name: impl ToString) -> DbQuery<T, C> {
185        let tag = collection_tag(name);
186        self.cached::<T>().key(tag.clone()).tag(tag)
187    }
188
189    /// Start describing a cacheable database-loaded value with a diagnostic name.
190    pub fn named<T>(&self, name: impl Into<String>) -> DbQuery<T, C> {
191        DbQuery {
192            cache: self.cache.clone(),
193            namespace: self.namespace.clone(),
194            name: Some(name.into()),
195            key: None,
196            tags: TagSet::new(),
197            ttl: None,
198            value: PhantomData,
199        }
200    }
201
202    /// Start describing a cacheable SQL query result.
203    ///
204    /// Prefer [`DbCache::cached`] or [`DbCache::named`] when writing new code.
205    /// This method remains useful if you want the SQL text itself to be the
206    /// diagnostic label for errors and logs.
207    pub fn query_as<T>(&self, sql: impl Into<String>) -> DbQuery<T, C> {
208        self.named(sql)
209    }
210}
211
212/// A cacheable database query descriptor.
213///
214/// The descriptor is deliberately explicit: callers choose the key, tags, and
215/// TTL that match their freshness model. An operation name is optional and used
216/// only for diagnostics. `fetch_with` executes the supplied loader only on a
217/// cache miss.
218pub struct DbQuery<T, C = PostcardCodec>
219where
220    C: CacheCodec,
221{
222    cache: HydraCache<C>,
223    namespace: String,
224    name: Option<String>,
225    key: Option<String>,
226    tags: TagSet,
227    ttl: Option<Duration>,
228    value: PhantomData<fn() -> T>,
229}
230
231impl<T, C> Clone for DbQuery<T, C>
232where
233    C: CacheCodec,
234{
235    fn clone(&self) -> Self {
236        Self {
237            cache: self.cache.clone(),
238            namespace: self.namespace.clone(),
239            name: self.name.clone(),
240            key: self.key.clone(),
241            tags: self.tags.clone(),
242            ttl: self.ttl,
243            value: PhantomData,
244        }
245    }
246}
247
248impl<T, C> fmt::Debug for DbQuery<T, C>
249where
250    C: CacheCodec,
251{
252    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
253        formatter
254            .debug_struct("DbQuery")
255            .field("namespace", &self.namespace)
256            .field("name", &self.name)
257            .field("key", &self.key)
258            .field("tags", &self.tags)
259            .field("ttl", &self.ttl)
260            .finish_non_exhaustive()
261    }
262}
263
264impl<T, C> DbQuery<T, C>
265where
266    C: CacheCodec,
267{
268    /// Return the optional diagnostic operation name.
269    pub fn name(&self) -> Option<&str> {
270        self.name.as_deref()
271    }
272
273    /// Set or replace the diagnostic operation name.
274    pub fn with_name(mut self, name: impl Into<String>) -> Self {
275        self.name = Some(name.into());
276        self
277    }
278
279    /// Return the namespace used for physical cache keys.
280    pub fn namespace(&self) -> &str {
281        &self.namespace
282    }
283
284    /// Return the logical key, if one has been configured.
285    pub fn key_value(&self) -> Option<&str> {
286        self.key.as_deref()
287    }
288
289    /// Return the physical cache key, including the adapter namespace.
290    pub fn physical_key(&self) -> Option<String> {
291        self.key
292            .as_deref()
293            .map(|key| physical_key(&self.namespace, key))
294    }
295
296    /// Return the configured tags.
297    pub fn tags_value(&self) -> &[String] {
298        self.tags.as_slice()
299    }
300
301    /// Return the configured per-entry TTL.
302    pub fn ttl_value(&self) -> Option<Duration> {
303        self.ttl
304    }
305
306    /// Set the logical cache key for this query result.
307    pub fn key(mut self, key: impl Into<String>) -> Self {
308        self.key = Some(key.into());
309        self
310    }
311
312    /// Set the logical cache key from a segmented key builder.
313    pub fn key_builder(self, key: CacheKeyBuilder) -> Self {
314        self.key(key.build_string())
315    }
316
317    /// Set the logical key and add an entity invalidation tag.
318    ///
319    /// `for_entity("user", 42)` sets the key to `user:42` and adds the tag
320    /// `user:42`. Both segments are escaped with [`CacheKeyBuilder`], so `:` and
321    /// `%` inside one segment cannot accidentally create extra key segments.
322    ///
323    /// # Example
324    ///
325    /// ```rust
326    /// use hydracache::HydraCache;
327    /// use hydracache_db::DbCache;
328    /// use serde::{Deserialize, Serialize};
329    ///
330    /// #[derive(Debug, Clone, Serialize, Deserialize)]
331    /// struct User {
332    ///     id: i64,
333    /// }
334    ///
335    /// let queries = DbCache::new(HydraCache::local().build(), "db");
336    /// let query = queries
337    ///     .cached::<User>()
338    ///     .tag("users")
339    ///     .for_entity("user", 42);
340    ///
341    /// assert_eq!(query.key_value(), Some("user:42"));
342    /// assert_eq!(
343    ///     query.tags_value(),
344    ///     &["users".to_owned(), "user:42".to_owned()]
345    /// );
346    /// ```
347    pub fn for_entity(mut self, kind: impl ToString, id: impl ToString) -> Self {
348        let key = entity_key(kind, id);
349        self.key = Some(key.clone());
350        self.tags = self.tags.tag(key);
351        self
352    }
353
354    /// Add one invalidation tag.
355    pub fn tag(mut self, tag: impl Into<String>) -> Self {
356        self.tags = self.tags.tag(tag);
357        self
358    }
359
360    /// Add a collection invalidation tag from one escaped key segment.
361    ///
362    /// Use this with [`DbCache::entity`] or [`DbQuery::for_entity`] when one
363    /// entity result also belongs to a broader list or query group.
364    ///
365    /// # Example
366    ///
367    /// ```rust
368    /// use hydracache::HydraCache;
369    /// use hydracache_db::DbCache;
370    /// use serde::{Deserialize, Serialize};
371    ///
372    /// #[derive(Debug, Clone, Serialize, Deserialize)]
373    /// struct User {
374    ///     id: i64,
375    /// }
376    ///
377    /// let queries = DbCache::new(HydraCache::local().build(), "db");
378    /// let query = queries
379    ///     .entity::<User>("user", 42)
380    ///     .collection_tag("users:active");
381    ///
382    /// assert_eq!(
383    ///     query.tags_value(),
384    ///     &["user:42".to_owned(), "users%3Aactive".to_owned()]
385    /// );
386    /// ```
387    pub fn collection_tag(mut self, name: impl ToString) -> Self {
388        self.tags = self.tags.tag(collection_tag(name));
389        self
390    }
391
392    /// Add several invalidation tags.
393    pub fn tags<I, S>(mut self, tags: I) -> Self
394    where
395        I: IntoIterator<Item = S>,
396        S: Into<String>,
397    {
398        self.tags = self.tags.tags(tags);
399        self
400    }
401
402    /// Replace invalidation tags from a reusable [`TagSet`].
403    pub fn tag_set(mut self, tags: TagSet) -> Self {
404        self.tags = tags;
405        self
406    }
407
408    /// Set a per-entry TTL for this query result.
409    pub fn ttl(mut self, ttl: Duration) -> Self {
410        self.ttl = Some(ttl);
411        self
412    }
413
414    /// Fetch a cached value or run the supplied database loader on miss.
415    ///
416    /// The loader is intentionally caller-supplied so the database library
417    /// remains responsible for pools, transactions, compile-time checked
418    /// queries, and row mapping. HydraCache owns only the cache boundary.
419    pub async fn fetch_with<E, F, Fut>(self, loader: F) -> Result<T>
420    where
421        T: Serialize + DeserializeOwned + Send + 'static,
422        E: Error + Send + Sync + 'static,
423        F: FnOnce() -> Fut + Send + 'static,
424        Fut: Future<Output = std::result::Result<T, E>> + Send + 'static,
425    {
426        self.fetch_value_with(loader).await
427    }
428
429    /// Fetch a cached value with an output type chosen by an adapter.
430    ///
431    /// Most application code should use [`DbQuery::fetch_with`]. This method is
432    /// intended for adapter crates that keep the descriptor type focused on a
433    /// database row while caching shapes such as `Option<T>` or `Vec<T>`.
434    pub async fn fetch_value_with<U, E, F, Fut>(self, loader: F) -> Result<U>
435    where
436        U: Serialize + DeserializeOwned + Send + 'static,
437        E: Error + Send + Sync + 'static,
438        F: FnOnce() -> Fut + Send + 'static,
439        Fut: Future<Output = std::result::Result<U, E>> + Send + 'static,
440    {
441        let Some(key) = self.physical_key() else {
442            return Err(DbCacheError::MissingKey {
443                operation: self.operation_label(),
444            });
445        };
446
447        self.cache
448            .get_or_load(&key, self.options(), loader)
449            .await
450            .map_err(DbCacheError::from)
451    }
452
453    fn options(&self) -> CacheOptions {
454        let mut options = CacheOptions::new().tag_set(self.tags.clone());
455        if let Some(ttl) = self.ttl {
456            options = options.ttl(ttl);
457        }
458        options
459    }
460
461    fn operation_label(&self) -> String {
462        match &self.name {
463            Some(name) => name.clone(),
464            None if self.namespace.is_empty() => "unnamed".to_owned(),
465            None => format!("{}:unnamed", self.namespace),
466        }
467    }
468}
469
470fn entity_key(kind: impl ToString, id: impl ToString) -> String {
471    CacheKeyBuilder::new().entity(kind, id).build_string()
472}
473
474fn collection_tag(name: impl ToString) -> String {
475    CacheKeyBuilder::from_segment(name).build_string()
476}
477
478fn physical_key(namespace: &str, key: &str) -> String {
479    if namespace.is_empty() {
480        key.to_owned()
481    } else {
482        format!("{namespace}:{key}")
483    }
484}