hyperchad_state 0.3.0

HyperChad state management package
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Core state store implementation with in-memory caching
//!
//! This module provides the [`StateStore`] type, which combines an in-memory cache
//! with a pluggable persistence backend to provide fast access to frequently used
//! state while ensuring durability through persistent storage.

use std::{
    collections::BTreeMap,
    sync::{Arc, RwLock},
};

use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;

use crate::{Error, persistence::StatePersistence};

/// In-memory state store that can be optionally backed by persistent storage
///
/// # Examples
///
/// ```rust,no_run
/// # #[cfg(feature = "persistence-sqlite")]
/// # {
/// use hyperchad_state::{StateStore, sqlite::SqlitePersistence};
///
/// # async fn example() -> Result<(), hyperchad_state::Error> {
/// let persistence = SqlitePersistence::new_in_memory().await?;
/// let store = StateStore::new(persistence);
///
/// store.set("theme", &"light").await?;
/// # Ok(())
/// # }
/// # }
/// ```
pub struct StateStore<P: StatePersistence> {
    persistence: Arc<P>,
    cache: Arc<RwLock<BTreeMap<String, Value>>>,
}

impl<P: StatePersistence> StateStore<P> {
    /// Create a new state store with the given persistence backend
    #[must_use]
    pub fn new(persistence: P) -> Self {
        Self {
            persistence: Arc::new(persistence),
            cache: Arc::new(RwLock::new(BTreeMap::new())),
        }
    }

    /// Set a value in the store
    ///
    /// The value is stored in both the in-memory cache and the persistence backend.
    ///
    /// # Errors
    ///
    /// * [`Error::Serde`] - If the value cannot be serialized to JSON
    /// * [`Error::Database`] - If the persistence backend database operation fails
    /// * [`Error::InvalidDbConfiguration`] - If the persistence backend database is misconfigured
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "persistence-sqlite")]
    /// # {
    /// use hyperchad_state::{StateStore, sqlite::SqlitePersistence};
    ///
    /// # async fn example() -> Result<(), hyperchad_state::Error> {
    /// let persistence = SqlitePersistence::new_in_memory().await?;
    /// let store = StateStore::new(persistence);
    ///
    /// store.set("volume", &60_u8).await?;
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    pub async fn set<T: Serialize + Send + Sync>(
        &self,
        key: impl Into<String> + Send + Sync,
        value: &T,
    ) -> Result<(), Error> {
        let key = key.into();

        let serialized = serde_json::to_value(value)?;
        if let Ok(mut cache) = self.cache.write() {
            cache.insert(key.clone(), serialized.clone());
        }
        self.persistence.set(key, &serialized).await
    }

    /// Get a value from the store
    ///
    /// Checks the in-memory cache first, then falls back to the persistence backend
    /// if not found in cache. Returns `None` if the key does not exist.
    ///
    /// # Errors
    ///
    /// * [`Error::Serde`] - If the stored value cannot be deserialized from JSON
    /// * [`Error::Database`] - If the persistence backend database operation fails
    /// * [`Error::InvalidDbConfiguration`] - If the persistence backend database is misconfigured
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "persistence-sqlite")]
    /// # {
    /// use hyperchad_state::{StateStore, sqlite::SqlitePersistence};
    ///
    /// # async fn example() -> Result<(), hyperchad_state::Error> {
    /// let persistence = SqlitePersistence::new_in_memory().await?;
    /// let store = StateStore::new(persistence);
    ///
    /// store.set("username", &"moosic").await?;
    /// let username: Option<String> = store.get("username").await?;
    /// assert_eq!(username.as_deref(), Some("moosic"));
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    pub async fn get<T: Serialize + DeserializeOwned + Send + Sync>(
        &self,
        key: impl AsRef<str> + Send + Sync,
    ) -> Result<Option<T>, Error> {
        let key = key.as_ref();

        if let Ok(cache) = self.cache.read()
            && let Some(data) = cache.get(key)
        {
            let data = serde_json::from_value(data.clone())?;
            return Ok(Some(data));
        }

        let Some(data) = self.persistence.get::<T>(key).await? else {
            return Ok(None);
        };

        let value = serde_json::to_value(data)?;

        if let Ok(mut cache) = self.cache.write() {
            cache.insert(key.to_string(), value.clone());
        }

        Ok(Some(serde_json::from_value(value)?))
    }

    /// Remove a value from the store
    ///
    /// Removes the value from both the in-memory cache and the persistence backend.
    ///
    /// # Errors
    ///
    /// * [`Error::Serde`] - If the stored value cannot be deserialized during removal
    /// * [`Error::Database`] - If the persistence backend database operation fails
    /// * [`Error::InvalidDbConfiguration`] - If the persistence backend database is misconfigured
    pub async fn remove(&self, key: impl AsRef<str> + Send + Sync) -> Result<(), Error> {
        let key = key.as_ref();

        if let Ok(mut cache) = self.cache.write() {
            cache.remove(key);
        }
        self.persistence.remove(key).await
    }

    /// Remove a value from the store and return it
    ///
    /// Removes the value from both the in-memory cache and the persistence backend,
    /// returning the value if it exists. Returns `None` if the key does not exist.
    ///
    /// # Errors
    ///
    /// * [`Error::Serde`] - If the stored value cannot be deserialized from JSON
    /// * [`Error::Database`] - If the persistence backend database operation fails
    /// * [`Error::InvalidDbConfiguration`] - If the persistence backend database is misconfigured
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "persistence-sqlite")]
    /// # {
    /// use hyperchad_state::{StateStore, sqlite::SqlitePersistence};
    ///
    /// # async fn example() -> Result<(), hyperchad_state::Error> {
    /// let persistence = SqlitePersistence::new_in_memory().await?;
    /// let store = StateStore::new(persistence);
    ///
    /// store.set("token", &"abc123").await?;
    /// let token: Option<String> = store.take("token").await?;
    /// assert_eq!(token.as_deref(), Some("abc123"));
    /// # Ok(())
    /// # }
    /// # }
    /// ```
    pub async fn take<T: DeserializeOwned + Send + Sync>(
        &self,
        key: impl AsRef<str> + Send + Sync,
    ) -> Result<Option<T>, Error> {
        let key = key.as_ref();

        if let Ok(mut cache) = self.cache.write() {
            cache.remove(key);
        }
        self.persistence.take(key).await
    }

    /// Clear all values from the store
    ///
    /// Removes all values from both the in-memory cache and the persistence backend.
    ///
    /// # Errors
    ///
    /// * [`Error::Database`] - If the persistence backend database operation fails
    pub async fn clear(&self) -> Result<(), Error> {
        if let Ok(mut cache) = self.cache.write() {
            cache.clear();
        }
        self.persistence.clear().await
    }
}

