kutil_http/cache/
tiered.rs

1use super::{cache::*, key::*, response::*};
2
3//
4// TieredCache
5//
6
7/// Two-tiered [Cache].
8///
9/// The assumption is that the first cache is faster than the next.
10///
11/// For more tiers you can chain this type.
12#[derive(Clone, Debug)]
13pub struct TieredCache<FirstCacheT, NextCacheT> {
14    /// First cache.
15    pub first: FirstCacheT,
16
17    /// Next cache.
18    pub next: NextCacheT,
19}
20
21impl<FirstCacheT, NextCacheT> TieredCache<FirstCacheT, NextCacheT> {
22    /// Constructor.
23    pub fn new(first: FirstCacheT, next: NextCacheT) -> Self {
24        Self { first, next }
25    }
26}
27
28impl<CacheKeyT, FirstCacheT, NextCacheT> Cache<CacheKeyT> for TieredCache<FirstCacheT, NextCacheT>
29where
30    CacheKeyT: CacheKey,
31    FirstCacheT: Cache<CacheKeyT>,
32    NextCacheT: Cache<CacheKeyT>,
33{
34    async fn get(&self, key: &CacheKeyT) -> Option<CachedResponseRef> {
35        match self.first.get(key).await {
36            Some(cached_response) => Some(cached_response),
37            None => self.next.get(key).await,
38        }
39    }
40
41    async fn put(&self, key: CacheKeyT, cached_response: CachedResponseRef) {
42        self.first.put(key.clone(), cached_response.clone()).await;
43        self.next.put(key, cached_response).await
44    }
45
46    async fn invalidate(&self, key: &CacheKeyT) {
47        self.first.invalidate(key).await;
48        self.next.invalidate(key).await
49    }
50
51    async fn invalidate_all(&self) {
52        self.first.invalidate_all().await;
53        self.next.invalidate_all().await
54    }
55}