cache-kit 0.9.0

A type-safe, fully generic, production-ready caching framework for 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Integration tests for cache serialization with real backends.
//!
//! These tests verify that the Postcard serialization with versioned envelopes
//! works correctly across different cache backends (InMemory, Redis, Memcached).

use cache_kit::backend::{CacheBackend, InMemoryBackend};
use cache_kit::feed::GenericFeeder;
use cache_kit::repository::InMemoryRepository;
use cache_kit::serialization::{
    deserialize_from_cache, serialize_for_cache, CACHE_MAGIC, CURRENT_SCHEMA_VERSION,
};
use cache_kit::{CacheEntity, CacheExpander, CacheStrategy};
use serde::{Deserialize, Serialize};

// ============================================================================
// Test Entities
// ============================================================================

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
struct User {
    id: u64,
    name: String,
    email: String,
    active: bool,
}

impl CacheEntity for User {
    type Key = u64;

    fn cache_key(&self) -> Self::Key {
        self.id
    }

    fn cache_prefix() -> &'static str {
        "user"
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
struct Product {
    id: String,
    name: String,
    price: f64,
    in_stock: bool,
}

impl CacheEntity for Product {
    type Key = String;

    fn cache_key(&self) -> Self::Key {
        self.id.clone()
    }

    fn cache_prefix() -> &'static str {
        "product"
    }
}

// ============================================================================
// InMemory Backend Tests
// ============================================================================

#[tokio::test]
async fn test_inmemory_backend_postcard_roundtrip() {
    let backend = InMemoryBackend::new();
    let expander = CacheExpander::new(backend.clone());

    // Setup repository with test data
    let mut repo = InMemoryRepository::new();
    let user = User {
        id: 1,
        name: "Alice".to_string(),
        email: "alice@example.com".to_string(),
        active: true,
    };
    repo.insert(user.id, user.clone());

    // First call: cache miss -> DB hit -> cache populated
    let mut feeder = GenericFeeder::new(1u64);
    expander
        .with::<User, _, _>(&mut feeder, &repo, CacheStrategy::Refresh)
        .await
        .unwrap();

    assert_eq!(feeder.data, Some(user.clone()));

    // Second call: cache hit
    let mut feeder2 = GenericFeeder::new(1u64);
    expander
        .with::<User, _, _>(&mut feeder2, &repo, CacheStrategy::Fresh)
        .await
        .unwrap();

    assert_eq!(feeder2.data, Some(user));
}

#[tokio::test]
async fn test_inmemory_backend_multiple_entities() {
    let backend = InMemoryBackend::new();
    let expander = CacheExpander::new(backend.clone());

    let mut repo = InMemoryRepository::new();

    let user1 = User {
        id: 1,
        name: "Alice".to_string(),
        email: "alice@example.com".to_string(),
        active: true,
    };

    let user2 = User {
        id: 2,
        name: "Bob".to_string(),
        email: "bob@example.com".to_string(),
        active: false,
    };

    repo.insert(user1.id, user1.clone());
    repo.insert(user2.id, user2.clone());

    // Cache both users
    let mut feeder1 = GenericFeeder::new(1u64);
    expander
        .with::<User, _, _>(&mut feeder1, &repo, CacheStrategy::Refresh)
        .await
        .unwrap();

    let mut feeder2 = GenericFeeder::new(2u64);
    expander
        .with::<User, _, _>(&mut feeder2, &repo, CacheStrategy::Refresh)
        .await
        .unwrap();

    assert_eq!(feeder1.data, Some(user1));
    assert_eq!(feeder2.data, Some(user2));
}

#[tokio::test]
async fn test_inmemory_backend_different_entity_types() {
    let backend = InMemoryBackend::new();
    let expander = CacheExpander::new(backend.clone());

    let mut user_repo = InMemoryRepository::new();
    let mut product_repo = InMemoryRepository::new();

    let user = User {
        id: 1,
        name: "Alice".to_string(),
        email: "alice@example.com".to_string(),
        active: true,
    };

    let product = Product {
        id: "prod_123".to_string(),
        name: "Widget".to_string(),
        price: 99.99,
        in_stock: true,
    };

    user_repo.insert(user.id, user.clone());
    product_repo.insert(product.id.clone(), product.clone());

    // Cache different entity types
    let mut user_feeder = GenericFeeder::new(1u64);
    expander
        .with::<User, _, _>(&mut user_feeder, &user_repo, CacheStrategy::Refresh)
        .await
        .unwrap();

    let mut product_feeder = GenericFeeder::new("prod_123".to_string());
    expander
        .with::<Product, _, _>(&mut product_feeder, &product_repo, CacheStrategy::Refresh)
        .await
        .unwrap();

    assert_eq!(user_feeder.data, Some(user));
    assert_eq!(product_feeder.data, Some(product));
}

