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 withCached::public). Everything else passes through. - Per route. Put the layer on one route with
MethodRouter::layerand setdefault_ttl; that route’s responses are stored without apublicmarker.
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’sAcceptandAccept-Encodingvalues, 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 containsauth,token,session,jwt,secret,api-key,apikeyoraccess-key, and any header added withRouteCache::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-Controldoes not containno-store,no-cacheorprivate,Varynames no header outside the key, and the body length is known and at mostRouteCache::max_body_bytes. Streaming bodies (server-sent events, file streams) pass through untouched. - On top of that, a response needs
Cache-Control: publicunlessdefault_ttlis set. - The entry lives for
s-maxage, elsemax-age, elsedefault_ttl. Apublicresponse 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: hitorx-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>
impl<C: Cache> RouteCache<C>
Sourcepub fn new(cache: C) -> Self
pub fn new(cache: C) -> Self
Cache GET/HEAD 200 responses marked Cache-Control: public in
cache.
Sourcepub fn namespace(self, namespace: impl Into<String>) -> Self
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.
Sourcepub fn trusted_proxies(self, proxies: TrustedProxies) -> Self
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.
Sourcepub fn byte_limits(self, key: usize, hdrs: usize, encoded: usize) -> Self
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.
Sourcepub fn generation_ttl(self, ttl: Duration) -> Self
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.
Sourcepub fn max_new_targets(self, max: u64) -> Self
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).
Sourcepub async fn invalidate_target(&self, req: &Request) -> Result<(), CacheError>
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.
Sourcepub fn default_ttl(self, ttl: Duration) -> Self
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.
Sourcepub fn bypass_header(self, name: HeaderName) -> Self
pub fn bypass_header(self, name: HeaderName) -> Self
Bypass the cache for requests carrying name (a credential header).
Sourcepub fn max_body_bytes(self, bytes: u64) -> Self
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>
impl<C: Clone> Clone for RouteCache<C>
Source§fn clone(&self) -> RouteCache<C>
fn clone(&self) -> RouteCache<C>
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl<C: Debug> Debug for RouteCache<C>
impl<C: Debug> Debug for RouteCache<C>
Source§impl<C: Cache> Layer<BoxCloneSyncService<Request<Body>, Response<Body>, Infallible>> for RouteCache<C>
impl<C: Cache> Layer<BoxCloneSyncService<Request<Body>, Response<Body>, Infallible>> for RouteCache<C>
Source§type Service = BoxCloneSyncService<Request<Body>, Response<Body>, Infallible>
type Service = BoxCloneSyncService<Request<Body>, Response<Body>, Infallible>
Source§fn layer(&self, inner: BoxService) -> Self::Service
fn layer(&self, inner: BoxService) -> Self::Service
Auto Trait Implementations§
impl<C> Freeze for RouteCache<C>
impl<C> RefUnwindSafe for RouteCache<C>where
C: RefUnwindSafe,
impl<C> Send for RouteCache<C>
impl<C> Sync for RouteCache<C>
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> 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,
§impl<T> Conv for T
impl<T> Conv for T
§impl<T> FmtForward for T
impl<T> FmtForward for T
§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.§fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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 Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
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) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
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
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
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
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
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
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.§impl<T> Pointable for T
impl<T> Pointable for T
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
§impl<T> ServiceExt for T
impl<T> ServiceExt for T
§fn compression(self) -> Compression<Self>where
Self: Sized,
fn compression(self) -> Compression<Self>where
Self: Sized,
§fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>where
Self: Sized,
fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>where
Self: Sized,
§fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>where
Self: Sized,
fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>where
Self: Sized,
§fn override_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
fn override_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
§fn append_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
fn append_request_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
§fn insert_request_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
fn insert_request_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetRequestHeader<Self, M>where
Self: Sized,
§fn override_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
fn override_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
§fn append_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
fn append_response_header<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
§fn insert_response_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
fn insert_response_header_if_not_present<M>(
self,
header_name: HeaderName,
make: M,
) -> SetResponseHeader<Self, M>where
Self: Sized,
§fn set_request_id<M>(
self,
header_name: HeaderName,
make_request_id: M,
) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
fn set_request_id<M>(
self,
header_name: HeaderName,
make_request_id: M,
) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
§fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>where
Self: Sized,
M: MakeRequestId,
x-request-id as the header name. Read more§fn propagate_request_id(
self,
header_name: HeaderName,
) -> PropagateRequestId<Self>where
Self: Sized,
fn propagate_request_id(
self,
header_name: HeaderName,
) -> PropagateRequestId<Self>where
Self: Sized,
§fn propagate_x_request_id(self) -> PropagateRequestId<Self>where
Self: Sized,
fn propagate_x_request_id(self) -> PropagateRequestId<Self>where
Self: Sized,
x-request-id as the header name. Read more§fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>where
Self: Sized,
fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>where
Self: Sized,
413 Payload Too Large responses. Read more§fn trim_trailing_slash(self) -> NormalizePath<Self>where
Self: Sized,
fn trim_trailing_slash(self) -> NormalizePath<Self>where
Self: Sized,
§fn append_trailing_slash(self) -> NormalizePath<Self>where
Self: Sized,
fn append_trailing_slash(self) -> NormalizePath<Self>where
Self: Sized,
§impl<T> Tap for T
impl<T> Tap for T
§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read more§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read more§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read more§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read more§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read more§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read more§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.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
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut() only in debug builds, and is erased in release
builds.§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.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
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut() only in debug builds, and is erased in release
builds.§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.