#[cfg(feature = "persistence-sqlite")]
#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    use crate::sqlite::SqlitePersistence;

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
    struct TestData {
        id: u32,
        name: String,
    }

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    struct IncompatibleType {
        required_field: Vec<u64>,
    }

    #[test_log::test(switchy_async::test)]
    async fn test_cache_hit_after_get() -> Result<(), Error> {
        // Test that values retrieved from persistence are cached for subsequent gets
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let data = TestData {
            id: 1,
            name: "test".to_string(),
        };

        // First set - should write to both cache and persistence
        store.set("key1", &data).await?;

        // First get - should hit persistence and populate cache
        let retrieved1: Option<TestData> = store.get("key1").await?;
        assert_eq!(retrieved1, Some(data.clone()));

        // Second get - should hit cache (we can't directly verify this, but it exercises the cache path)
        let retrieved2: Option<TestData> = store.get("key1").await?;
        assert_eq!(retrieved2, Some(data));

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_cache_invalidation_on_remove() -> Result<(), Error> {
        // Test that cache is properly invalidated when removing items
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let data = TestData {
            id: 2,
            name: "test".to_string(),
        };

        // Set and get to populate cache
        store.set("key2", &data).await?;
        let _: Option<TestData> = store.get("key2").await?;

        // Remove should clear from both cache and persistence
        store.remove("key2").await?;

        // Get should now return None
        let retrieved: Option<TestData> = store.get("key2").await?;
        assert_eq!(retrieved, None);

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_cache_invalidation_on_clear() -> Result<(), Error> {
        // Test that cache is properly cleared when clearing the entire store
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let data1 = TestData {
            id: 1,
            name: "first".to_string(),
        };
        let data2 = TestData {
            id: 2,
            name: "second".to_string(),
        };

        // Set multiple items and populate cache
        store.set("key1", &data1).await?;
        store.set("key2", &data2).await?;
        let _: Option<TestData> = store.get("key1").await?;
        let _: Option<TestData> = store.get("key2").await?;

        // Clear should remove all items from cache and persistence
        store.clear().await?;

        // Both keys should return None
        assert_eq!(store.get::<TestData>("key1").await?, None);
        assert_eq!(store.get::<TestData>("key2").await?, None);

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_take_removes_from_cache_and_returns_value() -> Result<(), Error> {
        // Test that take removes from both cache and persistence while returning the value
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let data = TestData {
            id: 3,
            name: "test".to_string(),
        };

        // Set and get to populate cache
        store.set("key3", &data).await?;
        let _: Option<TestData> = store.get("key3").await?;

        // Take should return the value and remove it
        let taken: Option<TestData> = store.take("key3").await?;
        assert_eq!(taken, Some(data));

        // Subsequent get should return None
        let retrieved: Option<TestData> = store.get("key3").await?;
        assert_eq!(retrieved, None);

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_take_nonexistent_key_returns_none() -> Result<(), Error> {
        // Test that taking a nonexistent key returns None without errors
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let taken: Option<TestData> = store.take("nonexistent").await?;
        assert_eq!(taken, None);

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_update_existing_key() -> Result<(), Error> {
        // Test that setting an existing key updates both cache and persistence
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let data1 = TestData {
            id: 1,
            name: "original".to_string(),
        };
        let data2 = TestData {
            id: 1,
            name: "updated".to_string(),
        };

        // Set initial value
        store.set("key4", &data1).await?;
        let retrieved1: Option<TestData> = store.get("key4").await?;
        assert_eq!(retrieved1, Some(data1));

        // Update the value
        store.set("key4", &data2).await?;
        let retrieved2: Option<TestData> = store.get("key4").await?;
        assert_eq!(retrieved2, Some(data2));

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_empty_string_key() -> Result<(), Error> {
        // Test that empty string keys are handled correctly
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let data = TestData {
            id: 5,
            name: "empty_key_test".to_string(),
        };

        // Empty string should be a valid key
        store.set("", &data).await?;
        let retrieved: Option<TestData> = store.get("").await?;
        assert_eq!(retrieved, Some(data));

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_special_characters_in_key() -> Result<(), Error> {
        // Test that keys with special characters are handled correctly
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let data = TestData {
            id: 6,
            name: "special".to_string(),
        };

        let special_key = "key/with:special@chars#$%";
        store.set(special_key, &data).await?;
        let retrieved: Option<TestData> = store.get(special_key).await?;
        assert_eq!(retrieved, Some(data));

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_complex_nested_data() -> Result<(), Error> {
        // Test serialization and deserialization of complex nested structures
        #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
        struct ComplexData {
            items: Vec<TestData>,
            metadata: BTreeMap<String, String>,
        }

        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let mut metadata = BTreeMap::new();
        metadata.insert("version".to_string(), "1.0".to_string());
        metadata.insert("author".to_string(), "test".to_string());

        let complex = ComplexData {
            items: vec![
                TestData {
                    id: 1,
                    name: "first".to_string(),
                },
                TestData {
                    id: 2,
                    name: "second".to_string(),
                },
            ],
            metadata,
        };

        store.set("complex", &complex).await?;
        let retrieved: Option<ComplexData> = store.get("complex").await?;
        assert_eq!(retrieved, Some(complex));

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_multiple_independent_keys() -> Result<(), Error> {
        // Test that multiple keys can coexist independently
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let data1 = TestData {
            id: 1,
            name: "first".to_string(),
        };
        let data2 = TestData {
            id: 2,
            name: "second".to_string(),
        };
        let data3 = TestData {
            id: 3,
            name: "third".to_string(),
        };

        // Set multiple keys
        store.set("key_a", &data1).await?;
        store.set("key_b", &data2).await?;
        store.set("key_c", &data3).await?;

        // Verify all keys are independently retrievable
        assert_eq!(store.get::<TestData>("key_a").await?, Some(data1.clone()));
        assert_eq!(store.get::<TestData>("key_b").await?, Some(data2));
        assert_eq!(store.get::<TestData>("key_c").await?, Some(data3.clone()));

        // Remove one key and verify others are unaffected
        store.remove("key_b").await?;
        assert_eq!(store.get::<TestData>("key_a").await?, Some(data1));
        assert_eq!(store.get::<TestData>("key_b").await?, None);
        assert_eq!(store.get::<TestData>("key_c").await?, Some(data3));

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_get_nonexistent_key_returns_none() -> Result<(), Error> {
        // Test that getting a key that never existed returns None
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        let result: Option<TestData> = store.get("nonexistent").await?;
        assert_eq!(result, None);

        Ok(())
    }

    #[test_log::test(switchy_async::test)]
    async fn test_store_type_mismatch_on_get_returns_error() -> Result<(), Error> {
        // Test that deserializing as wrong type returns serde error through StateStore
        let persistence = SqlitePersistence::new_in_memory().await?;
        let store = StateStore::new(persistence);

        // Set a TestData value
        let data = TestData {
            id: 1,
            name: "test".to_string(),
        };
        store.set("key", &data).await?;

        // Try to get it as an incompatible type
        let result = store.get::<IncompatibleType>("key").await;

        // Should return a serde error
        assert!(
            matches!(result, Err(Error::Serde(_))),
            "Expected Serde error, got: {result:?}"
        );

        Ok(())
    }
}