#[tokio::test]
async fn test_inmemory_backend_cache_miss() {
    let backend = InMemoryBackend::new();
    let expander = CacheExpander::new(backend);

    let repo: InMemoryRepository<User> = InMemoryRepository::new();

    // Try to get non-existent user
    let mut feeder = GenericFeeder::new(999u64);
    expander
        .with::<User, _, _>(&mut feeder, &repo, CacheStrategy::Fresh)
        .await
        .unwrap();

    assert_eq!(feeder.data, None);
}

// ============================================================================
// Direct Serialization Tests (Backend-agnostic)
// ============================================================================

#[tokio::test]
async fn test_direct_serialization_envelope_format() {
    let user = User {
        id: 42,
        name: "Test User".to_string(),
        email: "test@example.com".to_string(),
        active: true,
    };

    // Serialize
    let bytes = serialize_for_cache(&user).unwrap();

    // Verify envelope structure
    assert!(
        bytes.len() > 8,
        "Envelope should be at least 8 bytes (magic + version)"
    );

    // Verify magic
    let magic: [u8; 4] = bytes[0..4].try_into().unwrap();
    assert_eq!(magic, CACHE_MAGIC);

    // Verify version by deserializing envelope (postcard uses variable-length encoding)
    use cache_kit::serialization::CacheEnvelope;
    let envelope: CacheEnvelope<User> = postcard::from_bytes(&bytes).unwrap();
    assert_eq!(envelope.version, CURRENT_SCHEMA_VERSION);

    // Verify roundtrip
    let deserialized: User = deserialize_from_cache(&bytes).unwrap();
    assert_eq!(deserialized, user);
}

#[tokio::test]
async fn test_serialization_consistency_across_calls() {
    let user = User {
        id: 100,
        name: "Consistent User".to_string(),
        email: "consistent@example.com".to_string(),
        active: true,
    };

    // Serialize multiple times
    let bytes1 = serialize_for_cache(&user).unwrap();
    let bytes2 = serialize_for_cache(&user).unwrap();
    let bytes3 = serialize_for_cache(&user).unwrap();

    // All should be identical (deterministic)
    assert_eq!(bytes1, bytes2);
    assert_eq!(bytes2, bytes3);
}

#[tokio::test]
async fn test_serialization_size_comparison_with_json() {
    let user = User {
        id: 1,
        name: "Size Test User".to_string(),
        email: "size@example.com".to_string(),
        active: true,
    };

    // Postcard with envelope
    let postcard_bytes = serialize_for_cache(&user).unwrap();

    // JSON (for comparison)
    let json_bytes = serde_json::to_vec(&user).unwrap();

    // Postcard should be smaller or similar size
    // (With envelope overhead, might be close, but typically still smaller)
    println!("Postcard size: {} bytes", postcard_bytes.len());
    println!("JSON size: {} bytes", json_bytes.len());

    // For this small struct, Postcard should be competitive
    assert!(
        postcard_bytes.len() < json_bytes.len() * 2,
        "Postcard should not be more than 2x larger than JSON"
    );
}

#[tokio::test]
async fn test_serialization_complex_data() {
    #[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
    struct ComplexEntity {
        id: u64,
        name: String,
        tags: Vec<String>,
        metadata: std::collections::HashMap<String, String>,
        score: f64,
        active: bool,
    }

    impl CacheEntity for ComplexEntity {
        type Key = u64;
        fn cache_key(&self) -> Self::Key {
            self.id
        }
        fn cache_prefix() -> &'static str {
            "complex"
        }
    }

    let mut metadata = std::collections::HashMap::new();
    metadata.insert("key1".to_string(), "value1".to_string());
    metadata.insert("key2".to_string(), "value2".to_string());

    let entity = ComplexEntity {
        id: 1,
        name: "Complex Entity".to_string(),
        tags: vec!["tag1".to_string(), "tag2".to_string(), "tag3".to_string()],
        metadata,
        score: 95.5,
        active: true,
    };

    // Roundtrip through serialization
    let bytes = serialize_for_cache(&entity).unwrap();
    let deserialized: ComplexEntity = deserialize_from_cache(&bytes).unwrap();

    assert_eq!(deserialized, entity);
}

