Skip to main content

Cache

Struct Cache 

Source
pub struct Cache<S: CacheStore> { /* private fields */ }
Expand description

A flexible caching system with pluggable storage strategies.

§Features

  • Works with any CacheStore implementation
  • Structured cache keys with wildcard invalidation
  • Negative caching (caches None results)
  • Configurable expiration per operation
  • Local stampede protection (prevents duplicate fetches within same process)
  • Cost hints embedded in keys for tier-aware stores

Implementations§

Source§

impl<S: CacheStore> Cache<S>

Source

pub fn new(store: S) -> Self

Create a new cache with the given store

Source

pub fn with_ttl(store: S, ttl: Duration) -> Self

Create a new cache with a custom default TTL

Source

pub fn key<I, T>(&self, parts: I) -> CacheQuery<'_, S>
where I: IntoIterator<Item = T>, T: Into<KeyPart>,

Create a cache query from key parts.

Parts can be:

  • String literals: "users", "123"
  • KeyPart::hash(unbounded_value) for URLs, file paths, etc.
  • KeyPart::hash_with_prefix("prefix", value) for debugging

Use "*" as a segment for wildcard matching during invalidation. An empty array [] maps to __root__.

§Example
// Simple key from literals
cache.key(["users", "123"]).get(...).await?;

// Key with hashed segment for unbounded input
cache.key(["convertPCMtoMP3", KeyPart::hash(url)]).get(...).await?;

// Wildcard invalidation
cache.key(["users", "*"]).invalidate().await?;
Source

pub async fn clear(&self) -> Result<()>

Clear all cache entries

Source

pub async fn stats(&self) -> StoreStats

Get cache statistics

Source

pub fn default_ttl(&self) -> Duration

Get the default TTL

Source

pub fn store(&self) -> &S

Get a reference to the underlying store

Source

pub fn namespace(&self, namespace: impl Into<String>) -> NamespacedCache<'_, S>

Create a namespaced view of this cache.

All keys created through the namespaced cache will be prefixed with the namespace. This is useful for isolating cache entries by domain or feature.

§Example
let audio_cache = cache.namespace("audio");

// Key becomes "audio:convert:123"
audio_cache.key(["convert", "123"]).get(...).await?;

// Invalidate all audio cache entries
audio_cache.key(["*"]).invalidate().await?;
Source

pub async fn get_cached<T, F, Fut>( &self, id: T::Id, fetch: F, ) -> Result<Option<T>>
where T: Cached, F: FnOnce() -> Fut + Send, Fut: Future<Output = Option<T>> + Send,

Get a cached entity by ID, using the entity’s Cached trait implementation.

This is a convenience method that constructs the cache key from the entity’s CACHE_PREFIX and the provided ID, and uses the entity’s cache_ttl().

§Example
// Entity implements Cached trait
let member: Option<Member> = cache
    .get_cached::<Member, _>(member_id, || async {
        Member::find_by_id(member_id, db).await.ok()
    })
    .await?;
Source

pub async fn invalidate_cached<T>(&self, id: T::Id) -> Result<usize>
where T: Cached,

Invalidate a cached entity by ID, using the entity’s Cached trait implementation.

§Example
// Invalidate a specific member's cache
cache.invalidate_cached::<Member>(member_id).await?;
Source

pub async fn invalidate_all_cached<T>(&self) -> Result<usize>
where T: Cached,

Invalidate all cached entities of a given type.

§Example
// Invalidate all cached members
cache.invalidate_all_cached::<Member>().await?;

Trait Implementations§

Source§

impl<S: CacheStore> Clone for Cache<S>

Source§

fn clone(&self) -> Self

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<S> Freeze for Cache<S>

§

impl<S> !RefUnwindSafe for Cache<S>

§

impl<S> Send for Cache<S>

§

impl<S> Sync for Cache<S>

§

impl<S> Unpin for Cache<S>

§

impl<S> !UnwindSafe for Cache<S>

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more