Skip to main content

RouteCache

Struct RouteCache 

Source
pub struct RouteCache<C> { /* private fields */ }
Expand description

Middleware that caches successful GET and HEAD responses.

Caching is opt-in. There are two ways to opt a route in:

  • Per response. Put the layer on the whole app; it stores only responses marked Cache-Control: public (for example with Cached::public). Everything else passes through.
  • Per route. Put the layer on one route with MethodRouter::layer and set default_ttl; that route’s responses are stored without a public marker.
use siderite_cache::{MemoryCache, RouteCache};
use siderite_core::{App, Cached, get};
use std::time::Duration;

let cache = MemoryCache::new(1024);
let _app = App::new()
    // Opted in by its response.
    .route("/news", get(|| async {
        Cached::public(Duration::from_secs(60), "news")
    }))
    // Opted in by placement.
    .route("/stats", get(|| async { "stats" }).layer(
        RouteCache::new(cache.clone())
            .default_ttl(Duration::from_secs(30)),
    ))
    // Never stored: no `public` marker.
    .route("/me", get(|| async { "private" }))
    .layer(RouteCache::new(cache));

Do not set default_ttl on an app-wide layer unless every GET route in the app is safe to share between users.

§Behaviour

  • Only GET and HEAD responses are stored. Successful unsafe target writes rotate a shared generation across every representation. Related URI dependencies require explicit application invalidation.
  • The cache key is the method, scheme, Host, path and query (as received), plus the request’s Accept and Accept-Encoding values, so virtual hosts sharing one cache never see each other’s responses.
  • Requests carrying credentials bypass the cache: Authorization, Proxy-Authorization, Cookie, X-API-Key, any header whose name contains auth, token, session, jwt, secret, api-key, apikey or access-key, and any header added with RouteCache::bypass_header. Such requests are neither answered from nor stored in the cache.
  • Responses are stored only when the status is 200, there is no Set-Cookie, Cache-Control does not contain no-store, no-cache or private, Vary names no header outside the key, and the body length is known and at most RouteCache::max_body_bytes. Streaming bodies (server-sent events, file streams) pass through untouched.
  • On top of that, a response needs Cache-Control: public unless default_ttl is set.
  • The entry lives for s-maxage, else max-age, else default_ttl. A public response without any of these, or with a lifetime of zero, is not stored.
  • Request no-cache refreshes; no-store bypasses without deleting older entries. Unsupported conditionals and ranges bypass. Date is retained and Age includes origin age and residence. Entries are versioned.
  • Namespaces isolate layers by default. Stable namespaces intentionally share generations; key, header and encoded byte admission is bounded.
  • Every GET/HEAD response is tagged with x-cache: hit or x-cache: miss.

Cache backend failures fail open: the request is served and treated as a miss. Failed write invalidation disables this layer. A database commit and distributed cache invalidation are separate operations; other nodes need an outage/restart consistency policy. No secret values are logged.

Implementations§

Source§

impl<C: Cache> RouteCache<C>

Source

pub fn new(cache: C) -> Self

Cache GET/HEAD 200 responses marked Cache-Control: public in cache.

Source

pub fn namespace(self, namespace: impl Into<String>) -> Self

Set a stable app/deployment namespace for intentionally shared caches.

Args: namespace: Identity distinct from incompatible apps or revisions.

Returns: Configured layer; the default namespace is unique per instance.

Source

pub fn trusted_proxies(self, proxies: TrustedProxies) -> Self

Resolve cache request scheme with the shared trusted-peer policy.

Args: proxies: Same immediate-peer policy used by other middleware.

Returns: Layer ignoring forwarded headers from untrusted peers.

Source

pub fn byte_limits(self, key: usize, hdrs: usize, encoded: usize) -> Self

Bound keys, stored header bytes and serialized response bytes.

Args: key: Maximum key bytes, including namespace and generation. hdrs: Maximum stored header-name/value bytes. encoded: Maximum versioned serialized response size.

Returns: Layer bypassing oversized entries without failing the origin.

Source

pub fn generation_ttl(self, ttl: Duration) -> Self

Set the lifetime of per-target generation markers.

Markers are created with this expiry (default DEFAULT_GENERATION_TTL, one hour) and stored representations never outlive it: a representation’s TTL is clamped to min(response ttl, generation_ttl). When a marker expires, the next request draws a fresh random generation, so earlier or in-flight fills become unreachable and read as safe misses.

Args: ttl: Marker lifetime. Zero means route caching is disabled: no request touches the backend, nothing is stored or invalidated, and responses carry x-cache: miss. A value above the backend’s portable limit is rejected by the backend, so every request bypasses the cache.

Note: max-age/s-maxage above ttl is capped to ttl (default one hour), as is default_ttl.

Returns: Configured layer. A custom Cache without set_if_absent_with_ttl makes the layer bypass storage.

Source

pub fn max_new_targets(self, max: u64) -> Self

Bound the metadata one namespace can create (default DEFAULT_MAX_NEW_TARGETS).

At most max new target markers are admitted per namespace in each generation_ttl window, counted when a representation is first stored for a target, and counted exactly: a marker that would exceed the budget is never visible. Once the window’s budget is spent, further new targets bypass the cache (x-cache: miss) until the next window; targets that already have a marker keep hitting, and the layer remembers the spent window locally, so those requests cost one backend read.

