Skip to main content

http_cache/
lib.rs

1#![forbid(unsafe_code, future_incompatible)]
2#![deny(
3    missing_docs,
4    missing_debug_implementations,
5    missing_copy_implementations,
6    nonstandard_style,
7    unused_qualifications,
8    unused_import_braces,
9    unused_extern_crates,
10    trivial_casts,
11    trivial_numeric_casts
12)]
13#![allow(clippy::doc_lazy_continuation)]
14#![cfg_attr(docsrs, feature(doc_cfg))]
15//! A caching middleware that follows HTTP caching rules, thanks to
16//! [`http-cache-semantics`](https://github.com/kornelski/rusty-http-cache-semantics).
17//! By default, it uses [`cacache`](https://github.com/zkat/cacache-rs) as the backend cache manager.
18//!
19//! This crate provides the core HTTP caching functionality that can be used to build
20//! caching middleware for various HTTP clients and server frameworks. It implements
21//! RFC 7234 HTTP caching semantics, supporting features like:
22//!
23//! - Automatic cache invalidation for unsafe HTTP methods (PUT, POST, DELETE, PATCH)
24//! - Respect for HTTP cache-control headers
25//! - Conditional requests (ETag, Last-Modified)
26//! - Multiple cache storage backends
27//! - Streaming response support
28//!
29//! ## Basic Usage
30//!
31//! The core types for building HTTP caches:
32//!
33//! ```rust
34//! # #[cfg(feature = "manager-cacache")]
35//! # fn main() {
36//! use http_cache::{CACacheManager, HttpCache, CacheMode, HttpCacheOptions};
37//!
38//! // Create a cache manager with disk storage
39//! let manager = CACacheManager::new("./cache".into(), true);
40//!
41//! // Create an HTTP cache with default behavior
42//! let cache = HttpCache {
43//!     mode: CacheMode::Default,
44//!     manager,
45//!     options: HttpCacheOptions::default(),
46//! };
47//! # }
48//! # #[cfg(not(feature = "manager-cacache"))]
49//! # fn main() {}
50//! ```
51//!
52//! ## Cache Modes
53//!
54//! Different cache modes provide different behaviors:
55//!
56//! ```rust
57//! # #[cfg(feature = "manager-cacache")]
58//! # fn main() {
59//! use http_cache::{CacheMode, HttpCache, CACacheManager, HttpCacheOptions};
60//!
61//! let manager = CACacheManager::new("./cache".into(), true);
62//!
63//! // Default mode: follows HTTP caching rules
64//! let default_cache = HttpCache {
65//!     mode: CacheMode::Default,
66//!     manager: manager.clone(),
67//!     options: HttpCacheOptions::default(),
68//! };
69//!
70//! // NoStore mode: never caches responses
71//! let no_store_cache = HttpCache {
72//!     mode: CacheMode::NoStore,
73//!     manager: manager.clone(),
74//!     options: HttpCacheOptions::default(),
75//! };
76//!
77//! // ForceCache mode: caches responses even if headers suggest otherwise
78//! let force_cache = HttpCache {
79//!     mode: CacheMode::ForceCache,
80//!     manager,
81//!     options: HttpCacheOptions::default(),
82//! };
83//! # }
84//! # #[cfg(not(feature = "manager-cacache"))]
85//! # fn main() {}
86//! ```
87//!
88//! ## Custom Cache Keys
89//!
90//! You can customize how cache keys are generated:
91//!
92//! ```rust
93//! # #[cfg(feature = "manager-cacache")]
94//! # fn main() {
95//! use http_cache::{HttpCacheOptions, CACacheManager, HttpCache, CacheMode};
96//! use std::sync::Arc;
97//! use http::request::Parts;
98//!
99//! let manager = CACacheManager::new("./cache".into(), true);
100//!
101//! let options = HttpCacheOptions {
102//!     cache_key: Some(Arc::new(|req: &Parts| {
103//!         // Custom cache key that includes query parameters
104//!         format!("{}:{}", req.method, req.uri)
105//!     })),
106//!     ..Default::default()
107//! };
108//!
109//! let cache = HttpCache {
110//!     mode: CacheMode::Default,
111//!     manager,
112//!     options,
113//! };
114//! # }
115//! # #[cfg(not(feature = "manager-cacache"))]
116//! # fn main() {}
117//! ```
118//!
119//! ## Default and Maximum TTL
120//!
121//! Set a time-to-live for responses that don't specify their own expiration, and cap how long
122//! any response is considered fresh. Neither removes entries from the cache: a response that is
123//! no longer fresh is revalidated, and limiting the cache's size is up to the cache manager.
124//!
125//! ```rust
126//! # #[cfg(feature = "manager-cacache")]
127//! # fn main() {
128//! use http_cache::{HttpCacheOptions, CACacheManager, HttpCache, CacheMode};
129//! use std::time::Duration;
130//!
131//! let manager = CACacheManager::new("./cache".into(), true);
132//!
133//! let options = HttpCacheOptions {
134//!     // Responses without `max-age` or `Expires` are fresh for 1 minute
135//!     default_ttl: Some(Duration::from_secs(60)),
136//!     // No response is fresh for longer than 5 minutes
137//!     max_ttl: Some(Duration::from_secs(300)),
138//!     ..Default::default()
139//! };
140//!
141//! let cache = HttpCache {
142//!     mode: CacheMode::Default,
143//!     manager,
144//!     options,
145//! };
146//! # }
147//! # #[cfg(not(feature = "manager-cacache"))]
148//! # fn main() {}
149//! ```
150//!
151//! ## Response-Based Cache Mode Override
152//!
153//! Override cache behavior based on the response you receive. This is useful for scenarios like
154//! forcing cache for successful responses even when headers say not to cache, or never caching
155//! error responses like rate limits:
156//!
157//! ```rust
158//! # #[cfg(feature = "manager-cacache")]
159//! # fn main() {
160//! use http_cache::{HttpCacheOptions, CACacheManager, HttpCache, CacheMode};
161//! use std::sync::Arc;
162//!
163//! let manager = CACacheManager::new("./cache".into(), true);
164//!
165//! let options = HttpCacheOptions {
166//!     response_cache_mode_fn: Some(Arc::new(|_request_parts, response| {
167//!         match response.status {
168//!             // Force cache successful responses even if headers say not to cache
169//!             200..=299 => Some(CacheMode::ForceCache),
170//!             // Never cache rate-limited responses
171//!             429 => Some(CacheMode::NoStore),
172//!             // Use default behavior for everything else
173//!             _ => None,
174//!         }
175//!     })),
176//!     ..Default::default()
177//! };
178//!
179//! let cache = HttpCache {
180//!     mode: CacheMode::Default,
181//!     manager,
182//!     options,
183//! };
184//! # }
185//! # #[cfg(not(feature = "manager-cacache"))]
186//! # fn main() {}
187//! ```
188//!
189//! ## Content-Type Based Caching
190//!
191//! You can implement selective caching based on response content types using `response_cache_mode_fn`.
192//! This is useful when you only want to cache certain types of content:
193//!
194//! ```rust
195//! # #[cfg(feature = "manager-cacache")]
196//! # fn main() {
197//! use http_cache::{HttpCacheOptions, CACacheManager, HttpCache, CacheMode};
198//! use std::sync::Arc;
199//!
200//! let manager = CACacheManager::new("./cache".into(), true);
201//!
202//! let options = HttpCacheOptions {
203//!     response_cache_mode_fn: Some(Arc::new(|_request_parts, response| {
204//!         // Check the Content-Type header to decide caching behavior
205//!         if let Some(content_type) = response.headers.get("content-type") {
206//!             match content_type.as_str() {
207//!                 // Cache JSON APIs aggressively
208//!                 ct if ct.starts_with("application/json") => Some(CacheMode::ForceCache),
209//!                 // Cache images with default rules
210//!                 ct if ct.starts_with("image/") => Some(CacheMode::Default),
211//!                 // Cache static assets
212//!                 ct if ct.starts_with("text/css") => Some(CacheMode::ForceCache),
213//!                 ct if ct.starts_with("application/javascript") => Some(CacheMode::ForceCache),
214//!                 // Don't cache HTML pages (dynamic content)
215//!                 ct if ct.starts_with("text/html") => Some(CacheMode::NoStore),
216//!                 // Don't cache unknown content types
217//!                 _ => Some(CacheMode::NoStore),
218//!             }
219//!         } else {
220//!             // No Content-Type header - don't cache
221//!             Some(CacheMode::NoStore)
222//!         }
223//!     })),
224//!     ..Default::default()
225//! };
226//!
227//! let cache = HttpCache {
228//!     mode: CacheMode::Default, // This gets overridden by response_cache_mode_fn
229//!     manager,
230//!     options,
231//! };
232//! # }
233//! # #[cfg(not(feature = "manager-cacache"))]
234//! # fn main() {}
235//! ```
236//!
237//! ## Streaming Support
238//!
239//! For handling large responses without full buffering, use the `StreamingManager`:
240//!
241//! ```rust
242//! # #[cfg(feature = "streaming")]
243//! # {
244//! use http_cache::StreamingBody;
245//! use bytes::Bytes;
246//! use http_body::Body;
247//! use http_body_util::Full;
248//!
249//! // StreamingManager uses redb (metadata) + tokio::fs (bodies) with a moka
250//! // in-memory hot cache for disk-backed streaming.
251//! // Create with: StreamingManager::with_temp_dir(1000).await.unwrap()
252//!
253//! // StreamingBody can handle both buffered and streaming scenarios
254//! let body: StreamingBody<Full<Bytes>> = StreamingBody::buffered(Bytes::from("cached content"));
255//! println!("Body size: {:?}", body.size_hint());
256//! # }
257//! ```
258//!
259//! **Note**: Streaming support requires the `StreamingManager` with the `streaming` feature.
260//! Other cache managers (CACacheManager, MokaManager, QuickManager) do not support streaming
261//! and will buffer response bodies in memory.
262//!
263//! ## Features
264//!
265//! The following features are available. By default `manager-cacache` is enabled.
266//!
267//! - `manager-cacache` (default): enable [cacache](https://github.com/zkat/cacache-rs),
268//! a disk cache, backend manager. Uses tokio runtime.
269//! - `manager-moka` (disabled): enable [moka](https://github.com/moka-rs/moka),
270//! an in-memory cache, backend manager.
271//! - `manager-foyer` (disabled): enable [foyer](https://github.com/foyer-rs/foyer),
272//! a hybrid in-memory + disk cache, backend manager. Uses tokio runtime.
273//! - `http-headers-compat` (disabled): enable backwards compatibility for deserializing cached
274//! responses from older versions that used single-value headers. Enable this if you need to read
275//! cache entries created by older versions of http-cache.
276//! - `streaming` (disabled): enable the `StreamingManager` for streaming cache
277//!   support. Uses redb for metadata, raw `tokio::fs` files for bodies, and
278//!   moka as an in-memory hot cache of metadata.
279//! - `with-http-types` (disabled): enable [http-types](https://github.com/http-rs/http-types)
280//! type conversion support
281//!
282//! ### URL Implementation Features
283//!
284//! Exactly one URL implementation must be enabled. These features are **mutually exclusive**:
285//!
286//! - `url-standard` (default): uses the [url](https://github.com/servo/rust-url) crate.
287//!   Note: This brings in the `idna` crate which has a Unicode license.
288//! - `url-ada` (disabled): uses [ada-url](https://github.com/ada-url/rust) for WHATWG-compliant
289//!   URL parsing without the Unicode/IDNA license dependency.
290//!
291//! If you need to avoid the Unicode license, use `url-ada`:
292//!
293//! ```toml
294//! [dependencies]
295//! http-cache = { version = "1.0", default-features = false, features = ["manager-cacache", "url-ada"] }
296//! ```
297//!
298//! ### Legacy bincode features (deprecated)
299//!
300//! These features are deprecated due to [RUSTSEC-2025-0141](https://rustsec.org/advisories/RUSTSEC-2025-0141)
301//! and will be removed in the next major version:
302//!
303//! - `manager-cacache-bincode`: cacache with bincode serialization
304//! - `manager-moka-bincode`: moka with bincode serialization
305//!
306//! **Note**: Only `StreamingManager` (via the `streaming` feature) provides streaming support.
307//! Other managers will buffer response bodies in memory even when used with `StreamingManager`.
308//!
309//! ## Integration
310//!
311//! This crate is designed to be used as a foundation for HTTP client and server middleware.
312//! See the companion crates for specific integrations:
313//!
314//! - [`http-cache-reqwest`](https://docs.rs/http-cache-reqwest) for reqwest client middleware
315//! - [`http-cache-surf`](https://docs.rs/http-cache-surf) for surf client middleware  
316//! - [`http-cache-tower`](https://docs.rs/http-cache-tower) for tower service middleware
317
318// URL feature validation - exactly one URL implementation must be enabled
319#[cfg(all(feature = "url-standard", feature = "url-ada"))]
320compile_error!("features `url-standard` and `url-ada` are mutually exclusive");
321
322#[cfg(not(any(feature = "url-standard", feature = "url-ada")))]
323compile_error!("either feature `url-standard` or `url-ada` must be enabled");
324
325mod body;
326mod error;
327mod managers;
328
329#[cfg(feature = "rate-limiting")]
330pub mod rate_limiting;
331
332use std::{
333    collections::HashMap,
334    convert::TryFrom,
335    fmt::{self, Debug},
336    future::Future,
337    str::FromStr,
338    sync::Arc,
339    time::{Duration, SystemTime},
340};
341
342use http::{
343    HeaderValue, Response, StatusCode,
344    header::{CACHE_CONTROL, EXPIRES, PRAGMA},
345    request, response,
346};
347use http_cache_semantics::{AfterResponse, BeforeRequest, CachePolicy};
348use serde::{Deserialize, Deserializer, Serialize, Serializer};
349
350// URL type alias - allows users to choose between `url` (default) and `ada-url` crates
351// When using `url-ada` feature, this becomes `ada_url::Url`
352#[cfg(feature = "url-ada")]
353pub use ada_url::Url;
354#[cfg(not(feature = "url-ada"))]
355pub use url::Url;
356
357// ============================================================================
358// URL Helper Functions
359// ============================================================================
360// These functions abstract away API differences between `url` and `ada-url` crates.
361// Internal code should use these helpers instead of calling URL methods directly.
362
363/// Parse a URL string into a `Url` type.
364///
365/// This helper abstracts the parsing API difference between `url` and `ada-url`:
366/// - `url` crate: `Url::parse(s)` returns `Result<Url, ParseError>`
367/// - `ada-url` crate: `Url::parse(s, None)` returns `Result<Url, ParseUrlError>`
368#[inline]
369pub fn url_parse(s: &str) -> Result<Url> {
370    #[cfg(feature = "url-ada")]
371    {
372        Url::parse(s, None).map_err(|e| -> BoxError { e.to_string().into() })
373    }
374    #[cfg(not(feature = "url-ada"))]
375    {
376        Url::parse(s).map_err(|e| -> BoxError { Box::new(e) })
377    }
378}
379
380/// Set the path component of a URL.
381///
382/// API differences:
383/// - `url` crate: `url.set_path(path)`
384/// - `ada-url` crate: `url.set_pathname(Some(path))`
385#[inline]
386pub fn url_set_path(url: &mut Url, path: &str) {
387    #[cfg(feature = "url-ada")]
388    {
389        let _ = url.set_pathname(Some(path));
390    }
391    #[cfg(not(feature = "url-ada"))]
392    {
393        url.set_path(path);
394    }
395}
396
397/// Set the query component of a URL.
398///
399/// API differences:
400/// - `url` crate: `url.set_query(Some(query))` or `url.set_query(None)`
401/// - `ada-url` crate: `url.set_search(Some(query))` or `url.set_search(None)`
402#[inline]
403pub fn url_set_query(url: &mut Url, query: Option<&str>) {
404    #[cfg(feature = "url-ada")]
405    {
406        url.set_search(query);
407    }
408    #[cfg(not(feature = "url-ada"))]
409    {
410        url.set_query(query);
411    }
412}
413
414/// Get the hostname of a URL as a string.
415///
416/// API differences:
417/// - `url` crate: `url.host_str()` returns `Option<&str>`
418/// - `ada-url` crate: `url.hostname()` returns `&str` (empty string if no host)
419#[inline]
420#[must_use]
421pub fn url_hostname(url: &Url) -> Option<&str> {
422    #[cfg(feature = "url-ada")]
423    {
424        let hostname = url.hostname();
425        if hostname.is_empty() { None } else { Some(hostname) }
426    }
427    #[cfg(not(feature = "url-ada"))]
428    {
429        url.host_str()
430    }
431}
432
433/// Get the host of a URL as a string for display purposes (e.g., warning headers).
434///
435/// This returns the host portion as a string, or "unknown" if not available.
436/// Used in places like HTTP Warning headers where we need a displayable host value.
437#[inline]
438#[must_use]
439pub fn url_host_str(url: &Url) -> String {
440    #[cfg(feature = "url-ada")]
441    {
442        let hostname = url.hostname();
443        if hostname.is_empty() {
444            "unknown".to_string()
445        } else {
446            hostname.to_string()
447        }
448    }
449    #[cfg(not(feature = "url-ada"))]
450    {
451        url.host()
452            .map(|h| h.to_string())
453            .unwrap_or_else(|| "unknown".to_string())
454    }
455}
456
457pub use body::StreamingBody;
458pub use error::{
459    BadHeader, BadRequest, BadVersion, BoxError, ClientStreamingError,
460    HttpCacheError, HttpCacheResult, Result, StreamingError,
461};
462
463#[cfg(any(
464    feature = "manager-cacache",
465    feature = "manager-cacache-bincode"
466))]
467pub use managers::cacache::CACacheManager;
468
469#[cfg(feature = "streaming")]
470pub use managers::streaming_cache::{
471    StreamingManager, StreamingManagerOptions,
472};
473
474#[cfg(any(feature = "manager-moka", feature = "manager-moka-bincode"))]
475pub use managers::moka::MokaManager;
476
477#[cfg(feature = "manager-foyer")]
478pub use managers::foyer::FoyerManager;
479
480#[cfg(feature = "manager-redb")]
481pub use managers::redb::RedbManager;
482
483#[cfg(feature = "rate-limiting")]
484pub use rate_limiting::{
485    CacheAwareRateLimiter, DirectRateLimiter, DomainRateLimiter,
486};
487
488#[cfg(feature = "rate-limiting")]
489pub use rate_limiting::Quota;
490
491// Exposing the moka cache for convenience, renaming to avoid naming conflicts
492#[cfg(any(feature = "manager-moka", feature = "manager-moka-bincode"))]
493#[cfg_attr(docsrs, doc(cfg(feature = "manager-moka")))]
494pub use moka::future::{Cache as MokaCache, CacheBuilder as MokaCacheBuilder};
495
496// Custom headers used to indicate cache status (hit or miss)
497/// `x-cache` header: Value will be HIT if the response was served from cache, MISS if not
498pub const XCACHE: &str = "x-cache";
499/// `x-cache-lookup` header: Value will be HIT if a response existed in cache, MISS if not
500pub const XCACHELOOKUP: &str = "x-cache-lookup";
501/// `warning` header: HTTP warning header as per RFC 7234
502const WARNING: &str = "warning";
503
504/// Represents a basic cache status
505/// Used in the custom headers `x-cache` and `x-cache-lookup`
506#[derive(Debug, Copy, Clone)]
507pub enum HitOrMiss {
508    /// Yes, there was a hit
509    HIT,
510    /// No, there was no hit
511    MISS,
512}
513
514impl fmt::Display for HitOrMiss {
515    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
516        match self {
517            Self::HIT => write!(f, "HIT"),
518            Self::MISS => write!(f, "MISS"),
519        }
520    }
521}
522
523/// Represents an HTTP version
524#[derive(Debug, Copy, Clone, PartialEq, Eq, Deserialize, Serialize)]
525#[non_exhaustive]
526pub enum HttpVersion {
527    /// HTTP Version 0.9
528    #[serde(rename = "HTTP/0.9")]
529    Http09,
530    /// HTTP Version 1.0
531    #[serde(rename = "HTTP/1.0")]
532    Http10,
533    /// HTTP Version 1.1
534    #[serde(rename = "HTTP/1.1")]
535    Http11,
536    /// HTTP Version 2.0
537    #[serde(rename = "HTTP/2.0")]
538    H2,
539    /// HTTP Version 3.0
540    #[serde(rename = "HTTP/3.0")]
541    H3,
542}
543
544impl fmt::Display for HttpVersion {
545    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
546        match *self {
547            HttpVersion::Http09 => write!(f, "HTTP/0.9"),
548            HttpVersion::Http10 => write!(f, "HTTP/1.0"),
549            HttpVersion::Http11 => write!(f, "HTTP/1.1"),
550            HttpVersion::H2 => write!(f, "HTTP/2.0"),
551            HttpVersion::H3 => write!(f, "HTTP/3.0"),
552        }
553    }
554}
555
556/// Extract a URL from HTTP request parts for cache key generation
557///
558/// This function reconstructs the full URL from the request parts, handling both
559/// HTTP and HTTPS schemes based on the connection type or explicit headers.
560fn extract_url_from_request_parts(parts: &request::Parts) -> Result<Url> {
561    // First check if the URI is already absolute
562    if let Some(_scheme) = parts.uri.scheme() {
563        // URI is absolute, use it directly
564        return url_parse(&parts.uri.to_string())
565            .map_err(|_| -> BoxError { BadHeader.into() });
566    }
567
568    // Get the host header
569    let host = parts
570        .headers
571        .get("host")
572        .ok_or(BadHeader)?
573        .to_str()
574        .map_err(|_| BadHeader)?;
575
576    // Determine scheme based on host and headers
577    let scheme = determine_scheme(host, &parts.headers)?;
578
579    // Create base URL using the URL helper for cross-crate compatibility
580    let mut base_url = url_parse(&format!("{}://{}/", scheme, host))
581        .map_err(|_| -> BoxError { BadHeader.into() })?;
582
583    // Set the path and query from the URI using helpers
584    if let Some(path_and_query) = parts.uri.path_and_query() {
585        url_set_path(&mut base_url, path_and_query.path());
586        if let Some(query) = path_and_query.query() {
587            url_set_query(&mut base_url, Some(query));
588        }
589    }
590
591    Ok(base_url)
592}
593
594/// Determine the appropriate scheme for URL construction
595fn determine_scheme(host: &str, headers: &http::HeaderMap) -> Result<String> {
596    // Check for explicit protocol forwarding header first
597    if let Some(forwarded_proto) = headers.get("x-forwarded-proto") {
598        let proto = forwarded_proto.to_str().map_err(|_| BadHeader)?;
599        return match proto {
600            "http" | "https" => Ok(proto.to_string()),
601            _ => Ok("https".to_string()), // Default to secure for unknown protocols
602        };
603    }
604
605    // Check if this looks like a local development host
606    if host.starts_with("localhost") || host.starts_with("127.0.0.1") {
607        Ok("http".to_string())
608    } else {
609        Ok("https".to_string()) // Default to secure for all other hosts
610    }
611}
612
613/// Represents HTTP headers in either legacy or modern format.
614///
615/// Values are `String`s, so header values that are not valid UTF-8 cannot
616/// be represented and are skipped during conversion from `http::HeaderMap`.
617#[derive(Debug, Clone)]
618pub enum HttpHeaders {
619    /// Modern header representation - allows multiple values per key
620    Modern(HashMap<String, Vec<String>>),
621    /// Legacy header representation - kept for backward compatibility with deserialization
622    #[cfg(feature = "http-headers-compat")]
623    Legacy(HashMap<String, String>),
624}
625
626// Serialize directly as the inner HashMap (no enum variant wrapper)
627// This ensures compatibility: serialized data is just the raw HashMap
628impl Serialize for HttpHeaders {
629    fn serialize<S>(
630        &self,
631        serializer: S,
632    ) -> std::result::Result<S::Ok, S::Error>
633    where
634        S: Serializer,
635    {
636        #[cfg(feature = "http-headers-compat")]
637        {
638            // Always serialize as Legacy format when compat is enabled
639            match self {
640                HttpHeaders::Modern(modern) => {
641                    // Convert Modern to Legacy format by joining values
642                    let legacy: HashMap<String, String> = modern
643                        .iter()
644                        .map(|(k, v)| (k.clone(), v.join(", ")))
645                        .collect();
646                    legacy.serialize(serializer)
647                }
648                HttpHeaders::Legacy(legacy) => legacy.serialize(serializer),
649            }
650        }
651
652        #[cfg(not(feature = "http-headers-compat"))]
653        {
654            match self {
655                HttpHeaders::Modern(modern) => modern.serialize(serializer),
656            }
657        }
658    }
659}
660
661// Deserialize directly as HashMap based on feature flag
662// With http-headers-compat: reads HashMap<String, String> (legacy alpha.2 format)
663// Without http-headers-compat: reads HashMap<String, Vec<String>> (modern format)
664impl<'de> Deserialize<'de> for HttpHeaders {
665    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
666    where
667        D: Deserializer<'de>,
668    {
669        #[cfg(feature = "http-headers-compat")]
670        {
671            let legacy = HashMap::<String, String>::deserialize(deserializer)?;
672            Ok(HttpHeaders::Legacy(legacy))
673        }
674
675        #[cfg(not(feature = "http-headers-compat"))]
676        {
677            let modern =
678                HashMap::<String, Vec<String>>::deserialize(deserializer)?;
679            Ok(HttpHeaders::Modern(modern))
680        }
681    }
682}
683
684impl HttpHeaders {
685    /// Creates a new empty HttpHeaders in modern format
686    pub fn new() -> Self {
687        HttpHeaders::Modern(HashMap::new())
688    }
689
690    /// Inserts a header key-value pair, replacing any existing values for that key
691    /// Keys are normalized to lowercase per RFC 7230
692    pub fn insert(&mut self, key: String, value: String) {
693        let normalized_key = key.to_ascii_lowercase();
694        match self {
695            #[cfg(feature = "http-headers-compat")]
696            HttpHeaders::Legacy(legacy) => {
697                legacy.insert(normalized_key, value);
698            }
699            HttpHeaders::Modern(modern) => {
700                // Replace existing values with a new single-element vec
701                modern.insert(normalized_key, vec![value]);
702            }
703        }
704    }
705
706    /// Appends a header value, preserving existing values for the same key
707    /// Keys are normalized to lowercase per RFC 7230
708    pub fn append(&mut self, key: String, value: String) {
709        let normalized_key = key.to_ascii_lowercase();
710        match self {
711            #[cfg(feature = "http-headers-compat")]
712            HttpHeaders::Legacy(legacy) => {
713                // Legacy format doesn't support multi-value, fall back to insert
714                legacy.insert(normalized_key, value);
715            }
716            HttpHeaders::Modern(modern) => {
717                modern
718                    .entry(normalized_key)
719                    .or_insert_with(Vec::new)
720                    .push(value);
721            }
722        }
723    }
724
725    /// Retrieves the first value for a given header key
726    /// Keys are normalized to lowercase per RFC 7230
727    pub fn get(&self, key: &str) -> Option<&String> {
728        let normalized_key = key.to_ascii_lowercase();
729        match self {
730            #[cfg(feature = "http-headers-compat")]
731            HttpHeaders::Legacy(legacy) => legacy.get(&normalized_key),
732            HttpHeaders::Modern(modern) => {
733                modern.get(&normalized_key).and_then(|vals| vals.first())
734            }
735        }
736    }
737
738    /// Removes a header key and its associated values
739    /// Keys are normalized to lowercase per RFC 7230
740    pub fn remove(&mut self, key: &str) {
741        let normalized_key = key.to_ascii_lowercase();
742        match self {
743            #[cfg(feature = "http-headers-compat")]
744            HttpHeaders::Legacy(legacy) => {
745                legacy.remove(&normalized_key);
746            }
747            HttpHeaders::Modern(modern) => {
748                modern.remove(&normalized_key);
749            }
750        }
751    }
752
753    /// Checks if a header key exists
754    /// Keys are normalized to lowercase per RFC 7230
755    pub fn contains_key(&self, key: &str) -> bool {
756        let normalized_key = key.to_ascii_lowercase();
757        match self {
758            #[cfg(feature = "http-headers-compat")]
759            HttpHeaders::Legacy(legacy) => legacy.contains_key(&normalized_key),
760            HttpHeaders::Modern(modern) => modern.contains_key(&normalized_key),
761        }
762    }
763
764    /// Returns an iterator over the header key-value pairs
765    pub fn iter(&self) -> HttpHeadersIterator<'_> {
766        match self {
767            #[cfg(feature = "http-headers-compat")]
768            HttpHeaders::Legacy(legacy) => {
769                HttpHeadersIterator { inner: legacy.iter().collect(), index: 0 }
770            }
771            HttpHeaders::Modern(modern) => HttpHeadersIterator {
772                inner: modern
773                    .iter()
774                    .flat_map(|(k, vals)| vals.iter().map(move |v| (k, v)))
775                    .collect(),
776                index: 0,
777            },
778        }
779    }
780}
781
782impl From<&http::HeaderMap> for HttpHeaders {
783    fn from(headers: &http::HeaderMap) -> Self {
784        let mut modern_headers = HashMap::new();
785
786        // headers.keys() already yields each unique name exactly once
787        for name in headers.keys() {
788            let values: Vec<String> = headers
789                .get_all(name)
790                .iter()
791                .filter_map(|v| v.to_str().ok())
792                .map(|s| s.to_string())
793                .collect();
794
795            if !values.is_empty() {
796                modern_headers.insert(name.to_string(), values);
797            }
798        }
799
800        HttpHeaders::Modern(modern_headers)
801    }
802}
803
804impl From<HttpHeaders> for HashMap<String, Vec<String>> {
805    fn from(headers: HttpHeaders) -> Self {
806        match headers {
807            #[cfg(feature = "http-headers-compat")]
808            HttpHeaders::Legacy(legacy) => {
809                legacy.into_iter().map(|(k, v)| (k, vec![v])).collect()
810            }
811            HttpHeaders::Modern(modern) => modern,
812        }
813    }
814}
815
816impl Default for HttpHeaders {
817    fn default() -> Self {
818        HttpHeaders::new()
819    }
820}
821
822impl IntoIterator for HttpHeaders {
823    type Item = (String, String);
824    type IntoIter = HttpHeadersIntoIterator;
825
826    fn into_iter(self) -> Self::IntoIter {
827        HttpHeadersIntoIterator {
828            inner: match self {
829                #[cfg(feature = "http-headers-compat")]
830                HttpHeaders::Legacy(legacy) => legacy.into_iter().collect(),
831                HttpHeaders::Modern(modern) => modern
832                    .into_iter()
833                    .flat_map(|(k, vals)| {
834                        vals.into_iter().map(move |v| (k.clone(), v))
835                    })
836                    .collect(),
837            },
838            index: 0,
839        }
840    }
841}
842
843/// Iterator for HttpHeaders
844#[derive(Debug)]
845pub struct HttpHeadersIntoIterator {
846    inner: Vec<(String, String)>,
847    index: usize,
848}
849
850impl Iterator for HttpHeadersIntoIterator {
851    type Item = (String, String);
852
853    fn next(&mut self) -> Option<Self::Item> {
854        if self.index < self.inner.len() {
855            let item = self.inner[self.index].clone();
856            self.index += 1;
857            Some(item)
858        } else {
859            None
860        }
861    }
862}
863
864impl<'a> IntoIterator for &'a HttpHeaders {
865    type Item = (&'a String, &'a String);
866    type IntoIter = HttpHeadersIterator<'a>;
867
868    fn into_iter(self) -> Self::IntoIter {
869        self.iter()
870    }
871}
872
873/// Iterator for HttpHeaders references
874#[derive(Debug)]
875pub struct HttpHeadersIterator<'a> {
876    inner: Vec<(&'a String, &'a String)>,
877    index: usize,
878}
879
880impl<'a> Iterator for HttpHeadersIterator<'a> {
881    type Item = (&'a String, &'a String);
882
883    fn next(&mut self) -> Option<Self::Item> {
884        if self.index < self.inner.len() {
885            let item = self.inner[self.index];
886            self.index += 1;
887            Some(item)
888        } else {
889            None
890        }
891    }
892}
893
894/// A basic generic type that represents an HTTP response
895#[derive(Debug, Clone, Deserialize, Serialize)]
896pub struct HttpResponse {
897    /// HTTP response body
898    pub body: Vec<u8>,
899    /// HTTP response headers
900    pub headers: HttpHeaders,
901    /// HTTP response status code
902    pub status: u16,
903    /// HTTP response url
904    pub url: Url,
905    /// HTTP response version
906    pub version: HttpVersion,
907    /// Metadata
908    #[serde(default)]
909    pub metadata: Option<Vec<u8>>,
910}
911
912impl HttpResponse {
913    /// Returns `http::response::Parts`
914    pub fn parts(&self) -> Result<response::Parts> {
915        let mut converted =
916            response::Builder::new().status(self.status).body(())?;
917        {
918            let headers = converted.headers_mut();
919            for header in &self.headers {
920                headers.append(
921                    http::header::HeaderName::from_str(header.0.as_str())?,
922                    HeaderValue::from_str(header.1.as_str())?,
923                );
924            }
925        }
926        Ok(converted.into_parts().0)
927    }
928
929    /// Returns the status code of the warning header if present
930    #[must_use]
931    fn warning_code(&self) -> Option<usize> {
932        self.headers.get(WARNING).and_then(|hdr| {
933            hdr.as_str().chars().take(3).collect::<String>().parse().ok()
934        })
935    }
936
937    /// Adds a warning header to a response
938    fn add_warning(&mut self, url: &Url, code: usize, message: &str) {
939        // warning    = "warning" ":" 1#warning-value
940        // warning-value = warn-code SP warn-agent SP warn-text [SP warn-date]
941        // warn-code  = 3DIGIT
942        // warn-agent = ( host [ ":" port ] ) | pseudonym
943        //                 ; the name or pseudonym of the server adding
944        //                 ; the warning header, for use in debugging
945        // warn-text  = quoted-string
946        // warn-date  = <"> HTTP-date <">
947        // (https://tools.ietf.org/html/rfc2616#section-14.46)
948        let host = url_host_str(url);
949        // Escape message to prevent header injection and ensure valid HTTP format
950        let escaped_message =
951            message.replace('"', "'").replace(['\n', '\r'], " ");
952        self.headers.insert(
953            WARNING.to_string(),
954            format!(
955                "{} {} \"{}\" \"{}\"",
956                code,
957                host,
958                escaped_message,
959                httpdate::fmt_http_date(SystemTime::now())
960            ),
961        );
962    }
963
964    /// Removes a warning header from a response
965    fn remove_warning(&mut self) {
966        self.headers.remove(WARNING);
967    }
968
969    /// Update the headers from `http::response::Parts`
970    pub fn update_headers(&mut self, parts: &response::Parts) -> Result<()> {
971        // Clear-then-append per key. The From conversion keeps a key only
972        // when at least one of its values converts to a string, so headers
973        // whose values cannot be represented survive untouched.
974        let incoming: HashMap<String, Vec<String>> =
975            HttpHeaders::from(&parts.headers).into();
976        for (name, values) in incoming {
977            self.headers.remove(name.as_str());
978            for value in values {
979                self.headers.append(name.clone(), value);
980            }
981        }
982        Ok(())
983    }
984
985    /// Adds the custom `x-cache` header to the response
986    pub fn cache_status(&mut self, hit_or_miss: HitOrMiss) {
987        self.headers.insert(XCACHE.to_string(), hit_or_miss.to_string());
988    }
989
990    /// Adds the custom `x-cache-lookup` header to the response
991    pub fn cache_lookup_status(&mut self, hit_or_miss: HitOrMiss) {
992        self.headers.insert(XCACHELOOKUP.to_string(), hit_or_miss.to_string());
993    }
994}
995
996/// A trait providing methods for storing, reading, and removing cache records.
997pub trait CacheManager: Send + Sync + 'static {
998    /// Attempts to pull a cached response and related policy from cache.
999    fn get(
1000        &self,
1001        cache_key: &str,
1002    ) -> impl Future<Output = Result<Option<(HttpResponse, CachePolicy)>>> + Send;
1003    /// Attempts to cache a response and related policy.
1004    fn put(
1005        &self,
1006        cache_key: String,
1007        res: HttpResponse,
1008        policy: CachePolicy,
1009    ) -> impl Future<Output = Result<HttpResponse>> + Send;
1010    /// Attempts to remove a record from cache.
1011    fn delete(
1012        &self,
1013        cache_key: &str,
1014    ) -> impl Future<Output = Result<()>> + Send;
1015}
1016
1017/// A streaming cache manager that supports streaming request/response bodies
1018/// without buffering them in memory. This is ideal for large responses.
1019pub trait StreamingCacheManager: Send + Sync + 'static {
1020    /// The body type used by this cache manager
1021    type Body: http_body::Body + Send + 'static;
1022
1023    /// Attempts to pull a cached response and related policy from cache with streaming body.
1024    fn get(
1025        &self,
1026        cache_key: &str,
1027    ) -> impl Future<
1028        Output = Result<Option<(Response<Self::Body>, CachePolicy)>>,
1029    > + Send
1030    where
1031        <Self::Body as http_body::Body>::Data: Send,
1032        <Self::Body as http_body::Body>::Error:
1033            Into<StreamingError> + Send + Sync + 'static;
1034
1035    /// Attempts to cache a response with a streaming body and related policy.
1036    ///
1037    /// After `put()` resolves, the cache entry is durable and visible
1038    /// at-or-after full consumption of the returned body. The current
1039    /// implementation commits before returning; callers must not rely on
1040    /// the stronger property.
1041    fn put<B>(
1042        &self,
1043        cache_key: String,
1044        response: Response<B>,
1045        policy: CachePolicy,
1046        request_url: Url,
1047        metadata: Option<Vec<u8>>,
1048    ) -> impl Future<Output = Result<Response<Self::Body>>> + Send
1049    where
1050        B: http_body::Body + Send + 'static,
1051        B::Data: Send,
1052        B::Error: Into<StreamingError>,
1053        <Self::Body as http_body::Body>::Data: Send,
1054        <Self::Body as http_body::Body>::Error:
1055            Into<StreamingError> + Send + Sync + 'static;
1056
1057    /// Update the stored headers, cache policy, and user metadata for an
1058    /// existing entry WITHOUT touching the body file. Used by 304
1059    /// revalidation, where the body is known-unchanged.
1060    ///
1061    /// If `token` is `Some`, the update is applied only when the stored
1062    /// entry still matches that identity; `Ok(false)` means the entry no
1063    /// longer exists or was concurrently replaced — callers should serve
1064    /// the response and skip re-caching.
1065    fn update_metadata(
1066        &self,
1067        cache_key: &str,
1068        headers: &http::HeaderMap,
1069        policy: CachePolicy,
1070        user_metadata: Option<Vec<u8>>,
1071        token: Option<&CacheEntryToken>,
1072    ) -> impl Future<Output = Result<bool>> + Send;
1073
1074    /// Converts a generic body to the manager's body type for non-cacheable responses.
1075    /// This is called when a response should not be cached but still needs to be returned
1076    /// with the correct body type.
1077    fn convert_body<B>(
1078        &self,
1079        response: Response<B>,
1080    ) -> impl Future<Output = Result<Response<Self::Body>>> + Send
1081    where
1082        B: http_body::Body + Send + 'static,
1083        B::Data: Send,
1084        B::Error: Into<StreamingError>,
1085        <Self::Body as http_body::Body>::Data: Send,
1086        <Self::Body as http_body::Body>::Error:
1087            Into<StreamingError> + Send + Sync + 'static;
1088
1089    /// Attempts to remove a record from cache.
1090    fn delete(
1091        &self,
1092        cache_key: &str,
1093    ) -> impl Future<Output = Result<()>> + Send;
1094
1095    /// Creates an empty body of the manager's body type.
1096    /// Used for returning 504 Gateway Timeout responses on OnlyIfCached cache misses.
1097    fn empty_body(&self) -> Self::Body;
1098
1099    /// Convert the manager's body type to a reqwest-compatible bytes stream.
1100    /// This enables efficient streaming without collecting the entire body.
1101    #[cfg(feature = "streaming")]
1102    fn body_to_bytes_stream(
1103        body: Self::Body,
1104    ) -> impl futures_util::Stream<
1105        Item = std::result::Result<
1106            bytes::Bytes,
1107            Box<dyn std::error::Error + Send + Sync>,
1108        >,
1109    > + Send
1110    where
1111        <Self::Body as http_body::Body>::Data: Send,
1112        <Self::Body as http_body::Body>::Error: Send + Sync + 'static;
1113}
1114
1115/// Describes the functionality required for interfacing with HTTP client middleware
1116pub trait Middleware: Send {
1117    /// Allows the cache mode to be overridden.
1118    ///
1119    /// This overrides any cache mode set in the configuration, including cache_mode_fn.
1120    fn overridden_cache_mode(&self) -> Option<CacheMode> {
1121        None
1122    }
1123    /// Determines if the request method is either GET or HEAD
1124    fn is_method_get_head(&self) -> bool;
1125    /// Attempts to update the request headers with the passed `http::request::Parts`
1126    fn update_headers(&mut self, parts: &request::Parts) -> Result<()>;
1127    /// Attempts to force the "no-cache" directive on the request
1128    fn force_no_cache(&mut self) -> Result<()>;
1129    /// Attempts to construct `http::request::Parts` from the request
1130    fn parts(&self) -> Result<request::Parts>;
1131    /// Attempts to determine the requested url
1132    fn url(&self) -> Result<Url>;
1133    /// Attempts to fetch an upstream resource and return an [`HttpResponse`]
1134    fn remote_fetch(
1135        &mut self,
1136    ) -> impl Future<Output = Result<HttpResponse>> + Send;
1137}
1138
1139/// An interface for HTTP caching that works with composable middleware patterns
1140/// like Tower. This trait separates the concerns of request analysis, cache lookup,
1141/// and response processing into discrete steps.
1142pub trait HttpCacheInterface<B = Vec<u8>>: Send + Sync {
1143    /// Analyze a request to determine cache behavior
1144    fn analyze_request(
1145        &self,
1146        parts: &request::Parts,
1147        mode_override: Option<CacheMode>,
1148    ) -> Result<CacheAnalysis>;
1149
1150    /// Look up a cached response for the given cache key
1151    #[allow(async_fn_in_trait)]
1152    async fn lookup_cached_response(
1153        &self,
1154        key: &str,
1155    ) -> Result<Option<(HttpResponse, CachePolicy)>>;
1156
1157    /// Process a fresh response from upstream and potentially cache it
1158    #[allow(async_fn_in_trait)]
1159    async fn process_response(
1160        &self,
1161        analysis: CacheAnalysis,
1162        response: Response<B>,
1163        metadata: Option<Vec<u8>>,
1164    ) -> Result<Response<B>>;
1165
1166    /// Update request headers for conditional requests (e.g., If-None-Match)
1167    fn prepare_conditional_request(
1168        &self,
1169        parts: &mut request::Parts,
1170        cached_response: &HttpResponse,
1171        policy: &CachePolicy,
1172    ) -> Result<()>;
1173
1174    /// Handle a 304 Not Modified response by returning the cached response
1175    #[allow(async_fn_in_trait)]
1176    async fn handle_not_modified(
1177        &self,
1178        cached_response: HttpResponse,
1179        fresh_parts: &response::Parts,
1180    ) -> Result<HttpResponse>;
1181}
1182
1183/// Streaming version of the HTTP cache interface that supports streaming request/response bodies
1184/// without buffering them in memory. This is ideal for large responses or when memory usage
1185/// is a concern.
1186pub trait HttpCacheStreamInterface: Send + Sync {
1187    /// The body type used by this cache implementation
1188    type Body: http_body::Body + Send + 'static;
1189
1190    /// Analyze a request to determine cache behavior
1191    fn analyze_request(
1192        &self,
1193        parts: &request::Parts,
1194        mode_override: Option<CacheMode>,
1195    ) -> Result<CacheAnalysis>;
1196
1197    /// Look up a cached response for the given cache key, returning a streaming body
1198    #[allow(async_fn_in_trait)]
1199    async fn lookup_cached_response(
1200        &self,
1201        key: &str,
1202    ) -> Result<Option<(Response<Self::Body>, CachePolicy)>>
1203    where
1204        <Self::Body as http_body::Body>::Data: Send,
1205        <Self::Body as http_body::Body>::Error:
1206            Into<StreamingError> + Send + Sync + 'static;
1207
1208    /// Process a fresh response from upstream and potentially cache it with streaming support
1209    #[allow(async_fn_in_trait)]
1210    async fn process_response<B>(
1211        &self,
1212        analysis: CacheAnalysis,
1213        response: Response<B>,
1214        metadata: Option<Vec<u8>>,
1215    ) -> Result<Response<Self::Body>>
1216    where
1217        B: http_body::Body + Send + 'static,
1218        B::Data: Send,
1219        B::Error: Into<StreamingError>,
1220        <Self::Body as http_body::Body>::Data: Send,
1221        <Self::Body as http_body::Body>::Error:
1222            Into<StreamingError> + Send + Sync + 'static;
1223
1224    /// Update request headers for conditional requests (e.g., If-None-Match)
1225    fn prepare_conditional_request(
1226        &self,
1227        parts: &mut request::Parts,
1228        cached_response: &Response<Self::Body>,
1229        policy: &CachePolicy,
1230    ) -> Result<()>;
1231
1232    /// Handle a 304 Not Modified response by returning the cached response
1233    #[allow(async_fn_in_trait)]
1234    async fn handle_not_modified(
1235        &self,
1236        cached_response: Response<Self::Body>,
1237        fresh_parts: &response::Parts,
1238    ) -> Result<Response<Self::Body>>
1239    where
1240        <Self::Body as http_body::Body>::Data: Send,
1241        <Self::Body as http_body::Body>::Error:
1242            Into<StreamingError> + Send + Sync + 'static;
1243}
1244
1245/// Analysis result for a request, containing cache key and caching decisions
1246#[derive(Debug, Clone)]
1247pub struct CacheAnalysis {
1248    /// The cache key for this request
1249    pub cache_key: String,
1250    /// Whether this request should be cached
1251    pub should_cache: bool,
1252    /// The effective cache mode for this request
1253    pub cache_mode: CacheMode,
1254    /// Keys to bust from cache before processing
1255    pub cache_bust_keys: Vec<String>,
1256    /// The request parts for policy creation
1257    pub request_parts: request::Parts,
1258    /// Whether this is a GET or HEAD request
1259    pub is_get_head: bool,
1260}
1261
1262/// Describes the type of fetch to perform when the streaming cache
1263/// orchestrator needs to make a network request.
1264///
1265/// The streaming `run` method accepts a callback `FnOnce(FetchRequest) -> Fut`
1266/// rather than an `impl Middleware`, so this enum tells the caller whether to
1267/// issue a fresh request or a conditional (revalidation) request.
1268#[derive(Debug)]
1269pub enum FetchRequest {
1270    /// A fresh fetch (cache miss or forced).
1271    Fresh,
1272    /// A fresh fetch where the caller should add `cache-control: no-cache`
1273    /// to the outgoing request.  Used for [`CacheMode::NoCache`] to signal
1274    /// upstream caches that they must revalidate.
1275    FreshNoCache,
1276    /// A conditional fetch for revalidation.  The contained
1277    /// [`request::Parts`] carry the conditional headers (e.g.
1278    /// `If-None-Match`, `If-Modified-Since`) that should be merged into
1279    /// the outgoing request before sending it.  Callers should replace
1280    /// existing headers of the same name (insert, not append).
1281    Conditional(Box<request::Parts>),
1282}
1283
1284/// Cache mode determines how the HTTP cache behaves for requests.
1285///
1286/// These modes are similar to [make-fetch-happen cache options](https://github.com/npm/make-fetch-happen#--optscache)
1287/// and provide fine-grained control over caching behavior.
1288///
1289/// # Examples
1290///
1291/// ```rust
1292/// # #[cfg(feature = "manager-cacache")]
1293/// # fn main() {
1294/// use http_cache::{CacheMode, HttpCache, CACacheManager, HttpCacheOptions};
1295///
1296/// let manager = CACacheManager::new("./cache".into(), true);
1297///
1298/// // Use different cache modes for different scenarios
1299/// let default_cache = HttpCache {
1300///     mode: CacheMode::Default,        // Standard HTTP caching rules
1301///     manager: manager.clone(),
1302///     options: HttpCacheOptions::default(),
1303/// };
1304///
1305/// let force_cache = HttpCache {
1306///     mode: CacheMode::ForceCache,     // Cache everything, ignore staleness
1307///     manager: manager.clone(),
1308///     options: HttpCacheOptions::default(),
1309/// };
1310///
1311/// let no_cache = HttpCache {
1312///     mode: CacheMode::NoStore,        // Never cache anything
1313///     manager,
1314///     options: HttpCacheOptions::default(),
1315/// };
1316/// # }
1317/// # #[cfg(not(feature = "manager-cacache"))]
1318/// # fn main() {}
1319/// ```
1320#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1321pub enum CacheMode {
1322    /// Standard HTTP caching behavior (recommended for most use cases).
1323    ///
1324    /// This mode:
1325    /// - Checks the cache for fresh responses and uses them
1326    /// - Makes conditional requests for stale responses (revalidation)
1327    /// - Makes normal requests when no cached response exists
1328    /// - Updates the cache with new responses
1329    /// - Falls back to stale responses if revalidation fails
1330    ///
1331    /// This is the most common mode and follows HTTP caching standards closely.
1332    #[default]
1333    Default,
1334
1335    /// Completely bypasses the cache.
1336    ///
1337    /// This mode:
1338    /// - Never reads from the cache
1339    /// - Never writes to the cache
1340    /// - Always makes fresh network requests
1341    ///
1342    /// Use this when you need to ensure every request goes to the origin server.
1343    NoStore,
1344
1345    /// Bypasses cache on request but updates cache with response.
1346    ///
1347    /// This mode:
1348    /// - Ignores any cached responses
1349    /// - Always makes a fresh network request
1350    /// - Updates the cache with the response
1351    ///
1352    /// Equivalent to a "hard refresh" - useful when you know the cache is stale.
1353    Reload,
1354
1355    /// Always revalidates cached responses.
1356    ///
1357    /// This mode:
1358    /// - Sends `Cache-Control: no-cache` on cacheable requests, even on a cache miss
1359    /// - Makes conditional requests if a cached response exists
1360    /// - Makes unconditional requests if no cached response exists
1361    /// - Updates the cache with responses
1362    ///
1363    /// The request directive asks intermediary caches to validate stored responses
1364    /// with the origin server before reusing them ([RFC 9111 §5.2.1.4]).
1365    /// This uses `no-cache` on both hits and misses, replacing any existing
1366    /// `Cache-Control` value. This differs from [Fetch's header generation], which
1367    /// adds `max-age=0` when `Cache-Control` is absent.
1368    ///
1369    /// [RFC 9111 §5.2.1.4]: https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.1.4
1370    /// [Fetch's header generation]: https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
1371    ///
1372    /// Use this when you want to ensure content freshness while still benefiting
1373    /// from conditional requests (304 Not Modified responses).
1374    NoCache,
1375
1376    /// Uses cached responses regardless of staleness.
1377    ///
1378    /// This mode:
1379    /// - Uses any cached response, even if stale
1380    /// - Makes network requests only when no cached response exists
1381    /// - Updates the cache with new responses
1382    ///
1383    /// Useful for offline scenarios or when performance is more important than freshness.
1384    ForceCache,
1385
1386    /// Only serves from cache, never makes network requests.
1387    ///
1388    /// This mode:
1389    /// - Uses any cached response, even if stale
1390    /// - Returns an error if no cached response exists
1391    /// - Never makes network requests
1392    ///
1393    /// Use this for offline-only scenarios or when you want to guarantee
1394    /// no network traffic.
1395    OnlyIfCached,
1396
1397    /// Ignores HTTP caching rules and caches everything.
1398    ///
1399    /// This mode:
1400    /// - Caches all 200 responses regardless of cache-control headers
1401    /// - Uses cached responses regardless of staleness
1402    /// - Makes network requests when no cached response exists
1403    ///
1404    /// Use this when you want aggressive caching and don't want to respect
1405    /// server cache directives.
1406    IgnoreRules,
1407}
1408
1409impl TryFrom<http::Version> for HttpVersion {
1410    type Error = BoxError;
1411
1412    fn try_from(value: http::Version) -> Result<Self> {
1413        Ok(match value {
1414            http::Version::HTTP_09 => Self::Http09,
1415            http::Version::HTTP_10 => Self::Http10,
1416            http::Version::HTTP_11 => Self::Http11,
1417            http::Version::HTTP_2 => Self::H2,
1418            http::Version::HTTP_3 => Self::H3,
1419            _ => return Err(Box::new(BadVersion)),
1420        })
1421    }
1422}
1423
1424impl From<HttpVersion> for http::Version {
1425    fn from(value: HttpVersion) -> Self {
1426        match value {
1427            HttpVersion::Http09 => Self::HTTP_09,
1428            HttpVersion::Http10 => Self::HTTP_10,
1429            HttpVersion::Http11 => Self::HTTP_11,
1430            HttpVersion::H2 => Self::HTTP_2,
1431            HttpVersion::H3 => Self::HTTP_3,
1432        }
1433    }
1434}
1435
1436#[cfg(feature = "http-types")]
1437impl TryFrom<http_types::Version> for HttpVersion {
1438    type Error = BoxError;
1439
1440    fn try_from(value: http_types::Version) -> Result<Self> {
1441        Ok(match value {
1442            http_types::Version::Http0_9 => Self::Http09,
1443            http_types::Version::Http1_0 => Self::Http10,
1444            http_types::Version::Http1_1 => Self::Http11,
1445            http_types::Version::Http2_0 => Self::H2,
1446            http_types::Version::Http3_0 => Self::H3,
1447            _ => return Err(Box::new(BadVersion)),
1448        })
1449    }
1450}
1451
1452#[cfg(feature = "http-types")]
1453impl From<HttpVersion> for http_types::Version {
1454    fn from(value: HttpVersion) -> Self {
1455        match value {
1456            HttpVersion::Http09 => Self::Http0_9,
1457            HttpVersion::Http10 => Self::Http1_0,
1458            HttpVersion::Http11 => Self::Http1_1,
1459            HttpVersion::H2 => Self::Http2_0,
1460            HttpVersion::H3 => Self::Http3_0,
1461        }
1462    }
1463}
1464
1465/// Options struct provided by
1466/// [`http-cache-semantics`](https://github.com/kornelski/rusty-http-cache-semantics).
1467pub use http_cache_semantics::CacheOptions;
1468
1469/// A closure that takes [`http::request::Parts`] and returns a [`String`].
1470/// By default, the cache key is a combination of the request method and uri with a colon in between.
1471pub type CacheKey = Arc<dyn Fn(&request::Parts) -> String + Send + Sync>;
1472
1473/// A closure that takes [`http::request::Parts`] and returns a [`CacheMode`]
1474pub type CacheModeFn = Arc<dyn Fn(&request::Parts) -> CacheMode + Send + Sync>;
1475
1476/// A closure that takes [`http::request::Parts`], [`HttpResponse`] and returns a [`CacheMode`] to override caching behavior based on the response
1477pub type ResponseCacheModeFn = Arc<
1478    dyn Fn(&request::Parts, &HttpResponse) -> Option<CacheMode> + Send + Sync,
1479>;
1480
1481/// A closure that takes [`http::request::Parts`], [`Option<CacheKey>`], the default cache key ([`&str`]) and returns [`Vec<String>`] of keys to bust the cache for.
1482/// An empty vector means that no cache busting will be performed.
1483pub type CacheBust = Arc<
1484    dyn Fn(&request::Parts, &Option<CacheKey>, &str) -> Vec<String>
1485        + Send
1486        + Sync,
1487>;
1488
1489/// Type alias for metadata stored alongside cached responses.
1490/// Users are responsible for serialization/deserialization of this data.
1491pub type HttpCacheMetadata = Vec<u8>;
1492
1493/// A closure that takes [`http::request::Parts`] and [`http::response::Parts`] and returns optional metadata to store with the cached response.
1494/// This allows middleware to compute and store additional information alongside cached responses.
1495pub type MetadataProvider = Arc<
1496    dyn Fn(&request::Parts, &response::Parts) -> Option<HttpCacheMetadata>
1497        + Send
1498        + Sync,
1499>;
1500
1501/// A closure that takes a mutable reference to [`HttpResponse`] and modifies it before caching.
1502pub type ModifyResponse = Arc<dyn Fn(&mut HttpResponse) + Send + Sync>;
1503
1504/// Configuration options for customizing HTTP cache behavior on a per-request basis.
1505///
1506/// This struct allows you to override default caching behavior for individual requests
1507/// by providing custom cache options, cache keys, cache modes, and cache busting logic.
1508///
1509/// # Examples
1510///
1511/// ## Basic Custom Cache Key
1512/// ```rust
1513/// use http_cache::{HttpCacheOptions, CacheKey};
1514/// use http::request::Parts;
1515/// use std::sync::Arc;
1516///
1517/// let options = HttpCacheOptions {
1518///     cache_key: Some(Arc::new(|parts: &Parts| {
1519///         format!("custom:{}:{}", parts.method, parts.uri.path())
1520///     })),
1521///     ..Default::default()
1522/// };
1523/// ```
1524///
1525/// ## Custom Cache Mode per Request
1526/// ```rust
1527/// use http_cache::{HttpCacheOptions, CacheMode, CacheModeFn};
1528/// use http::request::Parts;
1529/// use std::sync::Arc;
1530///
1531/// let options = HttpCacheOptions {
1532///     cache_mode_fn: Some(Arc::new(|parts: &Parts| {
1533///         if parts.headers.contains_key("x-no-cache") {
1534///             CacheMode::NoStore
1535///         } else {
1536///             CacheMode::Default
1537///         }
1538///     })),
1539///     ..Default::default()
1540/// };
1541/// ```
1542///
1543/// ## Response-Based Cache Mode Override
1544/// ```rust
1545/// use http_cache::{HttpCacheOptions, ResponseCacheModeFn, CacheMode};
1546/// use http::request::Parts;
1547/// use http_cache::HttpResponse;
1548/// use std::sync::Arc;
1549///
1550/// let options = HttpCacheOptions {
1551///     response_cache_mode_fn: Some(Arc::new(|_parts: &Parts, response: &HttpResponse| {
1552///         // Force cache 2xx responses even if headers say not to cache
1553///         if response.status >= 200 && response.status < 300 {
1554///             Some(CacheMode::ForceCache)
1555///         } else if response.status == 429 { // Rate limited
1556///             Some(CacheMode::NoStore) // Don't cache rate limit responses
1557///         } else {
1558///             None // Use default behavior
1559///         }
1560///     })),
1561///     ..Default::default()
1562/// };
1563/// ```
1564///
1565/// ## Content-Type Based Cache Mode Override
1566/// ```rust
1567/// use http_cache::{HttpCacheOptions, ResponseCacheModeFn, CacheMode};
1568/// use http::request::Parts;
1569/// use http_cache::HttpResponse;
1570/// use std::sync::Arc;
1571///
1572/// let options = HttpCacheOptions {
1573///     response_cache_mode_fn: Some(Arc::new(|_parts: &Parts, response: &HttpResponse| {
1574///         // Cache different content types with different strategies
1575///         if let Some(content_type) = response.headers.get("content-type") {
1576///             match content_type.as_str() {
1577///                 ct if ct.starts_with("application/json") => Some(CacheMode::ForceCache),
1578///                 ct if ct.starts_with("image/") => Some(CacheMode::Default),
1579///                 ct if ct.starts_with("text/html") => Some(CacheMode::NoStore),
1580///                 _ => None, // Use default behavior for other types
1581///             }
1582///         } else {
1583///             Some(CacheMode::NoStore) // No content-type = don't cache
1584///         }
1585///     })),
1586///     ..Default::default()
1587/// };
1588/// ```
1589///
1590/// ## Cache Busting for Related Resources
1591/// ```rust
1592/// use http_cache::{HttpCacheOptions, CacheBust, CacheKey};
1593/// use http::request::Parts;
1594/// use std::sync::Arc;
1595///
1596/// let options = HttpCacheOptions {
1597///     cache_bust: Some(Arc::new(|parts: &Parts, _cache_key: &Option<CacheKey>, _uri: &str| {
1598///         if parts.method == "POST" && parts.uri.path().starts_with("/api/users") {
1599///             vec![
1600///                 "GET:/api/users".to_string(),
1601///                 "GET:/api/users/list".to_string(),
1602///             ]
1603///         } else {
1604///             vec![]
1605///         }
1606///     })),
1607///     ..Default::default()
1608/// };
1609/// ```
1610///
1611/// ## Storing Metadata with Cached Responses
1612/// ```rust
1613/// use http_cache::{HttpCacheOptions, MetadataProvider};
1614/// use http::{request, response};
1615/// use std::sync::Arc;
1616///
1617/// let options = HttpCacheOptions {
1618///     metadata_provider: Some(Arc::new(|request_parts: &request::Parts, response_parts: &response::Parts| {
1619///         // Store computed information with the cached response
1620///         let content_type = response_parts
1621///             .headers
1622///             .get("content-type")
1623///             .and_then(|v| v.to_str().ok())
1624///             .unwrap_or("unknown");
1625///
1626///         // Return serialized metadata (users handle serialization)
1627///         Some(format!("path={};content-type={}", request_parts.uri.path(), content_type).into_bytes())
1628///     })),
1629///     ..Default::default()
1630/// };
1631/// ```
1632#[derive(Clone)]
1633pub struct HttpCacheOptions {
1634    /// Override the default cache options.
1635    pub cache_options: Option<CacheOptions>,
1636    /// Override the default cache key generator.
1637    ///
1638    /// **Note:** Custom closures receive only `&request::Parts` and do not receive
1639    /// the `override_method` parameter used for cache invalidation. This means
1640    /// RFC 7234 section 4.4 cross-method invalidation (e.g., a POST invalidating
1641    /// cached GET/HEAD entries) will not work correctly unless your closure
1642    /// differentiates keys by HTTP method.
1643    pub cache_key: Option<CacheKey>,
1644    /// Override the default cache mode.
1645    pub cache_mode_fn: Option<CacheModeFn>,
1646    /// Override cache behavior based on the response received.
1647    /// This function is called after receiving a response and can override
1648    /// the cache mode for that specific response. Returning `None` means
1649    /// use the default cache mode. This allows fine-grained control over
1650    /// caching behavior based on response status, headers, or content.
1651    pub response_cache_mode_fn: Option<ResponseCacheModeFn>,
1652    /// Bust the caches of the returned keys.
1653    pub cache_bust: Option<CacheBust>,
1654    /// Modifies the response before storing it in the cache.
1655    pub modify_response: Option<ModifyResponse>,
1656    /// Determines if the cache status headers should be added to the response.
1657    pub cache_status_headers: bool,
1658    /// Time-to-live for responses that don't specify their own expiration,
1659    /// truncated to whole seconds.
1660    ///
1661    /// Applies when a response has no `max-age` directive and no `Expires`
1662    /// header (nor `s-maxage` in a shared cache). It replaces the heuristic
1663    /// based on `Last-Modified`, see [`CacheOptions::cache_heuristic`].
1664    ///
1665    /// Doesn't make responses cacheable that are not allowed to be stored,
1666    /// and `no-cache` responses are still revalidated on every use.
1667    /// An invalid or past `Expires` header marks a response as already stale,
1668    /// so this doesn't apply to those either.
1669    ///
1670    /// When `None`, responses without an explicit expiration only use the heuristic.
1671    pub default_ttl: Option<Duration>,
1672    /// Maximum time-to-live for cached responses, truncated to whole seconds.
1673    ///
1674    /// When set, this caps any longer lifetime specified by the server, as well
1675    /// as heuristic lifetimes and `default_ttl`. Shorter lifetimes are kept.
1676    /// It does not make responses without an expiration cacheable, use
1677    /// `default_ttl` for that.
1678    pub max_ttl: Option<Duration>,
1679    /// Rate limiter that applies only on cache misses.
1680    /// When enabled, requests that result in cache hits are returned immediately,
1681    /// while cache misses are rate limited before making network requests.
1682    /// This provides the optimal behavior for web scrapers and similar applications.
1683    #[cfg(feature = "rate-limiting")]
1684    pub rate_limiter: Option<Arc<dyn CacheAwareRateLimiter>>,
1685    /// Optional callback to provide metadata to store alongside cached responses.
1686    /// The callback receives request and response parts and can return metadata bytes.
1687    /// This is useful for storing computed information that should be associated with
1688    /// cached responses without recomputation on cache hits.
1689    pub metadata_provider: Option<MetadataProvider>,
1690}
1691
1692impl Default for HttpCacheOptions {
1693    fn default() -> Self {
1694        Self {
1695            cache_options: None,
1696            cache_key: None,
1697            cache_mode_fn: None,
1698            response_cache_mode_fn: None,
1699            cache_bust: None,
1700            modify_response: None,
1701            cache_status_headers: true,
1702            default_ttl: None,
1703            max_ttl: None,
1704            #[cfg(feature = "rate-limiting")]
1705            rate_limiter: None,
1706            metadata_provider: None,
1707        }
1708    }
1709}
1710
1711impl Debug for HttpCacheOptions {
1712    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1713        #[cfg(feature = "rate-limiting")]
1714        {
1715            f.debug_struct("HttpCacheOptions")
1716                .field("cache_options", &self.cache_options)
1717                .field("cache_key", &"Fn(&request::Parts) -> String")
1718                .field("cache_mode_fn", &"Fn(&request::Parts) -> CacheMode")
1719                .field(
1720                    "response_cache_mode_fn",
1721                    &"Fn(&request::Parts, &HttpResponse) -> Option<CacheMode>",
1722                )
1723                .field("cache_bust", &"Fn(&request::Parts) -> Vec<String>")
1724                .field("modify_response", &"Fn(&mut ModifyResponse)")
1725                .field("cache_status_headers", &self.cache_status_headers)
1726                .field("default_ttl", &self.default_ttl)
1727                .field("max_ttl", &self.max_ttl)
1728                .field("rate_limiter", &"Option<CacheAwareRateLimiter>")
1729                .field(
1730                    "metadata_provider",
1731                    &"Fn(&request::Parts, &response::Parts) -> Option<Vec<u8>>",
1732                )
1733                .finish()
1734        }
1735
1736        #[cfg(not(feature = "rate-limiting"))]
1737        {
1738            f.debug_struct("HttpCacheOptions")
1739                .field("cache_options", &self.cache_options)
1740                .field("cache_key", &"Fn(&request::Parts) -> String")
1741                .field("cache_mode_fn", &"Fn(&request::Parts) -> CacheMode")
1742                .field(
1743                    "response_cache_mode_fn",
1744                    &"Fn(&request::Parts, &HttpResponse) -> Option<CacheMode>",
1745                )
1746                .field("cache_bust", &"Fn(&request::Parts) -> Vec<String>")
1747                .field("modify_response", &"Fn(&mut ModifyResponse)")
1748                .field("cache_status_headers", &self.cache_status_headers)
1749                .field("default_ttl", &self.default_ttl)
1750                .field("max_ttl", &self.max_ttl)
1751                .field(
1752                    "metadata_provider",
1753                    &"Fn(&request::Parts, &response::Parts) -> Option<Vec<u8>>",
1754                )
1755                .finish()
1756        }
1757    }
1758}
1759
1760impl HttpCacheOptions {
1761    fn create_cache_key(
1762        &self,
1763        parts: &request::Parts,
1764        override_method: Option<&str>,
1765    ) -> String {
1766        if let Some(cache_key) = &self.cache_key {
1767            cache_key(parts)
1768        } else {
1769            format!(
1770                "{}:{}",
1771                override_method.unwrap_or_else(|| parts.method.as_str()),
1772                parts.uri
1773            )
1774        }
1775    }
1776
1777    /// Helper function for other crates to generate cache keys for invalidation
1778    /// This ensures consistent cache key generation across all implementations
1779    pub fn create_cache_key_for_invalidation(
1780        &self,
1781        parts: &request::Parts,
1782        method_override: &str,
1783    ) -> String {
1784        self.create_cache_key(parts, Some(method_override))
1785    }
1786
1787    /// Converts HttpResponse to http::Response with the given body type
1788    pub fn http_response_to_response<B>(
1789        http_response: &HttpResponse,
1790        body: B,
1791    ) -> Result<Response<B>> {
1792        let mut response_builder = Response::builder()
1793            .status(http_response.status)
1794            .version(http_response.version.into());
1795
1796        for (name, value) in &http_response.headers {
1797            if let (Ok(header_name), Ok(header_value)) =
1798                (name.parse::<http::HeaderName>(), value.parse::<HeaderValue>())
1799            {
1800                response_builder =
1801                    response_builder.header(header_name, header_value);
1802            }
1803        }
1804
1805        Ok(response_builder.body(body)?)
1806    }
1807
1808    /// Converts response parts to HttpResponse format for cache mode evaluation
1809    fn parts_to_http_response(
1810        &self,
1811        parts: &response::Parts,
1812        request_parts: &request::Parts,
1813        metadata: Option<Vec<u8>>,
1814    ) -> Result<HttpResponse> {
1815        Ok(HttpResponse {
1816            body: vec![], // We don't need the full body for cache mode decision
1817            headers: (&parts.headers).into(),
1818            status: parts.status.as_u16(),
1819            url: extract_url_from_request_parts(request_parts)?,
1820            version: parts.version.try_into()?,
1821            metadata,
1822        })
1823    }
1824
1825    /// Evaluates response-based cache mode override
1826    fn evaluate_response_cache_mode(
1827        &self,
1828        request_parts: &request::Parts,
1829        http_response: &HttpResponse,
1830        original_mode: CacheMode,
1831    ) -> CacheMode {
1832        if let Some(response_cache_mode_fn) = &self.response_cache_mode_fn
1833            && let Some(override_mode) =
1834                response_cache_mode_fn(request_parts, http_response)
1835        {
1836            return override_mode;
1837        }
1838        original_mode
1839    }
1840
1841    /// Generates metadata for a response using the metadata_provider callback if configured
1842    pub fn generate_metadata(
1843        &self,
1844        request_parts: &request::Parts,
1845        response_parts: &response::Parts,
1846    ) -> Option<HttpCacheMetadata> {
1847        self.metadata_provider
1848            .as_ref()
1849            .and_then(|provider| provider(request_parts, response_parts))
1850    }
1851
1852    /// Modifies the response before caching if a modifier function is provided
1853    pub fn modify_response_before_caching(&self, response: &mut HttpResponse) {
1854        if let Some(modify_response) = &self.modify_response {
1855            modify_response(response);
1856        }
1857    }
1858
1859    /// Creates a cache policy for the given request and response
1860    fn create_cache_policy(
1861        &self,
1862        request_parts: &request::Parts,
1863        response_parts: &response::Parts,
1864    ) -> CachePolicy {
1865        let cache_options = self.cache_options.unwrap_or_default();
1866        let now = SystemTime::now();
1867        let new_policy = |response_parts: &response::Parts| {
1868            CachePolicy::new_options(
1869                request_parts,
1870                response_parts,
1871                now,
1872                cache_options,
1873            )
1874        };
1875
1876        // `default_ttl` stands in for the heuristic freshness lifetime, so
1877        // it only applies when the server gave no explicit expiration.
1878        let mut policy = match self.default_ttl {
1879            Some(default_ttl)
1880                if !has_explicit_expiration(
1881                    response_parts,
1882                    cache_options.shared,
1883                ) =>
1884            {
1885                new_policy(&with_max_age(response_parts, default_ttl))
1886            }
1887            _ => new_policy(response_parts),
1888        };
1889
1890        // `max_ttl` caps the freshness lifetime however it was determined:
1891        // `max-age`, `s-maxage`, `Expires`, heuristics or `default_ttl`.
1892        // The lifetime counts from the response's age, like `max-age` does.
1893        if let Some(max_ttl) = self.max_ttl
1894            && policy.time_to_live(now) + policy.age(now) > max_ttl
1895        {
1896            policy = new_policy(&with_max_age(response_parts, max_ttl));
1897        }
1898
1899        policy
1900    }
1901
1902    /// Determines if a response should be cached based on cache mode and HTTP semantics
1903    fn should_cache_response(
1904        &self,
1905        effective_cache_mode: CacheMode,
1906        http_response: &HttpResponse,
1907        is_get_head: bool,
1908        policy: &CachePolicy,
1909    ) -> bool {
1910        // HTTP status codes that are cacheable by default (RFC 7234)
1911        let is_cacheable_status = matches!(
1912            http_response.status,
1913            200 | 203 | 204 | 206 | 300 | 301 | 404 | 405 | 410 | 414 | 501
1914        );
1915
1916        if is_cacheable_status {
1917            match effective_cache_mode {
1918                CacheMode::ForceCache => is_get_head,
1919                CacheMode::IgnoreRules => true,
1920                CacheMode::NoStore => false,
1921                _ => is_get_head && policy.is_storable(),
1922            }
1923        } else {
1924            false
1925        }
1926    }
1927
1928    /// Common request analysis logic shared between streaming and non-streaming implementations
1929    fn analyze_request_internal(
1930        &self,
1931        parts: &request::Parts,
1932        mode_override: Option<CacheMode>,
1933        default_mode: CacheMode,
1934    ) -> Result<CacheAnalysis> {
1935        let effective_mode = mode_override
1936            .or_else(|| self.cache_mode_fn.as_ref().map(|f| f(parts)))
1937            .unwrap_or(default_mode);
1938
1939        let is_get_head = parts.method == "GET" || parts.method == "HEAD";
1940        let should_cache = effective_mode == CacheMode::IgnoreRules
1941            || (is_get_head && effective_mode != CacheMode::NoStore);
1942
1943        let cache_key = self.create_cache_key(parts, None);
1944
1945        let cache_bust_keys = if let Some(cache_bust) = &self.cache_bust {
1946            cache_bust(parts, &self.cache_key, &cache_key)
1947        } else {
1948            Vec::new()
1949        };
1950
1951        Ok(CacheAnalysis {
1952            cache_key,
1953            should_cache,
1954            cache_mode: effective_mode,
1955            cache_bust_keys,
1956            request_parts: parts.clone(),
1957            is_get_head,
1958        })
1959    }
1960}
1961
1962/// Caches requests according to http spec.
1963#[derive(Debug, Clone)]
1964pub struct HttpCache<T: CacheManager> {
1965    /// Determines the manager behavior.
1966    pub mode: CacheMode,
1967    /// Manager instance that implements the [`CacheManager`] trait.
1968    /// By default, a manager implementation with [`cacache`](https://github.com/zkat/cacache-rs)
1969    /// as the backend has been provided, see [`CACacheManager`].
1970    pub manager: T,
1971    /// Override the default cache options.
1972    pub options: HttpCacheOptions,
1973}
1974
1975/// Wrapper for user metadata stored in response extensions during cache reads.
1976/// Used to preserve metadata through 304 re-cache operations so that
1977/// `StreamingCacheManager::put` receives the original metadata instead of
1978/// regenerating it (which may produce different or empty results).
1979#[derive(Debug, Clone)]
1980pub(crate) struct CachedUserMetadata(pub Option<Vec<u8>>);
1981
1982/// Request method of the request that produced a response, attached to the
1983/// response's extensions by the streaming orchestrator before it calls
1984/// [`StreamingCacheManager::put`]. Managers use it to special-case HEAD:
1985/// a HEAD response's `Content-Length` describes the entity, not the
1986/// (empty) stored body (RFC 9110 §8.6), so size/completeness checks that
1987/// compare received bytes against `Content-Length` must be skipped.
1988#[derive(Clone, Debug)]
1989pub struct CachedRequestMethod(pub http::Method);
1990
1991/// Opaque identity of the specific stored entry revision a response was
1992/// served from, attached to responses returned by
1993/// [`StreamingCacheManager::get`]. Passing it back to `update_metadata`
1994/// lets the manager refuse to apply a metadata update to an entry that was
1995/// concurrently replaced (which would otherwise staple one revision's
1996/// headers onto another revision's body).
1997#[derive(Clone, Debug, PartialEq, Eq)]
1998pub struct CacheEntryToken(pub Vec<u8>);
1999
2000/// Streaming version of HTTP cache that supports streaming request/response bodies
2001/// without buffering them in memory.
2002#[derive(Debug, Clone)]
2003pub struct HttpStreamingCache<T: StreamingCacheManager> {
2004    /// Determines the manager behavior.
2005    pub mode: CacheMode,
2006    /// Manager instance that implements the [`StreamingCacheManager`] trait.
2007    pub manager: T,
2008    /// Override the default cache options.
2009    pub options: HttpCacheOptions,
2010}
2011
2012// ============================================================================
2013// Helper functions for working with warning headers on http::Response
2014// ============================================================================
2015
2016/// Extracts the warning code from an `http::Response`'s warning header, if
2017/// present.  Returns the 3-digit warn-code as a `usize`.
2018fn response_warning_code<B>(response: &Response<B>) -> Option<usize> {
2019    response
2020        .headers()
2021        .get(WARNING)
2022        .and_then(|hdr| hdr.to_str().ok())
2023        .and_then(|s| s.chars().take(3).collect::<String>().parse().ok())
2024}
2025
2026/// Adds an RFC 2616 §14.46 warning header to an `http::Response`.
2027fn response_add_warning<B>(
2028    response: &mut Response<B>,
2029    url: &Url,
2030    code: usize,
2031    message: &str,
2032) {
2033    let host = url_host_str(url);
2034    let escaped_message = message.replace('"', "'").replace(['\n', '\r'], " ");
2035    let value = format!(
2036        "{} {} \"{}\" \"{}\"",
2037        code,
2038        host,
2039        escaped_message,
2040        httpdate::fmt_http_date(SystemTime::now()),
2041    );
2042    if let Ok(hv) = HeaderValue::from_str(&value) {
2043        response.headers_mut().insert(WARNING, hv);
2044    }
2045}
2046
2047/// Removes the warning header from an `http::Response`.
2048fn response_remove_warning<B>(response: &mut Response<B>) {
2049    response.headers_mut().remove(WARNING);
2050}
2051
2052/// RFC 9111 s4.2.4: whether a stored response may be served stale when
2053/// revalidating it failed. `no-cache` and `must-revalidate` forbid that, and so
2054/// do `proxy-revalidate` and `s-maxage` in a shared cache.
2055fn allows_stale_on_error(headers: &http::HeaderMap, shared: bool) -> bool {
2056    !cache_control_directives(headers).any(|directive| {
2057        let directive = directive.to_ascii_lowercase();
2058        is_directive(&directive, "no-cache")
2059            || is_directive(&directive, "must-revalidate")
2060            || (shared
2061                && (is_directive(&directive, "proxy-revalidate")
2062                    || is_directive(&directive, "s-maxage")))
2063    })
2064}
2065
2066/// Adds the custom `x-cache` status header to an `http::Response`.
2067fn response_cache_status<B>(
2068    response: &mut Response<B>,
2069    hit_or_miss: HitOrMiss,
2070) {
2071    if let Ok(hv) = HeaderValue::from_str(&hit_or_miss.to_string()) {
2072        response.headers_mut().insert(XCACHE, hv);
2073    }
2074}
2075
2076/// Adds the custom `x-cache-lookup` status header to an `http::Response`.
2077fn response_cache_lookup_status<B>(
2078    response: &mut Response<B>,
2079    hit_or_miss: HitOrMiss,
2080) {
2081    if let Ok(hv) = HeaderValue::from_str(&hit_or_miss.to_string()) {
2082        response.headers_mut().insert(XCACHELOOKUP, hv);
2083    }
2084}
2085
2086/// Applies [`HttpCacheOptions::modify_response_before_caching`] to a
2087/// streaming `Response<B>`.  The callback expects `&mut HttpResponse`, so we
2088/// build a temporary shim with the response's headers/status (empty body),
2089/// call the callback, and copy any header or status changes back.
2090///
2091/// Body and metadata modifications made by the callback are not reflected
2092/// because the streaming body is not buffered.
2093fn apply_modify_response_shim<B>(
2094    options: &HttpCacheOptions,
2095    response: &mut Response<B>,
2096    url: &Url,
2097) {
2098    let modify = match &options.modify_response {
2099        Some(f) => f,
2100        None => return,
2101    };
2102    let mut shim = HttpResponse {
2103        body: Vec::new(),
2104        headers: HttpHeaders::from(response.headers()),
2105        status: response.status().as_u16(),
2106        url: url.clone(),
2107        version: response.version().try_into().unwrap_or(HttpVersion::Http11),
2108        metadata: None,
2109    };
2110    modify(&mut shim);
2111    // Apply header changes back
2112    response.headers_mut().clear();
2113    for (name, value) in shim.headers.iter() {
2114        if let (Ok(hn), Ok(hv)) = (
2115            http::header::HeaderName::from_bytes(name.as_bytes()),
2116            HeaderValue::from_str(value),
2117        ) {
2118            response.headers_mut().append(hn, hv);
2119        }
2120    }
2121    // Apply status change back
2122    if let Ok(new_status) = StatusCode::from_u16(shim.status) {
2123        *response.status_mut() = new_status;
2124    }
2125}
2126
2127/// Replaces `dst` entries for every header name present in `src`, preserving
2128/// multi-valued headers (clear-then-append; naive `insert`/`extend` drops or
2129/// doubles values like `Set-Cookie`).
2130fn merge_headers(dst: &mut http::HeaderMap, src: &http::HeaderMap) {
2131    for name in src.keys() {
2132        dst.remove(name);
2133    }
2134    for (name, value) in src.iter() {
2135        dst.append(name.clone(), value.clone());
2136    }
2137}
2138
2139/// The directives of every `Cache-Control` header, trimmed.
2140fn cache_control_directives(
2141    headers: &http::HeaderMap,
2142) -> impl Iterator<Item = &str> {
2143    headers
2144        .get_all(CACHE_CONTROL)
2145        .iter()
2146        .filter_map(|value| value.to_str().ok())
2147        .flat_map(|value| value.split(','))
2148        .map(str::trim)
2149        .filter(|directive| !directive.is_empty())
2150}
2151
2152/// Whether `directive` is `name`, with or without an argument. Names are
2153/// case-sensitive, like `http-cache-semantics` parses them.
2154fn is_directive(directive: &str, name: &str) -> bool {
2155    directive.split('=').next().is_some_and(|key| key.trim() == name)
2156}
2157
2158/// RFC 9111 s4.2.1: whether the response states its own freshness lifetime,
2159/// matching the conditions `http-cache-semantics` checks. An `Expires` that is
2160/// invalid or in the past still counts, as it marks the response as stale.
2161fn has_explicit_expiration(parts: &response::Parts, shared: bool) -> bool {
2162    parts.headers.contains_key(EXPIRES)
2163        || cache_control_directives(&parts.headers).any(|directive| {
2164            is_directive(directive, "max-age")
2165                || (shared && is_directive(directive, "s-maxage"))
2166        })
2167}
2168
2169/// Copies `parts` with its freshness lifetime set to `ttl`, by replacing the
2170/// `max-age` and `s-maxage` directives. `max-age` takes precedence over
2171/// `Expires` and heuristics, so other headers are left alone.
2172fn with_max_age(parts: &response::Parts, ttl: Duration) -> response::Parts {
2173    let seconds = ttl.as_secs();
2174    let mut directives: Vec<String> = cache_control_directives(&parts.headers)
2175        .filter(|directive| !is_directive(directive, "max-age"))
2176        .map(|directive| {
2177            if is_directive(directive, "s-maxage") {
2178                format!("s-maxage={seconds}")
2179            } else {
2180                directive.to_string()
2181            }
2182        })
2183        .collect();
2184    directives.push(format!("max-age={seconds}"));
2185
2186    // `Pragma: no-cache` only counts when there is no `Cache-Control` header,
2187    // which we're about to add.
2188    if !parts.headers.contains_key(CACHE_CONTROL)
2189        && parts
2190            .headers
2191            .get(PRAGMA)
2192            .and_then(|value| value.to_str().ok())
2193            .is_some_and(|value| value.contains("no-cache"))
2194    {
2195        directives.push("no-cache".to_string());
2196    }
2197
2198    let mut parts = parts.clone();
2199    parts.headers.insert(
2200        CACHE_CONTROL,
2201        HeaderValue::from_str(&directives.join(", "))
2202            .unwrap_or_else(|_| HeaderValue::from_static("max-age=0")),
2203    );
2204    parts
2205}
2206
2207/// Removes a policy's possibly synthesized `Cache-Control`, unless the 304 sent one.
2208fn drop_policy_cache_control(
2209    headers: &mut http::HeaderMap,
2210    not_modified: Option<&http::HeaderMap>,
2211) {
2212    if !not_modified.is_some_and(|h| h.contains_key(CACHE_CONTROL)) {
2213        headers.remove(CACHE_CONTROL);
2214    }
2215}
2216
2217/// RFC 7234 s4.4: the GET and HEAD cache keys to invalidate after a
2218/// successful (2xx/3xx) response to a non-GET/HEAD request, or `None` when
2219/// the status does not warrant invalidation.
2220fn get_head_invalidation_keys(
2221    options: &HttpCacheOptions,
2222    parts: &request::Parts,
2223    status: StatusCode,
2224) -> Option<(String, String)> {
2225    (status.is_success() || status.is_redirection()).then(|| {
2226        (
2227            options.create_cache_key(parts, Some("GET")),
2228            options.create_cache_key(parts, Some("HEAD")),
2229        )
2230    })
2231}
2232
2233// ============================================================================
2234// HttpStreamingCache orchestrator methods
2235// ============================================================================
2236
2237impl<T: StreamingCacheManager> HttpStreamingCache<T>
2238where
2239    <T::Body as http_body::Body>::Data: Send,
2240    <T::Body as http_body::Body>::Error:
2241        Into<StreamingError> + Send + Sync + 'static,
2242{
2243    /// Determines if the request described by `parts` should be cached,
2244    /// taking into account any `mode_override`.
2245    pub fn can_cache_request(
2246        &self,
2247        parts: &request::Parts,
2248        mode_override: Option<CacheMode>,
2249    ) -> Result<bool> {
2250        let analysis = <Self as HttpCacheStreamInterface>::analyze_request(
2251            self,
2252            parts,
2253            mode_override,
2254        )?;
2255        Ok(analysis.should_cache)
2256    }
2257
2258    /// Apply rate limiting if enabled in options.
2259    #[cfg(feature = "rate-limiting")]
2260    async fn apply_rate_limiting(&self, url: &Url) {
2261        if let Some(rate_limiter) = &self.options.rate_limiter {
2262            let rate_limit_key = url_hostname(url).unwrap_or("unknown");
2263            rate_limiter.until_key_ready(rate_limit_key).await;
2264        }
2265    }
2266
2267    /// Apply rate limiting if enabled in options (no-op without
2268    /// rate-limiting feature).
2269    #[cfg(not(feature = "rate-limiting"))]
2270    async fn apply_rate_limiting(&self, _url: &Url) {
2271        // No-op when rate limiting feature is not enabled
2272    }
2273
2274    /// Performs cache-busting housekeeping for requests that should not be
2275    /// cached.  Mirrors [`HttpCache::run_no_cache`].
2276    pub async fn run_no_cache(&self, parts: &request::Parts) -> Result<()> {
2277        self.manager
2278            .delete(&self.options.create_cache_key(parts, Some("GET")))
2279            .await
2280            .ok();
2281        self.manager
2282            .delete(&self.options.create_cache_key(parts, Some("HEAD")))
2283            .await
2284            .ok();
2285
2286        let cache_key = self.options.create_cache_key(parts, None);
2287
2288        if let Some(cache_bust) = &self.options.cache_bust {
2289            for key_to_cache_bust in
2290                cache_bust(parts, &self.options.cache_key, &cache_key)
2291            {
2292                self.manager.delete(&key_to_cache_bust).await?;
2293            }
2294        }
2295
2296        Ok(())
2297    }
2298
2299    /// See [`get_head_invalidation_keys`].
2300    async fn invalidate_get_head(
2301        &self,
2302        parts: &request::Parts,
2303        status: StatusCode,
2304    ) {
2305        if let Some((get_key, head_key)) =
2306            get_head_invalidation_keys(&self.options, parts, status)
2307        {
2308            self.manager.delete(&get_key).await.ok();
2309            self.manager.delete(&head_key).await.ok();
2310        }
2311    }
2312
2313    /// The main streaming cache orchestrator.
2314    ///
2315    /// This mirrors the logic of [`HttpCache::run`] but operates on
2316    /// streaming `Response<B>` bodies and delegates upstream fetching to a
2317    /// caller-supplied callback instead of an `impl Middleware`.
2318    ///
2319    /// # Arguments
2320    ///
2321    /// * `parts` - The request parts to evaluate.
2322    /// * `mode_override` - Optional per-request cache mode override.
2323    /// * `fetch` - A callback that performs the actual HTTP request.  It
2324    ///   receives a [`FetchRequest`] indicating whether to issue a fresh or
2325    ///   conditional request, and must return the upstream `Response<B>`.
2326    ///   Called at most once per request.
2327    pub async fn run<B, F, Fut>(
2328        &self,
2329        parts: &request::Parts,
2330        mode_override: Option<CacheMode>,
2331        fetch: F,
2332    ) -> Result<Response<T::Body>>
2333    where
2334        B: http_body::Body + Send + 'static,
2335        B::Data: Send,
2336        B::Error: Into<StreamingError>,
2337        F: FnOnce(FetchRequest) -> Fut,
2338        Fut: Future<Output = Result<Response<B>>>,
2339    {
2340        // 1. Analyze the request
2341        let analysis = <Self as HttpCacheStreamInterface>::analyze_request(
2342            self,
2343            parts,
2344            mode_override,
2345        )?;
2346
2347        // 2. If the request should not be cached, fetch and process as a
2348        //    remote miss.
2349        if !analysis.should_cache {
2350            let url = extract_url_from_request_parts(parts)?;
2351            self.apply_rate_limiting(&url).await;
2352            let response = fetch(FetchRequest::Fresh).await?;
2353            return self.remote_fetch_and_cache(analysis, response).await;
2354        }
2355
2356        // 3. Bust cache keys if needed
2357        for key in &analysis.cache_bust_keys {
2358            self.manager.delete(key).await?;
2359        }
2360
2361        // 4. Look up cached response
2362        if let Some((mut cached_response, policy)) =
2363            <Self as HttpCacheStreamInterface>::lookup_cached_response(
2364                self,
2365                &analysis.cache_key,
2366            )
2367            .await?
2368        {
2369            if self.options.cache_status_headers {
2370                response_cache_lookup_status(
2371                    &mut cached_response,
2372                    HitOrMiss::HIT,
2373                );
2374            }
2375
2376            // Handle warning headers per RFC 7234 §4.3.4
2377            if let Some(warning_code) = response_warning_code(&cached_response)
2378                && (100..200).contains(&warning_code)
2379            {
2380                response_remove_warning(&mut cached_response);
2381            }
2382
2383            // 5. Branch on cache mode
2384            match analysis.cache_mode {
2385                CacheMode::Default => {
2386                    self.conditional_fetch(
2387                        &analysis,
2388                        fetch,
2389                        cached_response,
2390                        policy,
2391                    )
2392                    .await
2393                }
2394                CacheMode::NoCache => {
2395                    // The no-cache directive makes the policy treat even a
2396                    // fresh response as stale, so it is revalidated.
2397                    // Mirrors `Middleware::force_no_cache` in HttpCache::run.
2398                    let mut analysis = analysis;
2399                    analysis.request_parts.headers.insert(
2400                        CACHE_CONTROL,
2401                        HeaderValue::from_static("no-cache"),
2402                    );
2403                    self.conditional_fetch(
2404                        &analysis,
2405                        fetch,
2406                        cached_response,
2407                        policy,
2408                    )
2409                    .await
2410                }
2411                CacheMode::ForceCache
2412                | CacheMode::OnlyIfCached
2413                | CacheMode::IgnoreRules => {
2414                    //   112 Disconnected operation
2415                    // SHOULD be included if the cache is intentionally
2416                    // disconnected from the rest of the network for a
2417                    // period of time.
2418                    // (https://tools.ietf.org/html/rfc2616#section-14.46)
2419                    let url = extract_url_from_request_parts(parts)?;
2420                    response_add_warning(
2421                        &mut cached_response,
2422                        &url,
2423                        112,
2424                        "Disconnected operation",
2425                    );
2426                    if self.options.cache_status_headers {
2427                        response_cache_status(
2428                            &mut cached_response,
2429                            HitOrMiss::HIT,
2430                        );
2431                    }
2432                    Ok(cached_response)
2433                }
2434                CacheMode::Reload => {
2435                    let url = extract_url_from_request_parts(parts)?;
2436                    self.apply_rate_limiting(&url).await;
2437                    let response = fetch(FetchRequest::Fresh).await?;
2438                    let mut res =
2439                        self.remote_fetch_and_cache(analysis, response).await?;
2440                    if self.options.cache_status_headers {
2441                        response_cache_lookup_status(&mut res, HitOrMiss::HIT);
2442                    }
2443                    Ok(res)
2444                }
2445                _ => {
2446                    let url = extract_url_from_request_parts(parts)?;
2447                    self.apply_rate_limiting(&url).await;
2448                    let response = fetch(FetchRequest::Fresh).await?;
2449                    self.remote_fetch_and_cache(analysis, response).await
2450                }
2451            }
2452        } else {
2453            // 6. No cached response found
2454            match analysis.cache_mode {
2455                CacheMode::OnlyIfCached => {
2456                    // ENOTCACHED — return 504 Gateway Timeout
2457                    let mut res = Response::builder()
2458                        .status(StatusCode::GATEWAY_TIMEOUT)
2459                        .body(self.manager.empty_body())
2460                        .map_err(|e| -> BoxError { e.into() })?;
2461                    if self.options.cache_status_headers {
2462                        response_cache_status(&mut res, HitOrMiss::MISS);
2463                        response_cache_lookup_status(&mut res, HitOrMiss::MISS);
2464                    }
2465                    Ok(res)
2466                }
2467                _ => {
2468                    let url = extract_url_from_request_parts(parts)?;
2469                    self.apply_rate_limiting(&url).await;
2470                    let fetch_request =
2471                        if analysis.cache_mode == CacheMode::NoCache {
2472                            FetchRequest::FreshNoCache
2473                        } else {
2474                            FetchRequest::Fresh
2475                        };
2476                    let response = fetch(fetch_request).await?;
2477                    self.remote_fetch_and_cache(analysis, response).await
2478                }
2479            }
2480        }
2481    }
2482
2483    /// Processes a fresh upstream response and potentially caches it.
2484    ///
2485    /// Mirrors [`HttpCache::remote_fetch`] but receives the response
2486    /// directly rather than calling middleware.  Rate limiting is performed
2487    /// by the caller before invoking `fetch`.
2488    async fn remote_fetch_and_cache<B>(
2489        &self,
2490        analysis: CacheAnalysis,
2491        response: Response<B>,
2492    ) -> Result<Response<T::Body>>
2493    where
2494        B: http_body::Body + Send + 'static,
2495        B::Data: Send,
2496        B::Error: Into<StreamingError>,
2497    {
2498        // Delegate to process_response which handles:
2499        //   - response-based cache mode override evaluation
2500        //   - policy creation
2501        //   - should_cache_response check
2502        //   - cache busting for non-GET/HEAD
2503        //   - storing via manager.put or converting via manager.convert_body
2504        //   - adding cache status headers (MISS/MISS)
2505        //   - applying modify_response_before_caching shim before put
2506        let res = <Self as HttpCacheStreamInterface>::process_response(
2507            self,
2508            analysis.clone(),
2509            response,
2510            None,
2511        )
2512        .await?;
2513
2514        Ok(res)
2515    }
2516
2517    /// Performs a conditional fetch (revalidation) against the origin,
2518    /// returning either the still-valid cached response or the fresh
2519    /// upstream response.
2520    ///
2521    /// Mirrors [`HttpCache::conditional_fetch`].
2522    async fn conditional_fetch<B, F, Fut>(
2523        &self,
2524        analysis: &CacheAnalysis,
2525        fetch: F,
2526        mut cached_res: Response<T::Body>,
2527        mut policy: CachePolicy,
2528    ) -> Result<Response<T::Body>>
2529    where
2530        B: http_body::Body + Send + 'static,
2531        B::Data: Send,
2532        B::Error: Into<StreamingError>,
2533        F: FnOnce(FetchRequest) -> Fut,
2534        Fut: Future<Output = Result<Response<B>>>,
2535    {
2536        let parts = &analysis.request_parts;
2537        let before_req = policy.before_request(parts, SystemTime::now());
2538        match before_req {
2539            BeforeRequest::Fresh(mut fresh_parts) => {
2540                drop_policy_cache_control(&mut fresh_parts.headers, None);
2541                merge_headers(cached_res.headers_mut(), &fresh_parts.headers);
2542                if self.options.cache_status_headers {
2543                    response_cache_status(&mut cached_res, HitOrMiss::HIT);
2544                    response_cache_lookup_status(
2545                        &mut cached_res,
2546                        HitOrMiss::HIT,
2547                    );
2548                }
2549                Ok(cached_res)
2550            }
2551            BeforeRequest::Stale { request: stale_parts, matches } => {
2552                let serve_stale = matches
2553                    && allows_stale_on_error(
2554                        cached_res.headers(),
2555                        self.options.cache_options.unwrap_or_default().shared,
2556                    );
2557                let req_url = extract_url_from_request_parts(parts)?;
2558                // Apply rate limiting before revalidation request
2559                self.apply_rate_limiting(&req_url).await;
2560
2561                // Only send conditional headers when matches is true
2562                // (matching reference behavior at HttpCache::conditional_fetch)
2563                let fetch_result = if matches {
2564                    fetch(FetchRequest::Conditional(Box::new(stale_parts)))
2565                        .await
2566                } else if analysis.cache_mode == CacheMode::NoCache {
2567                    fetch(FetchRequest::FreshNoCache).await
2568                } else {
2569                    fetch(FetchRequest::Fresh).await
2570                };
2571
2572                match fetch_result {
2573                    Ok(cond_res) => {
2574                        let status = cond_res.status();
2575
2576                        // On a server error, act as if the server hadn't
2577                        // responded (RFC 9111 s4.3.3): serve the stale
2578                        // response, if it is the one for this request and
2579                        // its directives allow that.
2580                        if status.is_server_error() && serve_stale {
2581                            //   111 Revalidation failed
2582                            //   MUST be included if a cache returns a
2583                            //   stale response because an attempt to
2584                            //   revalidate the response failed, due to an
2585                            //   inability to reach the server.
2586                            // (https://tools.ietf.org/html/rfc2616#section-14.46)
2587                            response_add_warning(
2588                                &mut cached_res,
2589                                &req_url,
2590                                111,
2591                                "Revalidation failed",
2592                            );
2593                            if self.options.cache_status_headers {
2594                                response_cache_status(
2595                                    &mut cached_res,
2596                                    HitOrMiss::HIT,
2597                                );
2598                            }
2599                            Ok(cached_res)
2600                        } else if status == StatusCode::NOT_MODIFIED {
2601                            // 304 Not Modified — update cached response
2602                            // headers using policy.after_response
2603                            let (cond_parts, _cond_body) =
2604                                cond_res.into_parts();
2605                            let after_res = policy.after_response(
2606                                parts,
2607                                &cond_parts,
2608                                SystemTime::now(),
2609                            );
2610                            match after_res {
2611                                AfterResponse::Modified(_, mut new_parts)
2612                                | AfterResponse::NotModified(
2613                                    _,
2614                                    mut new_parts,
2615                                ) => {
2616                                    drop_policy_cache_control(
2617                                        &mut new_parts.headers,
2618                                        Some(&cond_parts.headers),
2619                                    );
2620                                    merge_headers(
2621                                        cached_res.headers_mut(),
2622                                        &new_parts.headers,
2623                                    );
2624                                }
2625                            }
2626                            let (stored_parts, body) = cached_res.into_parts();
2627                            policy = self
2628                                .options
2629                                .create_cache_policy(parts, &stored_parts);
2630                            cached_res =
2631                                Response::from_parts(stored_parts, body);
2632                            if self.options.cache_status_headers {
2633                                response_cache_status(
2634                                    &mut cached_res,
2635                                    HitOrMiss::HIT,
2636                                );
2637                                response_cache_lookup_status(
2638                                    &mut cached_res,
2639                                    HitOrMiss::HIT,
2640                                );
2641                            }
2642
2643                            apply_modify_response_shim(
2644                                &self.options,
2645                                &mut cached_res,
2646                                &req_url,
2647                            );
2648
2649                            // Preserve the cached response's original user
2650                            // metadata instead of regenerating it.
2651                            let metadata = cached_res
2652                                .extensions()
2653                                .get::<CachedUserMetadata>()
2654                                .and_then(|m| m.0.clone());
2655
2656                            // Metadata-only refresh: the body is
2657                            // known-unchanged (that's what 304 means), so
2658                            // never re-read or rewrite the body file. Any
2659                            // failure here must not break the response —
2660                            // cached_res is already valid to serve.
2661                            let cache_key =
2662                                self.options.create_cache_key(parts, None);
2663                            let token = cached_res
2664                                .extensions()
2665                                .get::<CacheEntryToken>()
2666                                .cloned();
2667                            match self
2668                                .manager
2669                                .update_metadata(
2670                                    &cache_key,
2671                                    cached_res.headers(),
2672                                    policy,
2673                                    metadata,
2674                                    token.as_ref(),
2675                                )
2676                                .await
2677                            {
2678                                Ok(true) => {}
2679                                Ok(false) => log::debug!(
2680                                    "streaming 304: entry vanished or was \
2681                                     replaced during revalidation; serving \
2682                                     without re-cache"
2683                                ),
2684                                Err(e) => log::debug!(
2685                                    "streaming 304: metadata update failed; \
2686                                     serving without re-cache: {e}"
2687                                ),
2688                            }
2689                            Ok(cached_res)
2690                        } else {
2691                            // A full response replaces the stored one
2692                            // (RFC 9111 s4.3.3), whatever its status.
2693                            let (cond_parts, cond_body) = cond_res.into_parts();
2694                            let new_policy = self
2695                                .options
2696                                .create_cache_policy(parts, &cond_parts);
2697                            let metadata = self
2698                                .options
2699                                .generate_metadata(parts, &cond_parts);
2700                            let cond_res =
2701                                Response::from_parts(cond_parts, cond_body);
2702
2703                            let request_url =
2704                                extract_url_from_request_parts(parts)?;
2705
2706                            // Apply modify_response BEFORE cacheability checks
2707                            // (matches non-streaming reference order)
2708                            let mut cond_res = cond_res;
2709                            apply_modify_response_shim(
2710                                &self.options,
2711                                &mut cond_res,
2712                                &request_url,
2713                            );
2714
2715                            // Build HttpResponse shim from modified response
2716                            let http_response_shim = HttpResponse {
2717                                body: vec![],
2718                                headers: cond_res.headers().into(),
2719                                status: cond_res.status().as_u16(),
2720                                url: request_url.clone(),
2721                                version: cond_res
2722                                    .version()
2723                                    .try_into()
2724                                    .unwrap_or(HttpVersion::Http11),
2725                                metadata: metadata.clone(),
2726                            };
2727                            // Apply response-based cache mode override
2728                            let effective_mode =
2729                                self.options.evaluate_response_cache_mode(
2730                                    parts,
2731                                    &http_response_shim,
2732                                    analysis.cache_mode,
2733                                );
2734                            let is_cacheable =
2735                                self.options.should_cache_response(
2736                                    effective_mode,
2737                                    &http_response_shim,
2738                                    analysis.is_get_head,
2739                                    &new_policy,
2740                                );
2741
2742                            // Set cache status headers
2743                            if self.options.cache_status_headers {
2744                                response_cache_status(
2745                                    &mut cond_res,
2746                                    HitOrMiss::MISS,
2747                                );
2748                                response_cache_lookup_status(
2749                                    &mut cond_res,
2750                                    HitOrMiss::HIT,
2751                                );
2752                            }
2753
2754                            let cache_key =
2755                                self.options.create_cache_key(parts, None);
2756                            if is_cacheable {
2757                                cond_res.extensions_mut().insert(
2758                                    CachedRequestMethod(parts.method.clone()),
2759                                );
2760                                let res = self
2761                                    .manager
2762                                    .put(
2763                                        cache_key,
2764                                        cond_res,
2765                                        new_policy,
2766                                        request_url,
2767                                        metadata,
2768                                    )
2769                                    .await?;
2770                                Ok(res)
2771                            } else {
2772                                // Drop the stored response so it isn't
2773                                // served in place of this one. On a server
2774                                // error, keep it as if the server hadn't
2775                                // responded (RFC 9111 s4.3.3).
2776                                if !status.is_server_error()
2777                                    && let Err(e) =
2778                                        self.manager.delete(&cache_key).await
2779                                {
2780                                    log::debug!(
2781                                        "streaming revalidation: failed to \
2782                                         remove the replaced entry: {e}"
2783                                    );
2784                                }
2785                                let res =
2786                                    self.manager.convert_body(cond_res).await?;
2787                                Ok(res)
2788                            }
2789                        }
2790                    }
2791                    Err(e) => {
2792                        if !serve_stale {
2793                            Err(e)
2794                        } else {
2795                            //   111 Revalidation failed
2796                            //   MUST be included if a cache returns a
2797                            //   stale response because an attempt to
2798                            //   revalidate the response failed, due to an
2799                            //   inability to reach the server.
2800                            // (https://tools.ietf.org/html/rfc2616#section-14.46)
2801                            response_add_warning(
2802                                &mut cached_res,
2803                                &req_url,
2804                                111,
2805                                "Revalidation failed",
2806                            );
2807                            if self.options.cache_status_headers {
2808                                response_cache_status(
2809                                    &mut cached_res,
2810                                    HitOrMiss::HIT,
2811                                );
2812                            }
2813                            Ok(cached_res)
2814                        }
2815                    }
2816                }
2817            }
2818        }
2819    }
2820}
2821
2822impl<T: CacheManager> HttpCache<T> {
2823    /// Determines if the request should be cached
2824    pub fn can_cache_request(
2825        &self,
2826        middleware: &impl Middleware,
2827    ) -> Result<bool> {
2828        let analysis = self.analyze_request(
2829            &middleware.parts()?,
2830            middleware.overridden_cache_mode(),
2831        )?;
2832        Ok(analysis.should_cache)
2833    }
2834
2835    /// Apply rate limiting if enabled in options
2836    #[cfg(feature = "rate-limiting")]
2837    async fn apply_rate_limiting(&self, url: &Url) {
2838        if let Some(rate_limiter) = &self.options.rate_limiter {
2839            let rate_limit_key = url_hostname(url).unwrap_or("unknown");
2840            rate_limiter.until_key_ready(rate_limit_key).await;
2841        }
2842    }
2843
2844    /// Apply rate limiting if enabled in options (no-op without rate-limiting feature)
2845    #[cfg(not(feature = "rate-limiting"))]
2846    async fn apply_rate_limiting(&self, _url: &Url) {
2847        // No-op when rate limiting feature is not enabled
2848    }
2849
2850    /// Cache-busting for non-cacheable requests, taking pre-extracted parts.
2851    pub async fn run_no_cache_from_parts(
2852        &self,
2853        parts: &request::Parts,
2854    ) -> Result<()> {
2855        self.manager
2856            .delete(&self.options.create_cache_key(parts, Some("GET")))
2857            .await
2858            .ok();
2859        self.manager
2860            .delete(&self.options.create_cache_key(parts, Some("HEAD")))
2861            .await
2862            .ok();
2863
2864        let cache_key = self.options.create_cache_key(parts, None);
2865
2866        if let Some(cache_bust) = &self.options.cache_bust {
2867            for key_to_cache_bust in
2868                cache_bust(parts, &self.options.cache_key, &cache_key)
2869            {
2870                self.manager.delete(&key_to_cache_bust).await?;
2871            }
2872        }
2873
2874        Ok(())
2875    }
2876
2877    /// Runs the actions to perform when the client middleware is running without the cache
2878    pub async fn run_no_cache(
2879        &self,
2880        middleware: &mut impl Middleware,
2881    ) -> Result<()> {
2882        let parts = middleware.parts()?;
2883        self.run_no_cache_from_parts(&parts).await
2884    }
2885
2886    /// See [`get_head_invalidation_keys`].
2887    async fn invalidate_get_head(
2888        &self,
2889        parts: &request::Parts,
2890        status: StatusCode,
2891    ) {
2892        if let Some((get_key, head_key)) =
2893            get_head_invalidation_keys(&self.options, parts, status)
2894        {
2895            self.manager.delete(&get_key).await.ok();
2896            self.manager.delete(&head_key).await.ok();
2897        }
2898    }
2899
2900    /// Attempts to run the passed middleware along with the cache
2901    pub async fn run(
2902        &self,
2903        mut middleware: impl Middleware,
2904    ) -> Result<HttpResponse> {
2905        // Use the HttpCacheInterface to analyze the request
2906        let analysis = self.analyze_request(
2907            &middleware.parts()?,
2908            middleware.overridden_cache_mode(),
2909        )?;
2910
2911        if !analysis.should_cache {
2912            return self.remote_fetch(&mut middleware).await;
2913        }
2914
2915        // Bust cache keys if needed
2916        for key in &analysis.cache_bust_keys {
2917            self.manager.delete(key).await?;
2918        }
2919
2920        // Look up cached response
2921        if let Some((mut cached_response, policy)) =
2922            self.lookup_cached_response(&analysis.cache_key).await?
2923        {
2924            if self.options.cache_status_headers {
2925                cached_response.cache_lookup_status(HitOrMiss::HIT);
2926            }
2927
2928            // Handle warning headers
2929            if let Some(warning_code) = cached_response.warning_code() {
2930                // https://tools.ietf.org/html/rfc7234#section-4.3.4
2931                //
2932                // If a stored response is selected for update, the cache MUST:
2933                //
2934                // * delete any warning header fields in the stored response with
2935                //   warn-code 1xx (see Section 5.5);
2936                //
2937                // * retain any warning header fields in the stored response with
2938                //   warn-code 2xx;
2939                //
2940                if (100..200).contains(&warning_code) {
2941                    cached_response.remove_warning();
2942                }
2943            }
2944
2945            match analysis.cache_mode {
2946                CacheMode::Default => {
2947                    self.conditional_fetch(middleware, cached_response, policy)
2948                        .await
2949                }
2950                CacheMode::NoCache => {
2951                    // The no-cache directive makes the policy treat even a
2952                    // fresh response as stale, so it is revalidated.
2953                    middleware.force_no_cache()?;
2954                    self.conditional_fetch(middleware, cached_response, policy)
2955                        .await
2956                }
2957                CacheMode::ForceCache
2958                | CacheMode::OnlyIfCached
2959                | CacheMode::IgnoreRules => {
2960                    //   112 Disconnected operation
2961                    // SHOULD be included if the cache is intentionally disconnected from
2962                    // the rest of the network for a period of time.
2963                    // (https://tools.ietf.org/html/rfc2616#section-14.46)
2964                    cached_response.add_warning(
2965                        &cached_response.url.clone(),
2966                        112,
2967                        "Disconnected operation",
2968                    );
2969                    if self.options.cache_status_headers {
2970                        cached_response.cache_status(HitOrMiss::HIT);
2971                    }
2972                    Ok(cached_response)
2973                }
2974                CacheMode::Reload => {
2975                    let mut res = self.remote_fetch(&mut middleware).await?;
2976                    if self.options.cache_status_headers {
2977                        res.cache_lookup_status(HitOrMiss::HIT);
2978                    }
2979                    Ok(res)
2980                }
2981                _ => self.remote_fetch(&mut middleware).await,
2982            }
2983        } else {
2984            match analysis.cache_mode {
2985                CacheMode::OnlyIfCached => {
2986                    // ENOTCACHED
2987                    let mut res = HttpResponse {
2988                        body: Vec::new(),
2989                        headers: HttpHeaders::default(),
2990                        status: 504,
2991                        url: middleware.url()?,
2992                        version: HttpVersion::Http11,
2993                        metadata: None,
2994                    };
2995                    if self.options.cache_status_headers {
2996                        res.cache_status(HitOrMiss::MISS);
2997                        res.cache_lookup_status(HitOrMiss::MISS);
2998                    }
2999                    Ok(res)
3000                }
3001                CacheMode::NoCache => {
3002                    middleware.force_no_cache()?;
3003                    self.remote_fetch(&mut middleware).await
3004                }
3005                _ => self.remote_fetch(&mut middleware).await,
3006            }
3007        }
3008    }
3009
3010    fn cache_mode(&self, middleware: &impl Middleware) -> Result<CacheMode> {
3011        Ok(if let Some(mode) = middleware.overridden_cache_mode() {
3012            mode
3013        } else if let Some(cache_mode_fn) = &self.options.cache_mode_fn {
3014            cache_mode_fn(&middleware.parts()?)
3015        } else {
3016            self.mode
3017        })
3018    }
3019
3020    async fn remote_fetch(
3021        &self,
3022        middleware: &mut impl Middleware,
3023    ) -> Result<HttpResponse> {
3024        // Apply rate limiting before making the network request
3025        let url = middleware.url()?;
3026        self.apply_rate_limiting(&url).await;
3027
3028        let mut res = middleware.remote_fetch().await?;
3029        if self.options.cache_status_headers {
3030            res.cache_status(HitOrMiss::MISS);
3031            res.cache_lookup_status(HitOrMiss::MISS);
3032        }
3033        let parts = middleware.parts()?;
3034        let policy = self.options.create_cache_policy(&parts, &res.parts()?);
3035        let is_get_head = middleware.is_method_get_head();
3036        let mut mode = self.cache_mode(middleware)?;
3037
3038        // Allow response-based cache mode override
3039        if let Some(response_cache_mode_fn) =
3040            &self.options.response_cache_mode_fn
3041            && let Some(override_mode) = response_cache_mode_fn(&parts, &res)
3042        {
3043            mode = override_mode;
3044        }
3045
3046        let is_cacheable = self.options.should_cache_response(
3047            mode,
3048            &res,
3049            is_get_head,
3050            &policy,
3051        );
3052
3053        if is_cacheable {
3054            // Generate metadata using the provider callback if configured
3055            let response_parts = res.parts()?;
3056            res.metadata =
3057                self.options.generate_metadata(&parts, &response_parts);
3058
3059            self.options.modify_response_before_caching(&mut res);
3060            let res = self
3061                .manager
3062                .put(self.options.create_cache_key(&parts, None), res, policy)
3063                .await?;
3064            if !is_get_head {
3065                self.invalidate_get_head(
3066                    &parts,
3067                    StatusCode::from_u16(res.status)?,
3068                )
3069                .await;
3070            }
3071            Ok(res)
3072        } else if !is_get_head {
3073            self.invalidate_get_head(&parts, StatusCode::from_u16(res.status)?)
3074                .await;
3075            Ok(res)
3076        } else {
3077            Ok(res)
3078        }
3079    }
3080
3081    async fn conditional_fetch(
3082        &self,
3083        mut middleware: impl Middleware,
3084        mut cached_res: HttpResponse,
3085        mut policy: CachePolicy,
3086    ) -> Result<HttpResponse> {
3087        let parts = middleware.parts()?;
3088        let before_req = policy.before_request(&parts, SystemTime::now());
3089        let matches = match before_req {
3090            BeforeRequest::Fresh(mut parts) => {
3091                drop_policy_cache_control(&mut parts.headers, None);
3092                cached_res.update_headers(&parts)?;
3093                if self.options.cache_status_headers {
3094                    cached_res.cache_status(HitOrMiss::HIT);
3095                    cached_res.cache_lookup_status(HitOrMiss::HIT);
3096                }
3097                return Ok(cached_res);
3098            }
3099            BeforeRequest::Stale { request: parts, matches } => {
3100                if matches {
3101                    middleware.update_headers(&parts)?;
3102                }
3103                matches
3104            }
3105        };
3106        let serve_stale = matches
3107            && allows_stale_on_error(
3108                &cached_res.parts()?.headers,
3109                self.options.cache_options.unwrap_or_default().shared,
3110            );
3111        let req_url = middleware.url()?;
3112        // Apply rate limiting before revalidation request
3113        self.apply_rate_limiting(&req_url).await;
3114        match middleware.remote_fetch().await {
3115            Ok(mut cond_res) => {
3116                let status = StatusCode::from_u16(cond_res.status)?;
3117                // On a server error, act as if the server hadn't responded
3118                // (RFC 9111 s4.3.3): serve the stale response, if it is the
3119                // one for this request and its directives allow that.
3120                if status.is_server_error() && serve_stale {
3121                    //   111 Revalidation failed
3122                    //   MUST be included if a cache returns a stale response
3123                    //   because an attempt to revalidate the response failed,
3124                    //   due to an inability to reach the server.
3125                    // (https://tools.ietf.org/html/rfc2616#section-14.46)
3126                    cached_res.add_warning(
3127                        &req_url,
3128                        111,
3129                        "Revalidation failed",
3130                    );
3131                    if self.options.cache_status_headers {
3132                        cached_res.cache_status(HitOrMiss::HIT);
3133                    }
3134                    Ok(cached_res)
3135                } else if cond_res.status == 304 {
3136                    let cond_parts = cond_res.parts()?;
3137                    let after_res = policy.after_response(
3138                        &parts,
3139                        &cond_parts,
3140                        SystemTime::now(),
3141                    );
3142                    match after_res {
3143                        AfterResponse::Modified(_, mut parts)
3144                        | AfterResponse::NotModified(_, mut parts) => {
3145                            drop_policy_cache_control(
3146                                &mut parts.headers,
3147                                Some(&cond_parts.headers),
3148                            );
3149                            cached_res.update_headers(&parts)?;
3150                        }
3151                    }
3152                    policy = self
3153                        .options
3154                        .create_cache_policy(&parts, &cached_res.parts()?);
3155                    if self.options.cache_status_headers {
3156                        cached_res.cache_status(HitOrMiss::HIT);
3157                        cached_res.cache_lookup_status(HitOrMiss::HIT);
3158                    }
3159                    self.options
3160                        .modify_response_before_caching(&mut cached_res);
3161                    let res = self
3162                        .manager
3163                        .put(
3164                            self.options.create_cache_key(&parts, None),
3165                            cached_res,
3166                            policy,
3167                        )
3168                        .await?;
3169                    Ok(res)
3170                } else {
3171                    // A full response replaces the stored one (RFC 9111
3172                    // s4.3.3), whatever its status.
3173                    let response_parts = cond_res.parts()?;
3174                    let policy = self
3175                        .options
3176                        .create_cache_policy(&parts, &response_parts);
3177                    if self.options.cache_status_headers {
3178                        cond_res.cache_status(HitOrMiss::MISS);
3179                        cond_res.cache_lookup_status(HitOrMiss::HIT);
3180                    }
3181                    // Generate metadata using the provider callback if configured
3182                    cond_res.metadata =
3183                        self.options.generate_metadata(&parts, &response_parts);
3184
3185                    self.options.modify_response_before_caching(&mut cond_res);
3186
3187                    let mode = self.cache_mode(&middleware)?;
3188                    // Apply response-based cache mode override if configured
3189                    let mode = self
3190                        .options
3191                        .evaluate_response_cache_mode(&parts, &cond_res, mode);
3192                    let is_get_head = middleware.is_method_get_head();
3193                    let is_cacheable = self.options.should_cache_response(
3194                        mode,
3195                        &cond_res,
3196                        is_get_head,
3197                        &policy,
3198                    );
3199
3200                    let cache_key = self.options.create_cache_key(&parts, None);
3201                    if is_cacheable {
3202                        let res = self
3203                            .manager
3204                            .put(cache_key, cond_res, policy)
3205                            .await?;
3206                        Ok(res)
3207                    } else {
3208                        // Drop the stored response so it isn't served in
3209                        // place of this one. On a server error, keep it as if
3210                        // the server hadn't responded (RFC 9111 s4.3.3).
3211                        if !status.is_server_error()
3212                            && let Err(e) =
3213                                self.manager.delete(&cache_key).await
3214                        {
3215                            log::debug!(
3216                                "revalidation: failed to remove the replaced \
3217                                 entry: {e}"
3218                            );
3219                        }
3220                        Ok(cond_res)
3221                    }
3222                }
3223            }
3224            Err(e) => {
3225                if !serve_stale {
3226                    Err(e)
3227                } else {
3228                    //   111 Revalidation failed
3229                    //   MUST be included if a cache returns a stale response
3230                    //   because an attempt to revalidate the response failed,
3231                    //   due to an inability to reach the server.
3232                    // (https://tools.ietf.org/html/rfc2616#section-14.46)
3233                    cached_res.add_warning(
3234                        &req_url,
3235                        111,
3236                        "Revalidation failed",
3237                    );
3238                    if self.options.cache_status_headers {
3239                        cached_res.cache_status(HitOrMiss::HIT);
3240                    }
3241                    Ok(cached_res)
3242                }
3243            }
3244        }
3245    }
3246}
3247
3248impl<T: StreamingCacheManager> HttpCacheStreamInterface
3249    for HttpStreamingCache<T>
3250where
3251    <T::Body as http_body::Body>::Data: Send,
3252    <T::Body as http_body::Body>::Error:
3253        Into<StreamingError> + Send + Sync + 'static,
3254{
3255    type Body = T::Body;
3256
3257    fn analyze_request(
3258        &self,
3259        parts: &request::Parts,
3260        mode_override: Option<CacheMode>,
3261    ) -> Result<CacheAnalysis> {
3262        self.options.analyze_request_internal(parts, mode_override, self.mode)
3263    }
3264
3265    async fn lookup_cached_response(
3266        &self,
3267        key: &str,
3268    ) -> Result<Option<(Response<Self::Body>, CachePolicy)>> {
3269        self.manager.get(key).await
3270    }
3271
3272    async fn process_response<B>(
3273        &self,
3274        analysis: CacheAnalysis,
3275        response: Response<B>,
3276        metadata: Option<Vec<u8>>,
3277    ) -> Result<Response<Self::Body>>
3278    where
3279        B: http_body::Body + Send + 'static,
3280        B::Data: Send,
3281        B::Error: Into<StreamingError>,
3282        <T::Body as http_body::Body>::Data: Send,
3283        <T::Body as http_body::Body>::Error:
3284            Into<StreamingError> + Send + Sync + 'static,
3285    {
3286        // For non-cacheable requests based on initial analysis, convert them to manager's body type
3287        if !analysis.should_cache {
3288            if !analysis.is_get_head {
3289                self.invalidate_get_head(
3290                    &analysis.request_parts,
3291                    response.status(),
3292                )
3293                .await;
3294            }
3295            let mut converted_response =
3296                self.manager.convert_body(response).await?;
3297            // Add cache miss headers
3298            if self.options.cache_status_headers {
3299                converted_response.headers_mut().insert(
3300                    XCACHE,
3301                    "MISS".parse().map_err(StreamingError::new)?,
3302                );
3303                converted_response.headers_mut().insert(
3304                    XCACHELOOKUP,
3305                    "MISS".parse().map_err(StreamingError::new)?,
3306                );
3307            }
3308            return Ok(converted_response);
3309        }
3310
3311        // Bust cache keys if needed
3312        for key in &analysis.cache_bust_keys {
3313            self.manager.delete(key).await?;
3314        }
3315
3316        // Convert response to HttpResponse format for response-based cache mode evaluation
3317        let (parts, body) = response.into_parts();
3318        // Use provided metadata or generate from provider
3319        let effective_metadata = metadata.or_else(|| {
3320            self.options.generate_metadata(&analysis.request_parts, &parts)
3321        });
3322        let http_response = self.options.parts_to_http_response(
3323            &parts,
3324            &analysis.request_parts,
3325            effective_metadata.clone(),
3326        )?;
3327
3328        // Check for response-based cache mode override
3329        let effective_cache_mode = self.options.evaluate_response_cache_mode(
3330            &analysis.request_parts,
3331            &http_response,
3332            analysis.cache_mode,
3333        );
3334
3335        // Reconstruct response for further processing
3336        let response = Response::from_parts(parts, body);
3337
3338        // If response-based override says NoStore, don't cache
3339        if effective_cache_mode == CacheMode::NoStore {
3340            if !analysis.is_get_head {
3341                self.invalidate_get_head(
3342                    &analysis.request_parts,
3343                    StatusCode::from_u16(http_response.status)?,
3344                )
3345                .await;
3346            }
3347            let mut converted_response =
3348                self.manager.convert_body(response).await?;
3349            // Add cache miss headers
3350            if self.options.cache_status_headers {
3351                converted_response.headers_mut().insert(
3352                    XCACHE,
3353                    "MISS".parse().map_err(StreamingError::new)?,
3354                );
3355                converted_response.headers_mut().insert(
3356                    XCACHELOOKUP,
3357                    "MISS".parse().map_err(StreamingError::new)?,
3358                );
3359            }
3360            return Ok(converted_response);
3361        }
3362
3363        // Create policy for the response
3364        let (parts, body) = response.into_parts();
3365        let policy =
3366            self.options.create_cache_policy(&analysis.request_parts, &parts);
3367
3368        // Reconstruct response for caching
3369        let response = Response::from_parts(parts, body);
3370
3371        let should_cache_response = self.options.should_cache_response(
3372            effective_cache_mode,
3373            &http_response,
3374            analysis.is_get_head,
3375            &policy,
3376        );
3377
3378        if should_cache_response {
3379            // Extract URL from request parts for caching
3380            let request_url =
3381                extract_url_from_request_parts(&analysis.request_parts)?;
3382
3383            // Apply modify_response_before_caching shim before storing
3384            let mut response = response;
3385            apply_modify_response_shim(
3386                &self.options,
3387                &mut response,
3388                &request_url,
3389            );
3390            response.extensions_mut().insert(CachedRequestMethod(
3391                analysis.request_parts.method.clone(),
3392            ));
3393
3394            // Cache the response using the streaming manager
3395            let mut cached_response = self
3396                .manager
3397                .put(
3398                    analysis.cache_key,
3399                    response,
3400                    policy,
3401                    request_url,
3402                    effective_metadata,
3403                )
3404                .await?;
3405
3406            if !analysis.is_get_head {
3407                self.invalidate_get_head(
3408                    &analysis.request_parts,
3409                    StatusCode::from_u16(http_response.status)?,
3410                )
3411                .await;
3412            }
3413
3414            // Add cache miss headers (response is being stored for first time)
3415            if self.options.cache_status_headers {
3416                cached_response.headers_mut().insert(
3417                    XCACHE,
3418                    "MISS".parse().map_err(StreamingError::new)?,
3419                );
3420                cached_response.headers_mut().insert(
3421                    XCACHELOOKUP,
3422                    "MISS".parse().map_err(StreamingError::new)?,
3423                );
3424            }
3425            Ok(cached_response)
3426        } else {
3427            if !analysis.is_get_head {
3428                self.invalidate_get_head(
3429                    &analysis.request_parts,
3430                    StatusCode::from_u16(http_response.status)?,
3431                )
3432                .await;
3433            }
3434            // Don't cache, just convert to manager's body type
3435            let mut converted_response =
3436                self.manager.convert_body(response).await?;
3437            // Add cache miss headers
3438            if self.options.cache_status_headers {
3439                converted_response.headers_mut().insert(
3440                    XCACHE,
3441                    "MISS".parse().map_err(StreamingError::new)?,
3442                );
3443                converted_response.headers_mut().insert(
3444                    XCACHELOOKUP,
3445                    "MISS".parse().map_err(StreamingError::new)?,
3446                );
3447            }
3448            Ok(converted_response)
3449        }
3450    }
3451
3452    fn prepare_conditional_request(
3453        &self,
3454        parts: &mut request::Parts,
3455        _cached_response: &Response<Self::Body>,
3456        policy: &CachePolicy,
3457    ) -> Result<()> {
3458        let before_req = policy.before_request(parts, SystemTime::now());
3459        if let BeforeRequest::Stale { request, .. } = before_req {
3460            parts.headers.extend(request.headers);
3461        }
3462        Ok(())
3463    }
3464
3465    async fn handle_not_modified(
3466        &self,
3467        cached_response: Response<Self::Body>,
3468        fresh_parts: &response::Parts,
3469    ) -> Result<Response<Self::Body>> {
3470        let (mut parts, body) = cached_response.into_parts();
3471
3472        merge_headers(&mut parts.headers, &fresh_parts.headers);
3473
3474        let mut response = Response::from_parts(parts, body);
3475        if self.options.cache_status_headers {
3476            response_cache_status(&mut response, HitOrMiss::HIT);
3477            response_cache_lookup_status(&mut response, HitOrMiss::HIT);
3478        }
3479        Ok(response)
3480    }
3481}
3482
3483impl<T: CacheManager> HttpCacheInterface for HttpCache<T> {
3484    fn analyze_request(
3485        &self,
3486        parts: &request::Parts,
3487        mode_override: Option<CacheMode>,
3488    ) -> Result<CacheAnalysis> {
3489        self.options.analyze_request_internal(parts, mode_override, self.mode)
3490    }
3491
3492    async fn lookup_cached_response(
3493        &self,
3494        key: &str,
3495    ) -> Result<Option<(HttpResponse, CachePolicy)>> {
3496        self.manager.get(key).await
3497    }
3498
3499    async fn process_response(
3500        &self,
3501        analysis: CacheAnalysis,
3502        response: Response<Vec<u8>>,
3503        metadata: Option<Vec<u8>>,
3504    ) -> Result<Response<Vec<u8>>> {
3505        if !analysis.should_cache {
3506            if !analysis.is_get_head {
3507                self.invalidate_get_head(
3508                    &analysis.request_parts,
3509                    response.status(),
3510                )
3511                .await;
3512            }
3513            return Ok(response);
3514        }
3515
3516        // Bust cache keys if needed
3517        for key in &analysis.cache_bust_keys {
3518            self.manager.delete(key).await?;
3519        }
3520
3521        // Convert response to HttpResponse format
3522        let (parts, body) = response.into_parts();
3523        // Use provided metadata or generate from provider
3524        let effective_metadata = metadata.or_else(|| {
3525            self.options.generate_metadata(&analysis.request_parts, &parts)
3526        });
3527        let mut http_response = self.options.parts_to_http_response(
3528            &parts,
3529            &analysis.request_parts,
3530            effective_metadata,
3531        )?;
3532        http_response.body = body.clone(); // Include the body for buffered cache managers
3533
3534        // Check for response-based cache mode override
3535        let effective_cache_mode = self.options.evaluate_response_cache_mode(
3536            &analysis.request_parts,
3537            &http_response,
3538            analysis.cache_mode,
3539        );
3540
3541        // If response-based override says NoStore, don't cache
3542        if effective_cache_mode == CacheMode::NoStore {
3543            if !analysis.is_get_head {
3544                self.invalidate_get_head(
3545                    &analysis.request_parts,
3546                    StatusCode::from_u16(http_response.status)?,
3547                )
3548                .await;
3549            }
3550            let response = Response::from_parts(parts, body);
3551            return Ok(response);
3552        }
3553
3554        // Create policy and determine if we should cache based on response-based mode
3555        let policy = self.options.create_cache_policy(
3556            &analysis.request_parts,
3557            &http_response.parts()?,
3558        );
3559
3560        let should_cache_response = self.options.should_cache_response(
3561            effective_cache_mode,
3562            &http_response,
3563            analysis.is_get_head,
3564            &policy,
3565        );
3566
3567        if should_cache_response {
3568            self.options.modify_response_before_caching(&mut http_response);
3569            let cached_response = self
3570                .manager
3571                .put(analysis.cache_key, http_response, policy)
3572                .await?;
3573
3574            if !analysis.is_get_head {
3575                self.invalidate_get_head(
3576                    &analysis.request_parts,
3577                    StatusCode::from_u16(cached_response.status)?,
3578                )
3579                .await;
3580            }
3581
3582            // Convert back to standard Response
3583            let response_parts = cached_response.parts()?;
3584            let mut response = Response::builder()
3585                .status(response_parts.status)
3586                .version(response_parts.version)
3587                .body(cached_response.body)?;
3588
3589            // Copy headers from the response parts
3590            *response.headers_mut() = response_parts.headers;
3591
3592            Ok(response)
3593        } else {
3594            if !analysis.is_get_head {
3595                self.invalidate_get_head(
3596                    &analysis.request_parts,
3597                    StatusCode::from_u16(http_response.status)?,
3598                )
3599                .await;
3600            }
3601            // Don't cache, return original response
3602            let response = Response::from_parts(parts, body);
3603            Ok(response)
3604        }
3605    }
3606
3607    fn prepare_conditional_request(
3608        &self,
3609        parts: &mut request::Parts,
3610        _cached_response: &HttpResponse,
3611        policy: &CachePolicy,
3612    ) -> Result<()> {
3613        let before_req = policy.before_request(parts, SystemTime::now());
3614        if let BeforeRequest::Stale { request, .. } = before_req {
3615            parts.headers.extend(request.headers);
3616        }
3617        Ok(())
3618    }
3619
3620    async fn handle_not_modified(
3621        &self,
3622        mut cached_response: HttpResponse,
3623        fresh_parts: &response::Parts,
3624    ) -> Result<HttpResponse> {
3625        cached_response.update_headers(fresh_parts)?;
3626        if self.options.cache_status_headers {
3627            cached_response.cache_status(HitOrMiss::HIT);
3628            cached_response.cache_lookup_status(HitOrMiss::HIT);
3629        }
3630        Ok(cached_response)
3631    }
3632}
3633
3634#[cfg(test)]
3635mod test;