Skip to main content

RedisCache

Struct RedisCache 

Source
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

Source

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.

Source

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.

Source

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

Source§

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>)

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>)

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>

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>

As Cache::insert_raw_bytes, but a failed write is an error.

Source§

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.

Source§

fn shares_fill_epoch(&self) -> bool

RedisCache keeps a shared fill epoch per namespace.

Source§

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

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)

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

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

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

Async namespace sweep with retries. Returns the final error.

Source§

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)

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.

Source§

fn clear(&self)

Remove all entries.
Source§

impl Clone for RedisCache

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> AggregateExpressionMethods for T

Source§

fn aggregate_distinct(self) -> Self::Output
where Self: DistinctDsl,

DISTINCT modifier for aggregate functions Read more
Source§

fn aggregate_all(self) -> Self::Output
where Self: AllDsl,

ALL modifier for aggregate functions Read more
Source§

fn aggregate_filter<P>(self, f: P) -> Self::Output
where P: AsExpression<Bool>, Self: FilterDsl<<P as AsExpression<Bool>>::Expression>,

Add an aggregate function filter Read more
Source§

fn aggregate_order<O>(self, o: O) -> Self::Output
where Self: OrderAggregateDsl<O>,

Add an aggregate function order Read more
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> AutumnCounterCaches for T
where T: 'static,

Source§

const HAS_COUNTER_CACHES: bool = false

Whether this model has any counter cache at all. Read more
Source§

fn counter_caches() -> &'static [CounterCacheSpec<Self>]

The model’s counter-cache specs, in declaration order.
Source§

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

Source§

fn dependents() -> &'static [RuntimeDependentSpec]

The model’s dependent-cascade specs, in declaration order. Defaults to none; #[model] overrides via an inherent shadow when dependents exist.
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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts 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>

Converts 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)

Converts &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)

Converts &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
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Sync + Send>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send> ⓘ

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> IntoSql for T

Source§

fn into_sql<T>(self) -> Self::Expression

Convert self to an expression for Diesel’s query builder. Read more
Source§

fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
where &'a Self: AsExpression<T>, T: SqlType + TypedExpressionType,

Convert &self to an expression for Diesel’s query builder. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

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

Source§

fn autumn_clone(&self) -> T

Clone hook state for generated repository values.
Source§

impl<T, Conn> RunQueryDsl<Conn> for T

Source§

fn execute<'conn, 'query>( self, conn: &'conn mut Conn, ) -> <Conn as AsyncConnectionCore>::ExecuteFuture<'conn, 'query>
where Conn: AsyncConnectionCore + Send, Self: ExecuteDsl<Conn> + 'query,

Executes the given command, returning the number of rows affected. Read more
Source§

fn load<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<Self::LoadFuture<'conn>, TryCollect<Self::Stream<'conn>, Vec<U>>>
where U: Send, Conn: AsyncConnectionCore, Self: LoadQuery<'query, Conn, U> + 'query,

Executes the given query, returning a Vec with the returned rows. Read more
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,

Executes the given query, returning a [Stream] with the returned rows. Read more
Source§

fn get_result<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<Self::LoadFuture<'conn>, LoadNext<Pin<Box<Self::Stream<'conn>>>>>
where U: Send + 'conn, Conn: AsyncConnectionCore, Self: LoadQuery<'query, Conn, U> + 'query,

Runs the command, and returns the affected row. Read more
Source§

fn get_results<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<Self::LoadFuture<'conn>, TryCollect<Self::Stream<'conn>, Vec<U>>>
where U: Send, Conn: AsyncConnectionCore, Self: LoadQuery<'query, Conn, U> + 'query,

Runs the command, returning an Vec with the affected rows. Read more
Source§

fn first<'query, 'conn, U>( self, conn: &'conn mut Conn, ) -> AndThen<<Self::Output as LoadQuery<'query, Conn, U>>::LoadFuture<'conn>, LoadNext<Pin<Box<<Self::Output as LoadQuery<'query, Conn, U>>::Stream<'conn>>>>>
where U: Send + 'conn, Conn: AsyncConnectionCore, Self: LimitDsl, Self::Output: LoadQuery<'query, Conn, U> + Send + 'query,

Attempts to load a single record. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Scoped for T
where T: Send + Sync + 'static,

Source§

fn scope(ctx: &PolicyContext) -> ScopeQuery<'_, Self>

Open a deferred ScopeQuery for this type. Resolves the registered scope at .load() time, not here.
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 = !

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

fn try_from(value: U) -> Result<T, !>

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

Source§

fn over(self) -> Self::Output
where Self: OverDsl,

Turn a function call into a window function call Read more
Source§

fn window_filter<P>(self, f: P) -> Self::Output
where P: AsExpression<Bool>, Self: FilterDsl<<P as AsExpression<Bool>>::Expression>,

Add a filter to the current window function Read more
Source§

fn partition_by<E>(self, expr: E) -> Self::Output
where Self: PartitionByDsl<E>,

Add a partition clause to the current window function Read more
Source§

fn window_order<E>(self, expr: E) -> Self::Output
where Self: OrderWindowDsl<E>,

Add a order clause to the current window function Read more
Source§

fn frame_by<E>(self, expr: E) -> Self::Output
where Self: FrameDsl<E>,

Add a frame clause to the current window function Read more
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