// ============================================================================
// Cache Backend Integration Tests
// ============================================================================

#[tokio::test]
async fn test_backend_raw_bytes_validation() {
    let backend = InMemoryBackend::new();

    let user = User {
        id: 1,
        name: "Raw Test".to_string(),
        email: "raw@example.com".to_string(),
        active: true,
    };

    // Serialize user
    let bytes = serialize_for_cache(&user).unwrap();

    // Store raw bytes in backend
    let key = format!("{}:{}", User::cache_prefix(), user.cache_key());
    backend.set(&key, bytes.clone(), None).await.unwrap();

    // Retrieve raw bytes
    let retrieved_bytes = backend.get(&key).await.unwrap().expect("Should find entry");

    // Verify envelope in raw bytes
    assert_eq!(&retrieved_bytes[0..4], b"CKIT");

    // Deserialize
    let deserialized: User = deserialize_from_cache(&retrieved_bytes).unwrap();
    assert_eq!(deserialized, user);
}

#[tokio::test]
async fn test_backend_stores_postcard_not_json() {
    let backend = InMemoryBackend::new();
    let expander = CacheExpander::new(backend.clone());

    let user = User {
        id: 1,
        name: "Format Test".to_string(),
        email: "format@example.com".to_string(),
        active: true,
    };

    // Use expander to cache user
    let mut repo = InMemoryRepository::new();
    repo.insert(user.id, user.clone());

    let mut feeder = GenericFeeder::new(1u64);
    expander
        .with::<User, _, _>(&mut feeder, &repo, CacheStrategy::Refresh)
        .await
        .unwrap();

    // Get raw bytes from backend
    let key = format!("{}:{}", User::cache_prefix(), user.cache_key());
    let raw_bytes = backend.get(&key).await.unwrap().expect("Should find entry");

    // Verify it's NOT JSON (should start with CKIT magic, not '{')
    assert_eq!(&raw_bytes[0..4], b"CKIT");
    assert_ne!(raw_bytes[0], b'{'); // NOT JSON

    // Verify it IS valid Postcard with envelope
    let deserialized: User = deserialize_from_cache(&raw_bytes).unwrap();
    assert_eq!(deserialized, user);
}

// ============================================================================
// Edge Cases and Error Handling
// ============================================================================

#[tokio::test]
async fn test_empty_string_fields() {
    let user = User {
        id: 1,
        name: String::new(),
        email: String::new(),
        active: false,
    };

    let bytes = serialize_for_cache(&user).unwrap();
    let deserialized: User = deserialize_from_cache(&bytes).unwrap();

    assert_eq!(deserialized, user);
}

#[tokio::test]
async fn test_large_string_fields() {
    let user = User {
        id: 1,
        name: "x".repeat(10000),
        email: "y".repeat(5000),
        active: true,
    };

    let bytes = serialize_for_cache(&user).unwrap();
    let deserialized: User = deserialize_from_cache(&bytes).unwrap();

    assert_eq!(deserialized, user);
}

#[tokio::test]
async fn test_special_characters_in_strings() {
    let user = User {
        id: 1,
        name: "User with émojis 🎉 and spëcial çhars".to_string(),
        email: "test+tag@example.com".to_string(),
        active: true,
    };

    let bytes = serialize_for_cache(&user).unwrap();
    let deserialized: User = deserialize_from_cache(&bytes).unwrap();

    assert_eq!(deserialized, user);
}

#[tokio::test]
async fn test_max_values() {
    let user = User {
        id: u64::MAX,
        name: "Max User".to_string(),
        email: "max@example.com".to_string(),
        active: true,
    };

    let bytes = serialize_for_cache(&user).unwrap();
    let deserialized: User = deserialize_from_cache(&bytes).unwrap();

    assert_eq!(deserialized, user);
}