CacheService

Struct CacheService 

Source
pub struct CacheService<B: CacheBackend> { /* private fields */ }
Expand description

High-level cache service for web applications.

Wraps CacheExpander in Arc for easy sharing across threads without requiring external Arc<Mutex<>> wrappers.

§Design

Since CacheBackend implementations use interior mutability (RwLock, Mutex), and CacheExpander now uses &self methods, we can safely wrap it in Arc without needing an additional Mutex.

§Example

use cache_kit::{CacheService, backend::InMemoryBackend};

// Create service (can be shared across threads)
let cache = CacheService::new(InMemoryBackend::new());

// In your web service struct
pub struct UserService {
    cache: CacheService<InMemoryBackend>,
    repo: Arc<UserRepository>,
}

impl UserService {
    pub fn get(&self, id: &str) -> Result<Option<User>> {
        let mut feeder = UserFeeder { id: id.to_string(), user: None };
        self.cache.execute(&mut feeder, &*self.repo, CacheStrategy::Refresh)?;
        Ok(feeder.user)
    }
}

Implementations§

Source§

impl<B: CacheBackend> CacheService<B>

Source

pub fn new(backend: B) -> Self

Create a new cache service with the given backend.

Source

pub fn with_metrics(backend: B, metrics: Box<dyn CacheMetrics>) -> Self

Create a new cache service with custom metrics.

Source

pub async fn execute<T, F, R>( &self, feeder: &mut F, repository: &R, strategy: CacheStrategy, ) -> Result<()>
where T: CacheEntity, F: CacheFeed<T>, R: DataRepository<T>, T::Key: FromStr,

Execute a cache operation.

This is equivalent to calling expander.with() but more ergonomic for service-oriented architectures.

§Arguments
  • feeder: Entity feeder (implements CacheFeed<T>)
  • repository: Data repository (implements DataRepository<T>)
  • strategy: Cache strategy (Fresh, Refresh, Invalidate, Bypass)
§Example
let cache = CacheService::new(InMemoryBackend::new());
let mut feeder = UserFeeder { id: "user_123".to_string(), user: None };
let repo = UserRepository::new(pool);

cache.execute(&mut feeder, &repo, CacheStrategy::Refresh).await?;
let user = feeder.user;
§Errors

Returns Err in these cases:

  • Error::ValidationError: Feeder validation fails
  • Error::DeserializationError: Cached data is corrupted
  • Error::InvalidCacheEntry: Invalid cache envelope
  • Error::VersionMismatch: Schema version mismatch
  • Error::BackendError: Cache backend unavailable
  • Error::RepositoryError: Database access fails
  • Error::SerializationError: Entity serialization fails
Source

pub async fn execute_with_config<T, F, R>( &self, feeder: &mut F, repository: &R, strategy: CacheStrategy, config: OperationConfig, ) -> Result<()>
where T: CacheEntity, F: CacheFeed<T>, R: DataRepository<T>, T::Key: FromStr,

Execute a cache operation with advanced configuration.

This method allows per-operation configuration such as TTL override and retry logic, while working seamlessly with Arc-wrapped services.

§Arguments
  • feeder: Entity feeder (implements CacheFeed<T>)
  • repository: Data repository (implements DataRepository<T>)
  • strategy: Cache strategy (Fresh, Refresh, Invalidate, Bypass)
  • config: Operation configuration (TTL override, retry count)
§Example
let cache = CacheService::new(InMemoryBackend::new());
let mut feeder = UserFeeder { id: "user_123".to_string(), user: None };
let repo = UserRepository::new(pool);

let config = OperationConfig::default()
    .with_ttl(Duration::from_secs(300))
    .with_retry(3);

cache.execute_with_config(&mut feeder, &repo, CacheStrategy::Refresh, config).await?;
let user = feeder.user;
§Errors

Same error cases as execute(), plus retry-related failures.

Source

pub fn expander(&self) -> &CacheExpander<B>

Get a reference to the underlying expander.

Use this if you need direct access to expander methods.

Trait Implementations§

Source§

impl<B: Clone + CacheBackend> Clone for CacheService<B>

Source§

fn clone(&self) -> CacheService<B>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<B> Freeze for CacheService<B>

§

impl<B> !RefUnwindSafe for CacheService<B>

§

impl<B> Send for CacheService<B>

§

impl<B> Sync for CacheService<B>

§

impl<B> Unpin for CacheService<B>

§

impl<B> !UnwindSafe for CacheService<B>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.