tower-etag-cache
A tower middleware for implementing ETag-based HTTP caching.
Quickstart
The const-lru-provider feature provides a const-lru-backed CacheProvider implementation that's ready to be used.
use ;
use ;
use ;
pub async
async
The ConstLruProvider calculates ETag as the base64-encoded blake3 hash of response bodies.
It keys entries by SimpleEtagCacheKey, a struct comprising the request URI + sorted Vec collections of header values for the Accept, Accept-Language, and Accept-Encoding request headers. This causes it to vary ETags based on these headers.
Since the current implementation loads the entire response body into memory to calculate the ETag, ConstLruProvider is not suitable for extremely large responses such as large files.
How This Works
The EtagCache tower service and EtagCacheLayer tower layer is created with an inner tower service + any type that implements the CacheProvider trait.
- comprises 2 tower services
- 1 that runs on incoming http requests to lookup ETags to check if a request's
If-None-Matchmatches an ETag in the cache - 1 that runs on outgoing http responses to calculate and save the ETag of the response
- 1 that runs on incoming http requests to lookup ETags to check if a request's
- has an associated cache key type that is used to key cache entries
- has an associated transform response body type that it transforms outgoing http response bodies into after the ETag calculation and saving procedure
When a http request comes in,
- If the service's passthrough_predicate indicates that the request should be passed through, the unmodified request is passed directly to the inner service and the response is directly returned to the client.
- Else the
CacheProvider's first ETag lookup service runs on the request. - If the service returns a cache hit, an empty HTTP 304 response is returned to the client with the relevant headers.
- Else the inner service runs on the unmodified request.
- If the service's passthrough_predicate indicates that the response should be passed through, the unmodified response is returned to the client.
- Else the
CacheProvider's second ETag calculating and saving service runs on the http response returned by the inner service. - The service transforms the response body and modifies the response headers to include the saved ETag and other relevant headers and returns it to the client.
PassthroughPredicate
The PassthroughPredicate trait controls when requests and responses should ignore the caching layer.
The provided DefaultPredicate is available for use with EtagCacheLayer::with_default_predicate and has the following behaviour:
requests:
- only
GETandHEADmethods are ran through the caching layer
responses:
- only
HTTP 2XXresponses, excluding204 No Content, are cached - only responses that dont already have the
ETagheader are cached - only responses that eiter have a missing, invalid, or non-zero
Content-Lengthheader are cached