pub trait CacheEntity:
Send
+ Sync
+ Serialize
+ for<'de> Deserialize<'de>
+ Clone {
type Key: Display + Clone + Send + Sync + Eq + Hash + 'static;
// Required methods
fn cache_key(&self) -> Self::Key;
fn cache_prefix() -> &'static str;
// Provided methods
fn serialize_for_cache(&self) -> Result<Vec<u8>> { ... }
fn deserialize_from_cache(bytes: &[u8]) -> Result<Self> { ... }
fn validate(&self) -> Result<()> { ... }
}Expand description
Trait that all entities stored in cache must implement.
§Example
use serde::{Deserialize, Serialize};
use cache_kit::CacheEntity;
#[derive(Clone, Serialize, Deserialize)]
pub struct Employment {
pub id: String,
pub employer_name: String,
}
impl CacheEntity for Employment {
type Key = String;
fn cache_key(&self) -> Self::Key {
self.id.clone()
}
fn cache_prefix() -> &'static str {
"employment"
}
}Required Associated Types§
Required Methods§
Sourcefn cache_key(&self) -> Self::Key
fn cache_key(&self) -> Self::Key
Return the entity’s unique cache key.
Called to extract the key from the entity itself.
Example: Employment.id → "emp_12345"
Sourcefn cache_prefix() -> &'static str
fn cache_prefix() -> &'static str
Return the cache prefix for this entity type.
Used to namespace cache keys. Example: “employment”, “borrower”
Final cache key format: "{prefix}:{key}"
Provided Methods§
Sourcefn serialize_for_cache(&self) -> Result<Vec<u8>>
fn serialize_for_cache(&self) -> Result<Vec<u8>>
Serialize entity for cache storage.
Uses Postcard with versioned envelopes for all cache storage. This method is NOT overridable to ensure consistency across all entities.
§Format
[MAGIC: 4 bytes] [VERSION: 4 bytes] [POSTCARD PAYLOAD]§Performance
- 10-15x faster than JSON
- 60% smaller payloads
See crate::serialization for implementation details.
Sourcefn deserialize_from_cache(bytes: &[u8]) -> Result<Self>
fn deserialize_from_cache(bytes: &[u8]) -> Result<Self>
Deserialize entity from cache storage.
Validates magic header and schema version before deserializing. This method is NOT overridable to ensure consistency across all entities.
§Validation
- Magic must be b“CKIT“
- Version must match current schema version
- Postcard deserialization must succeed
§Errors
Error::InvalidCacheEntry: Bad magic or corrupted envelopeError::VersionMismatch: Schema version changedError::DeserializationError: Corrupted payload
See crate::serialization for implementation details.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.