pub struct RedisCache { /* private fields */ }Expand description
A Cache implementation backed by Redis.
Values are stored as JSON blobs. Multiple replicas share the same Redis namespace so writes on replica A are immediately visible on replica B, and invalidations propagate within a single round-trip.
Use autumn_web::cache::insert_cached and autumn_web::cache::get_cached
(or equivalently the #[cached] macro) to store and retrieve values — both
functions handle JSON serialization transparently. The plain
autumn_web::cache::insert / get functions perform only in-memory
downcasts and will miss on cross-replica reads. CacheResponseLayer is
safe to use because it stores response entries through the serialized path.
§Runtime requirement
The sync Cache methods bridge to async Redis calls with
tokio::task::block_in_place. They need a multi-thread Tokio
runtime, and panic on a current-thread runtime (for example the default
#[tokio::test] flavor).
Cache::invalidate_async and Cache::invalidate_namespace_async are
real async calls. They work on any runtime and do not hold a worker.
Framework invalidation (generated repositories,
coherence::invalidate_namespace_async) uses them.
§Invalidation errors
Invalidation retries with InvalidationRetry. The async methods return
the final error. The sync invalidate and clear cannot return it, so
they log it with warn! and count it in
autumn_cache_invalidation_failures_total.
Implementations§
Source§impl RedisCache
impl RedisCache
Sourcepub async fn connect(
url: &str,
key_prefix: impl Into<String>,
) -> Result<Self, RedisCacheError>
pub async fn connect( url: &str, key_prefix: impl Into<String>, ) -> Result<Self, RedisCacheError>
Connect using an explicit URL and key prefix.
§Errors
Returns RedisCacheError::Connection if the initial connection fails.
Sourcepub async fn from_config(
config: &CacheRedisConfig,
) -> Result<Self, RedisCacheError>
pub async fn from_config( config: &CacheRedisConfig, ) -> Result<Self, RedisCacheError>
Build a RedisCache from the [cache] section of autumn.toml.
§Errors
Returns RedisCacheError::MissingUrl if cache.redis.url is absent.
Returns RedisCacheError::Connection on connection failure.
Sourcepub const fn with_invalidation_retry(self, retry: InvalidationRetry) -> Self
pub const fn with_invalidation_retry(self, retry: InvalidationRetry) -> Self
Set the retry policy for invalidation. See InvalidationRetry.
Trait Implementations§
Source§impl Cache for RedisCache
impl Cache for RedisCache
Source§fn get_value(&self, key: &str) -> Option<Arc<dyn Any + Send + Sync>>
fn get_value(&self, key: &str) -> Option<Arc<dyn Any + Send + Sync>>
Retrieves a value from Redis and returns it as RawCacheBytes.
Callers using autumn_web::cache::get_cached (which the #[cached]
macro generates) will have the bytes automatically deserialized into the
concrete return type V via serde_json. Direct callers that need the
concrete type should also use get_cached rather than get_value.
Source§fn insert_value(&self, key: &str, value: Arc<dyn Any + Send + Sync>)
fn insert_value(&self, key: &str, value: Arc<dyn Any + Send + Sync>)
Stores a value in Redis by serializing the most common primitive types.
For arbitrary serde types — including structs and collections — use
insert_raw_bytes (called automatically by
autumn_web::cache::insert_cached) instead. Unknown types are
silently skipped here because autumn_web::cache::insert_cached will have already
written the serialized form via insert_raw_bytes.
Source§fn insert_raw_bytes(&self, key: &str, bytes: Vec<u8>, ttl: Option<Duration>)
fn insert_raw_bytes(&self, key: &str, bytes: Vec<u8>, ttl: Option<Duration>)
Stores pre-serialized JSON bytes in Redis, applying the TTL when provided.
This is the primary write path for #[cached]-annotated functions (via
autumn_web::cache::insert_cached). It handles all serde::Serialize
types, including structs and collections that insert_value cannot
serialize from an erased Arc<dyn Any>.
When ttl is Some, the entry is stored with millisecond precision so
Redis expires it automatically, matching the TTL declared on #[cached].
Source§fn try_get_value(
&self,
key: &str,
) -> Result<Option<Arc<dyn Any + Send + Sync>>, CacheBackendError>
fn try_get_value( &self, key: &str, ) -> Result<Option<Arc<dyn Any + Send + Sync>>, CacheBackendError>
As Cache::get_value, but a Redis error is an error, not a miss.
Source§fn try_insert_raw_bytes(
&self,
key: &str,
bytes: Vec<u8>,
ttl: Option<Duration>,
) -> Result<(), CacheBackendError>
fn try_insert_raw_bytes( &self, key: &str, bytes: Vec<u8>, ttl: Option<Duration>, ) -> Result<(), CacheBackendError>
As Cache::insert_raw_bytes, but a failed write is an error.
Source§fn try_invalidate(&self, key: &str) -> Result<(), InvalidationError>
fn try_invalidate(&self, key: &str) -> Result<(), InvalidationError>
As Cache::invalidate, but the final error is returned. It is not
added to the invalidation failure counter. A reserved key is refused.
Like invalidate, this needs a multi-thread runtime.
RedisCache keeps a shared fill epoch per namespace.
Source§fn fill_epoch(&self, namespace: &str) -> FillEpoch
fn fill_epoch(&self, namespace: &str) -> FillEpoch
Reads the namespace’s shared epoch (one GET). A missing key is 0. A
Redis error is FillEpoch::Unavailable, so the fill skips its insert.
Source§fn insert_raw_bytes_if_epoch(
&self,
key: &str,
bytes: Vec<u8>,
ttl: Option<Duration>,
namespace: &str,
sampled: u64,
) -> bool
fn insert_raw_bytes_if_epoch( &self, key: &str, bytes: Vec<u8>, ttl: Option<Duration>, namespace: &str, sampled: u64, ) -> bool
Stores the bytes through one Lua call that compares the epoch first. An error counts as not stored: the cost is one extra miss.
Source§fn invalidate(&self, key: &str)
fn invalidate(&self, key: &str)
Sync DEL with retries. The final error is logged with warn! and
counted, because this method cannot return it. Prefer
Cache::invalidate_async.
Source§fn invalidate_namespace(&self, namespace: &str) -> bool
fn invalidate_namespace(&self, namespace: &str) -> bool
Sync namespace sweep. Returns false when the sweep failed after all
retries. The caller owns that false, so it is not counted here.
Source§fn invalidate_async<'a>(
&'a self,
key: &'a str,
) -> CacheFuture<'a, Result<(), InvalidationError>>
fn invalidate_async<'a>( &'a self, key: &'a str, ) -> CacheFuture<'a, Result<(), InvalidationError>>
Async DEL with retries. No block_in_place, so it works on a
current-thread runtime. Returns the final error.
Source§fn invalidate_namespace_async<'a>(
&'a self,
namespace: &'a str,
) -> CacheFuture<'a, Result<(), InvalidationError>>
fn invalidate_namespace_async<'a>( &'a self, namespace: &'a str, ) -> CacheFuture<'a, Result<(), InvalidationError>>
Async namespace sweep with retries. Returns the final error.
Source§fn try_acquire_fill_lock(
&self,
key: &str,
token: &str,
ttl: Duration,
) -> FillLockStatus
fn try_acquire_fill_lock( &self, key: &str, token: &str, ttl: Duration, ) -> FillLockStatus
Acquires a cross-replica fill lock via SET NX PX. Redis errors are
treated as FillLockStatus::Held (fail closed toward “someone else
may be filling”) — the caller’s lock_wait_timeout bounds how long it
waits before falling back to filling locally.
Source§fn release_fill_lock(&self, key: &str, token: &str)
fn release_fill_lock(&self, key: &str, token: &str)
Releases the fill lock only if token still owns it (compare-and-delete
via a Lua script), so a caller can never release a lock another replica
has since taken over after this caller’s lock expired.
Auto Trait Implementations§
impl !RefUnwindSafe for RedisCache
impl !UnwindSafe for RedisCache
impl Freeze for RedisCache
impl Send for RedisCache
impl Sync for RedisCache
impl Unpin for RedisCache
impl UnsafeUnpin for RedisCache
Blanket Implementations§
Source§impl<T> AggregateExpressionMethods for T
impl<T> AggregateExpressionMethods for T
Source§fn aggregate_distinct(self) -> Self::Outputwhere
Self: DistinctDsl,
fn aggregate_distinct(self) -> Self::Outputwhere
Self: DistinctDsl,
DISTINCT modifier for aggregate functions Read moreSource§fn aggregate_all(self) -> Self::Outputwhere
Self: AllDsl,
fn aggregate_all(self) -> Self::Outputwhere
Self: AllDsl,
ALL modifier for aggregate functions Read moreSource§fn aggregate_filter<P>(self, f: P) -> Self::Output
fn aggregate_filter<P>(self, f: P) -> Self::Output
Source§fn aggregate_order<O>(self, o: O) -> Self::Outputwhere
Self: OrderAggregateDsl<O>,
fn aggregate_order<O>(self, o: O) -> Self::Outputwhere
Self: OrderAggregateDsl<O>,
Source§impl<T> AutumnCounterCaches for Twhere
T: 'static,
impl<T> AutumnCounterCaches for Twhere
T: 'static,
Source§const HAS_COUNTER_CACHES: bool = false
const HAS_COUNTER_CACHES: bool = false
Source§fn counter_caches() -> &'static [CounterCacheSpec<Self>]
fn counter_caches() -> &'static [CounterCacheSpec<Self>]
Source§impl<T> AutumnDependents for Twhere
T: ?Sized,
impl<T> AutumnDependents for Twhere
T: ?Sized,
Source§fn dependents() -> &'static [RuntimeDependentSpec]
fn dependents() -> &'static [RuntimeDependentSpec]
#[model] overrides via an inherent shadow when dependents exist.Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be
downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further
downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.Source§impl<T> DowncastSend for T
impl<T> DowncastSend for T
Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoSql for T
impl<T> IntoSql for T
Source§fn into_sql<T>(self) -> Self::Expression
fn into_sql<T>(self) -> Self::Expression
self to an expression for Diesel’s query builder. Read moreSource§fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
&self to an expression for Diesel’s query builder. Read moreSource§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
Source§impl<T> RepositoryHooksClone for Twhere
T: Clone,
impl<T> RepositoryHooksClone for Twhere
T: Clone,
Source§fn autumn_clone(&self) -> T
fn autumn_clone(&self) -> T
Source§impl<T, Conn> RunQueryDsl<Conn> for T
impl<T, Conn> RunQueryDsl<Conn> for T
Source§fn execute<'conn, 'query>(
self,
conn: &'conn mut Conn,
) -> <Conn as AsyncConnectionCore>::ExecuteFuture<'conn, 'query>
fn execute<'conn, 'query>( self, conn: &'conn mut Conn, ) -> <Conn as AsyncConnectionCore>::ExecuteFuture<'conn, 'query>
Source§fn load<'query, 'conn, U>(
self,
conn: &'conn mut Conn,
) -> AndThen<Self::LoadFuture<'conn>, TryCollect<Self::Stream<'conn>, Vec<U>>>
fn load<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<Self::LoadFuture<'conn>, TryCollect<Self::Stream<'conn>, Vec<U>>>
Source§fn load_stream<'conn, 'query, U>(
self,
conn: &'conn mut Conn,
) -> Self::LoadFuture<'conn>where
Conn: AsyncConnectionCore,
U: 'conn,
Self: LoadQuery<'query, Conn, U> + 'query,
fn load_stream<'conn, 'query, U>(
self,
conn: &'conn mut Conn,
) -> Self::LoadFuture<'conn>where
Conn: AsyncConnectionCore,
U: 'conn,
Self: LoadQuery<'query, Conn, U> + 'query,
Stream] with the returned rows. Read moreSource§fn get_result<'query, 'conn, U>(
self,
conn: &'conn mut Conn,
) -> AndThen<Self::LoadFuture<'conn>, LoadNext<Pin<Box<Self::Stream<'conn>>>>>
fn get_result<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<Self::LoadFuture<'conn>, LoadNext<Pin<Box<Self::Stream<'conn>>>>>
Source§fn get_results<'query, 'conn, U>(
self,
conn: &'conn mut Conn,
) -> AndThen<Self::LoadFuture<'conn>, TryCollect<Self::Stream<'conn>, Vec<U>>>
fn get_results<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<Self::LoadFuture<'conn>, TryCollect<Self::Stream<'conn>, Vec<U>>>
Vec with the affected rows. Read moreSource§impl<T> Scoped for T
impl<T> Scoped for T
Source§fn scope(ctx: &PolicyContext) -> ScopeQuery<'_, Self>
fn scope(ctx: &PolicyContext) -> ScopeQuery<'_, Self>
ScopeQuery for this type. Resolves the
registered scope at .load() time, not here.