Skip to main content

rpytest_core/storage/
traits.rs

1//! Storage backend trait for abstracting persistence layer.
2
3use std::path::Path;
4
5/// Error type for storage operations.
6#[derive(Debug, thiserror::Error)]
7pub enum StorageError {
8    #[error("I/O error: {0}")]
9    Io(#[from] std::io::Error),
10
11    #[error("Serialization error: {0}")]
12    Serialization(String),
13
14    #[error("Key not found")]
15    NotFound,
16
17    #[error("Storage corrupted: {0}")]
18    Corrupted(String),
19
20    #[error("Storage backend error: {0}")]
21    Backend(String),
22}
23
24/// Result type for storage operations.
25pub type StorageResult<T> = Result<T, StorageError>;
26
27/// Abstraction over key-value storage backends.
28///
29/// This trait allows rpytest to use different storage implementations
30/// (e.g., sled, redb) without changing the core logic.
31pub trait StorageBackend: Send + Sync {
32    /// Open or create a storage instance at the given path.
33    fn open(path: &Path) -> StorageResult<Self>
34    where
35        Self: Sized;
36
37    /// Get a value by key.
38    fn get(&self, key: &[u8]) -> StorageResult<Option<Vec<u8>>>;
39
40    /// Set a key-value pair.
41    fn set(&self, key: &[u8], value: &[u8]) -> StorageResult<()>;
42
43    /// Delete a key.
44    fn delete(&self, key: &[u8]) -> StorageResult<()>;
45
46    /// Check if a key exists.
47    fn contains(&self, key: &[u8]) -> StorageResult<bool> {
48        Ok(self.get(key)?.is_some())
49    }
50
51    /// Flush pending writes to disk.
52    fn flush(&self) -> StorageResult<()>;
53
54    /// Iterate over all keys with a given prefix.
55    fn scan_prefix(&self, prefix: &[u8]) -> StorageResult<Vec<(Vec<u8>, Vec<u8>)>>;
56
57    /// Clear all data (use with caution).
58    fn clear(&self) -> StorageResult<()>;
59}
60
61/// Schema version for cache format compatibility.
62pub const SCHEMA_VERSION: u32 = 1;
63
64/// Key prefixes for namespacing data in storage.
65pub mod keys {
66    /// Prefix for inventory data.
67    pub const INVENTORY: &[u8] = b"inv:";
68
69    /// Prefix for test duration history.
70    pub const DURATIONS: &[u8] = b"dur:";
71
72    /// Prefix for test outcome history.
73    pub const OUTCOMES: &[u8] = b"out:";
74
75    /// Prefix for context metadata.
76    pub const CONTEXT: &[u8] = b"ctx:";
77
78    /// Key for schema version.
79    pub const SCHEMA: &[u8] = b"_schema_version";
80}