CacheEntity

Trait CacheEntity 

Source
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§

Source

type Key: Display + Clone + Send + Sync + Eq + Hash + 'static

Type of the entity’s key/ID (typically String or UUID)

Required Methods§

Source

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"

Source

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§

Source

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.

Source

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 envelope
  • Error::VersionMismatch: Schema version changed
  • Error::DeserializationError: Corrupted payload

See crate::serialization for implementation details.

Source

fn validate(&self) -> Result<()>

Optional: Validate entity after deserialization.

Called after loading from cache. Use to ensure consistency.

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.

Implementors§