hitbox-backend 0.2.1

Backend trait for asynchronous caching framework in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Trait for composing backends into layered cache hierarchies.
//!
//! The `Compose` trait provides a fluent API for building `CompositionBackend` instances,
//! making it easy to create multi-level cache hierarchies with custom policies.
//!
//! # Examples
//!
//! Basic composition with default policies:
//! ```ignore
//! use hitbox_backend::composition::Compose;
//!
//! let cache = mem_backend.compose(redis_backend, offload);
//! ```
//!
//! Composition with custom policies:
//! ```ignore
//! use hitbox_backend::composition::{Compose, CompositionPolicy};
//! use hitbox_backend::composition::policy::{RaceReadPolicy, SequentialWritePolicy};
//!
//! let policy = CompositionPolicy::new()
//!     .read(RaceReadPolicy::new())
//!     .write(SequentialWritePolicy::new());
//!
//! let cache = mem_backend.compose_with(redis_backend, offload, policy);
//! ```

use super::policy::{CompositionReadPolicy, CompositionWritePolicy};
use super::{CompositionBackend, CompositionPolicy};
use crate::Backend;
use hitbox_core::Offload;

/// Trait for composing backends into layered cache hierarchies.
///
/// This trait is automatically implemented for all types that implement `Backend`,
/// providing a fluent API for creating `CompositionBackend` instances.
///
/// # Examples
///
/// ```ignore
/// use hitbox_backend::composition::Compose;
///
/// // Simple composition with default policies
/// let cache = l1_backend.compose(l2_backend, offload);
///
/// // Composition with custom policies
/// let policy = CompositionPolicy::new()
///     .read(RaceReadPolicy::new())
///     .write(SequentialWritePolicy::new());
///
/// let cache = l1_backend.compose_with(l2_backend, offload, policy);
/// ```
pub trait Compose: Backend + Sized {
    /// Compose this backend with another backend as L2, using default policies.
    ///
    /// This creates a `CompositionBackend` where:
    /// - `self` becomes L1 (first layer, checked first on reads)
    /// - `l2` becomes L2 (second layer, checked if L1 misses)
    ///
    /// Default policies:
    /// - Read: `SequentialReadPolicy` (try L1 first, then L2)
    /// - Write: `OptimisticParallelWritePolicy` (write to both, succeed if ≥1 succeeds)
    /// - Refill: `AlwaysRefill` (always populate L1 after L2 hit)
    ///
    /// # Arguments
    /// * `l2` - The second-layer backend
    /// * `offload` - Offload manager for background tasks
    ///
    /// # Example
    /// ```ignore
    /// use hitbox_backend::composition::Compose;
    /// use hitbox_moka::MokaBackend;
    /// use hitbox_redis::{RedisBackend, ConnectionMode};
    ///
    /// let moka = MokaBackend::builder().max_entries(1000).build();
    /// let redis = RedisBackend::builder()
    ///     .connection(ConnectionMode::single("redis://localhost/"))
    ///     .build()?;
    ///
    /// // Moka as L1, Redis as L2
    /// let cache = moka.compose(redis, offload);
    /// ```
    fn compose<L2, O>(self, l2: L2, offload: O) -> CompositionBackend<Self, L2, O>
    where
        L2: Backend,
        O: Offload<'static>,
    {
        CompositionBackend::new(self, l2, offload)
    }

    /// Compose this backend with another backend as L2, using custom policies.
    ///
    /// This provides full control over read, write, and refill policies.
    ///
    /// # Arguments
    /// * `l2` - The second-layer backend
    /// * `offload` - Offload manager for background tasks
    /// * `policy` - Custom composition policies
    ///
    /// # Example
    /// ```ignore
    /// use hitbox_backend::composition::{Compose, CompositionPolicy};
    /// use hitbox_backend::composition::policy::{RaceReadPolicy, SequentialWritePolicy};
    ///
    /// let policy = CompositionPolicy::new()
    ///     .read(RaceReadPolicy::new())
    ///     .write(SequentialWritePolicy::new());
    ///
    /// let cache = l1.compose_with(l2, offload, policy);
    /// ```
    fn compose_with<L2, O, R, W>(
        self,
        l2: L2,
        offload: O,
        policy: CompositionPolicy<R, W>,
    ) -> CompositionBackend<Self, L2, O, R, W>
    where
        L2: Backend,
        O: Offload<'static>,
        R: CompositionReadPolicy,
        W: CompositionWritePolicy,
    {
        CompositionBackend::new(self, l2, offload).with_policy(policy)
    }
}