Windows are floor(clock / generation_ttl). RedisCache reads the Redis server clock inside the admission script (and expires the counter on that same clock after two windows), so every process sharing a namespace uses one window whatever its own clock says; MemoryCache uses its own clock. A marker lives one generation_ttl, so live markers were created in at most two consecutive windows: at most 2 * max per namespace. A stored representation can outlive its marker’s creation window by up to another generation_ttl, so representations come from at most three windows: at most 3 * max * v per namespace, where v is the number of request variants (method, Accept, Accept-Encoding) seen per target. Fills still in the origin when their marker ages out add at most one representation each.

Zero admits nothing: GET and HEAD requests make no backend calls. Successful writes still invalidate, which is one backend call each, because other processes sharing the namespace may have markers.

The counter lives in the backend, so the bound holds across processes sharing a namespace, provided the backend does not evict the counter. Third-party Cache adapters that do not override Cache::admit_marker use the generic sequence, whose window comes from each process’s own clock: processes whose clocks differ by a large fraction of generation_ttl can then each spend a full budget, up to the number of distinct clock phases times the bound above. A Cache without increment_with_expiry or set_if_absent_with_ttl cannot enforce the budget, so the layer stops storing (one warning).

Source

pub async fn invalidate_target(&self, req: &Request) -> Result<(), CacheError>

Invalidate every cached representation of one related target URI.

Args: req: Request identifying the target authority, scheme and URI.

Returns: Success after rotating its shared backend generation. Use this for application-specific list/detail dependencies after writes.

§Errors

Invalid context, oversized key or cache backend failure. A failed invalidation disables this layer to avoid stale local reuse.

Source

pub fn default_ttl(self, ttl: Duration) -> Self

Also store responses without Cache-Control: public, for ttl when they carry no max-age. Meant for a layer on a single route (see the type docs). A ttl of zero stores nothing.

Source

pub fn bypass_header(self, name: HeaderName) -> Self

Bypass the cache for requests carrying name (a credential header).

Source

pub fn max_body_bytes(self, bytes: u64) -> Self

Store only bodies of at most bytes (default DEFAULT_MAX_BODY_BYTES).

Trait Implementations§

Source§

impl<C: Clone> Clone for RouteCache<C>

Source§

fn clone(&self) -> RouteCache<C>

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

impl<C: Debug> Debug for RouteCache<C>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<C: Cache> Layer<BoxCloneSyncService<Request<Body>, Response<Body>, Infallible>> for RouteCache<C>

Source§

type Service = BoxCloneSyncService<Request<Body>, Response<Body>, Infallible>

The wrapped service
Source§

fn layer(&self, inner: BoxService) -> Self::Service

Wrap the given service with the middleware, returning a new service that has been decorated with the middleware.

Auto Trait Implementations§

§

impl<C> Freeze for RouteCache<C>

§

impl<C> RefUnwindSafe for RouteCache<C>
where C: RefUnwindSafe,

§

impl<C> Send for RouteCache<C>
where C: Sync + Send,

§

impl<C> Sync for RouteCache<C>
where C: Sync + Send,

§

impl<C> Unpin for RouteCache<C>

§

impl<C> UnsafeUnpin for RouteCache<C>

§

impl<C> UnwindSafe for RouteCache<C>
where C: RefUnwindSafe,

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
§

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

§

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
§

impl<T> Conv for T

§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
§

impl<T> FmtForward for T

§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

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

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> Instrument for T

§

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

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

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
§

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

§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

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

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<T> ServiceExt for T

§

fn compression(self) -> Compression<Self>
where Self: Sized,

Compresses response bodies. Read more
§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
§

fn override_request_header<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Insert a header into the request. Read more
§

fn append_request_header<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Append a header into the request. Read more
§

fn insert_request_header_if_not_present<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Insert a header into the request, if the header is not already present. Read more
§

fn override_response_header<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Insert a header into the response. Read more
§

fn append_response_header<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Append a header into the response. Read more
§

fn insert_response_header_if_not_present<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Insert a header into the response, if the header is not already present. Read more
§

fn set_request_id<M>( self, header_name: HeaderName, make_request_id: M, ) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Add request id header and extension. Read more
§

fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Add request id header and extension, using x-request-id as the header name. Read more
§

fn propagate_request_id( self, header_name: HeaderName, ) -> PropagateRequestId<Self>
where Self: Sized,

Propgate request ids from requests to responses. Read more
§

fn propagate_x_request_id(self) -> PropagateRequestId<Self>
where Self: Sized,

Propgate request ids from requests to responses, using x-request-id as the header name. Read more
§

fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>
where Self: Sized,

Intercept requests with over-sized payloads and convert them into 413 Payload Too Large responses. Read more
§

fn trim_trailing_slash(self) -> NormalizePath<Self>
where Self: Sized,

Remove trailing slashes from paths. Read more
§

fn append_trailing_slash(self) -> NormalizePath<Self>
where Self: Sized,

Append trailing slash to paths. Read more
§

impl<T> Tap for T

§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
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
§

impl<T> TryConv for T

§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. 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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

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