// Blanket implementation for all Backend types
impl<T: Backend> Compose for T {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::{Format, JsonFormat};
    use crate::{
        Backend, BackendResult, CacheBackend, CacheKeyFormat, Compressor, DeleteStatus,
        PassthroughCompressor,
    };
    use async_trait::async_trait;
    use chrono::Utc;
    use hitbox_core::{
        BoxContext, CacheContext, CacheKey, CachePolicy, CacheValue, CacheableResponse,
        EntityPolicyConfig, Predicate, Raw,
    };
    use serde::{Deserialize, Serialize};
    use smol_str::SmolStr;
    use std::collections::HashMap;
    use std::future::Future;
    use std::sync::{Arc, Mutex};

    #[cfg(feature = "rkyv_format")]
    use rkyv::{Archive, Serialize as RkyvSerialize};

    /// Test offload that spawns tasks with tokio::spawn
    #[derive(Clone, Debug)]
    struct TestOffload;

    impl Offload<'static> for TestOffload {
        #[allow(deprecated)]
        fn spawn<F>(&self, _kind: impl Into<SmolStr>, future: F)
        where
            F: Future<Output = ()> + Send + 'static,
        {
            tokio::spawn(future);
        }
    }

    #[derive(Clone, Debug)]
    struct TestBackend {
        store: Arc<Mutex<HashMap<CacheKey, CacheValue<Raw>>>>,
    }

    impl TestBackend {
        fn new() -> Self {
            Self {
                store: Arc::new(Mutex::new(HashMap::new())),
            }
        }
    }

    #[async_trait]
    impl Backend for TestBackend {
        async fn read(&self, key: &CacheKey) -> BackendResult<Option<CacheValue<Raw>>> {
            Ok(self.store.lock().unwrap().get(key).cloned())
        }

        async fn write(&self, key: &CacheKey, value: CacheValue<Raw>) -> BackendResult<()> {
            self.store.lock().unwrap().insert(key.clone(), value);
            Ok(())
        }

        async fn remove(&self, key: &CacheKey) -> BackendResult<DeleteStatus> {
            match self.store.lock().unwrap().remove(key) {
                Some(_) => Ok(DeleteStatus::Deleted(1)),
                None => Ok(DeleteStatus::Missing),
            }
        }

        fn value_format(&self) -> &dyn Format {
            &JsonFormat
        }

        fn key_format(&self) -> &CacheKeyFormat {
            &CacheKeyFormat::Bitcode
        }

        fn compressor(&self) -> &dyn Compressor {
            &PassthroughCompressor
        }
    }

    impl CacheBackend for TestBackend {}

    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
    #[cfg_attr(
        feature = "rkyv_format",
        derive(Archive, RkyvSerialize, rkyv::Deserialize)
    )]
    struct CachedData {
        value: String,
    }

    struct MockResponse;

    impl CacheableResponse for MockResponse {
        type Cached = CachedData;
        type Subject = MockResponse;
        type IntoCachedFuture = std::future::Ready<CachePolicy<Self::Cached, Self>>;
        type FromCachedFuture = std::future::Ready<Self>;

        async fn cache_policy<P: Predicate<Subject = Self::Subject> + Send + Sync>(
            self,
            _predicate: P,
            _config: &EntityPolicyConfig,
        ) -> CachePolicy<CacheValue<Self::Cached>, Self> {
            unimplemented!()
        }

        fn into_cached(self) -> Self::IntoCachedFuture {
            unimplemented!()
        }

        fn from_cached(_cached: Self::Cached) -> Self::FromCachedFuture {
            unimplemented!()
        }
    }

    #[tokio::test]
    async fn test_compose_basic() {
        let l1 = TestBackend::new();
        let l2 = TestBackend::new();
        let offload = TestOffload;

        // Use compose trait
        let cache = l1.clone().compose(l2.clone(), offload);

        let key = CacheKey::from_str("test", "key1");
        let value = CacheValue::new(
            CachedData {
                value: "test_value".to_string(),
            },
            Some(Utc::now() + chrono::Duration::seconds(60)),
            None,
        );

        // Write and read
        let mut ctx: BoxContext = CacheContext::default().boxed();
        cache
            .set::<MockResponse>(&key, &value, &mut ctx)
            .await
            .unwrap();

        let mut ctx: BoxContext = CacheContext::default().boxed();
        let result = cache.get::<MockResponse>(&key, &mut ctx).await.unwrap();
        assert_eq!(result.unwrap().data().value, "test_value");

        // Verify both layers have the data
        let mut ctx: BoxContext = CacheContext::default().boxed();
        assert!(
            l1.get::<MockResponse>(&key, &mut ctx)
                .await
                .unwrap()
                .is_some()
        );
        let mut ctx: BoxContext = CacheContext::default().boxed();
        assert!(
            l2.get::<MockResponse>(&key, &mut ctx)
                .await
                .unwrap()
                .is_some()
        );
    }

    #[tokio::test]
    async fn test_compose_with_policy() {
        use super::super::policy::{RaceReadPolicy, RefillPolicy};

        let l1 = TestBackend::new();
        let l2 = TestBackend::new();
        let offload = TestOffload;

        // Use compose_with to specify custom policies
        let policy = CompositionPolicy::new()
            .read(RaceReadPolicy::new())
            .refill(RefillPolicy::Never);

        let cache = l1.clone().compose_with(l2.clone(), offload, policy);

        let key = CacheKey::from_str("test", "key1");
        let value = CacheValue::new(
            CachedData {
                value: "from_l2".to_string(),
            },
            Some(Utc::now() + chrono::Duration::seconds(60)),
            None,
        );

        // Populate only L2
        let mut ctx: BoxContext = CacheContext::default().boxed();
        l2.set::<MockResponse>(&key, &value, &mut ctx)
            .await
            .unwrap();

        // Read through composition (should use RaceReadPolicy)
        let mut ctx: BoxContext = CacheContext::default().boxed();
        let result = cache.get::<MockResponse>(&key, &mut ctx).await.unwrap();
        assert_eq!(result.unwrap().data().value, "from_l2");

        // With NeverRefill, L1 should NOT be populated
        let mut ctx: BoxContext = CacheContext::default().boxed();
        assert!(
            l1.get::<MockResponse>(&key, &mut ctx)
                .await
                .unwrap()
                .is_none()
        );
    }

    #[tokio::test]
    async fn test_compose_nested() {
        // Test that composed backends can be further composed
        let l1 = TestBackend::new();
        let l2 = TestBackend::new();
        let l3 = TestBackend::new();
        let offload = TestOffload;

        // Create L2+L3 composition
        let l2_l3 = l2.clone().compose(l3.clone(), offload.clone());

        // Compose L1 with the (L2+L3) composition
        let cache = l1.clone().compose(l2_l3, offload);

        let key = CacheKey::from_str("test", "nested_key");
        let value = CacheValue::new(
            CachedData {
                value: "nested_value".to_string(),
            },
            Some(Utc::now() + chrono::Duration::seconds(60)),
            None,
        );

        // Write through nested composition
        let mut ctx: BoxContext = CacheContext::default().boxed();
        cache
            .set::<MockResponse>(&key, &value, &mut ctx)
            .await
            .unwrap();

        // All three levels should have the data
        let mut ctx: BoxContext = CacheContext::default().boxed();
        assert!(
            l1.get::<MockResponse>(&key, &mut ctx)
                .await
                .unwrap()
                .is_some()
        );
        let mut ctx: BoxContext = CacheContext::default().boxed();
        assert!(
            l2.get::<MockResponse>(&key, &mut ctx)
                .await
                .unwrap()
                .is_some()
        );
        let mut ctx: BoxContext = CacheContext::default().boxed();
        assert!(
            l3.get::<MockResponse>(&key, &mut ctx)
                .await
                .unwrap()
                .is_some()
        );
    }

    #[tokio::test]
    async fn test_compose_chaining() {
        use super::super::policy::RaceReadPolicy;

        let l1 = TestBackend::new();
        let l2 = TestBackend::new();
        let offload = TestOffload;

        // Test method chaining: compose + builder methods
        let cache = l1
            .clone()
            .compose(l2.clone(), offload)
            .read(RaceReadPolicy::new());

        let key = CacheKey::from_str("test", "chain_key");
        let value = CacheValue::new(
            CachedData {
                value: "chain_value".to_string(),
            },
            Some(Utc::now() + chrono::Duration::seconds(60)),
            None,
        );

        let mut ctx: BoxContext = CacheContext::default().boxed();
        cache
            .set::<MockResponse>(&key, &value, &mut ctx)
            .await
            .unwrap();

        let mut ctx: BoxContext = CacheContext::default().boxed();
        let result = cache.get::<MockResponse>(&key, &mut ctx).await.unwrap();
        assert_eq!(result.unwrap().data().value, "chain_value");
    }
}