Skip to main content

deps_core/cache/
response.rs

1//! Cached response entries with their validators and credential partitions.
2
3use bytes::Bytes;
4use reqwest::header;
5use std::hash::Hash;
6use std::time::Instant;
7
8/// What a cached read does when revalidating a stored entry fails.
9///
10/// A caller that merges several cached responses into one answer (a paginated list) cannot
11/// accept a silently stale part: the merged result would mix generations.
12///
13/// # Examples
14///
15/// ```
16/// use deps_core::cache::RevalidationFailure;
17///
18/// assert_eq!(RevalidationFailure::default(), RevalidationFailure::ServeStale);
19/// ```
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21pub enum RevalidationFailure {
22    /// Serve the stored entry and log the failure (stale-while-revalidate).
23    #[default]
24    ServeStale,
25    /// Return the revalidation error and keep the stored entry.
26    Fail,
27}
28
29/// Stands in for a `Link` header value that is not visible ASCII, so a caller detecting
30/// pagination fails closed (treats the list as truncated) instead of silently ignoring it.
31const UNREADABLE_LINK: &str = r#"<>; rel="next""#;
32
33/// The response headers a [`CachedResponse`] keeps, captured before the body consumes the
34/// response.
35pub(super) struct ResponseValidators {
36    etag: Option<String>,
37    last_modified: Option<String>,
38    link: Option<String>,
39}
40
41impl ResponseValidators {
42    pub(super) fn from_headers(headers: &header::HeaderMap) -> Self {
43        let single = |name: header::HeaderName| {
44            headers
45                .get(name)
46                .and_then(|v| v.to_str().ok())
47                .map(String::from)
48        };
49        let links: Vec<&str> = headers
50            .get_all(header::LINK)
51            .iter()
52            .map(|v| v.to_str().unwrap_or(UNREADABLE_LINK))
53            .collect();
54        Self {
55            etag: single(header::ETAG),
56            last_modified: single(header::LAST_MODIFIED),
57            link: (!links.is_empty()).then(|| links.join(", ")),
58        }
59    }
60
61    pub(super) fn into_response(self, body: Bytes) -> CachedResponse {
62        CachedResponse {
63            body,
64            etag: self.etag,
65            last_modified: self.last_modified,
66            link: self.link,
67            fetched_at: Instant::now(),
68        }
69    }
70}
71
72/// Identifies the credential state a trusted-origin response was fetched under, so the cache can
73/// keep bodies of different states apart (see
74/// [`HttpCache::get_cached_trusted_origin_response`](crate::cache::HttpCache::get_cached_trusted_origin_response)).
75///
76/// A distinct type from the credential-header digests used for pinned requests: the two are
77/// both hashes, but only a partition is a statement about "which state", and mixing them up
78/// would silently share or split cache entries.
79///
80/// # Examples
81///
82/// ```
83/// use deps_core::cache::CredentialPartition;
84///
85/// assert_eq!(CredentialPartition::new(7), CredentialPartition::new(7));
86/// assert_ne!(CredentialPartition::new(7), CredentialPartition::new(8));
87/// ```
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89pub struct CredentialPartition(u64);
90
91impl CredentialPartition {
92    /// Wraps the caller's hash of its credential state.
93    #[must_use]
94    pub const fn new(raw: u64) -> Self {
95        Self(raw)
96    }
97
98    pub(super) const fn get(self) -> u64 {
99        self.0
100    }
101}
102
103/// Cached HTTP response with validation headers.
104///
105/// Stores response body and cache validation headers (ETag, Last-Modified)
106/// for efficient conditional requests. The body uses `Bytes` which is an
107/// Arc-like type optimized for network data, enabling zero-cost cloning
108/// across multiple consumers without copying.
109///
110/// # Examples
111///
112/// ```
113/// use deps_core::cache::CachedResponse;
114/// use bytes::Bytes;
115/// use std::time::Instant;
116///
117/// let response = CachedResponse::new(Bytes::from("response data")).with_etag("\"abc123\"");
118///
119/// // Clone is cheap - only increments reference count
120/// let cloned = response.clone();
121/// ```
122#[non_exhaustive]
123#[derive(Debug, Clone)]
124pub struct CachedResponse {
125    /// Raw response body, shareable across consumers without copying.
126    pub body: Bytes,
127    /// `ETag` header from the response, used for `If-None-Match` revalidation.
128    pub etag: Option<String>,
129    /// `Last-Modified` header from the response, used for `If-Modified-Since` revalidation.
130    pub last_modified: Option<String>,
131    /// Raw `Link` header (RFC 8288) from the response, kept so a caller can detect a paginated
132    /// list (see `pagination::ListCoverage::from_link_header`). Several `Link` headers are
133    /// joined with `, `. Carried over unchanged on a 304 revalidation.
134    pub link: Option<String>,
135    /// Local time the response was fetched, used for TTL expiry checks.
136    pub fetched_at: Instant,
137}
138
139impl CachedResponse {
140    /// Constructs a `CachedResponse` for `body`, fetched now, with [`Self::etag`] and
141    /// [`Self::last_modified`] left `None` — chain [`Self::with_etag`] and/or
142    /// [`Self::with_last_modified`] to attach them.
143    ///
144    /// Needed because [`Self`] is `#[non_exhaustive]`: a struct literal only works inside
145    /// this crate, so every other crate must go through this constructor instead.
146    ///
147    /// # Examples
148    ///
149    /// ```
150    /// use deps_core::cache::CachedResponse;
151    /// use bytes::Bytes;
152    ///
153    /// let response = CachedResponse::new(Bytes::from("response data")).with_etag("\"abc123\"");
154    /// assert_eq!(response.etag.as_deref(), Some("\"abc123\""));
155    /// ```
156    #[must_use]
157    pub fn new(body: Bytes) -> Self {
158        Self {
159            body,
160            etag: None,
161            last_modified: None,
162            link: None,
163            fetched_at: Instant::now(),
164        }
165    }
166
167    /// Attaches the response's `Link` header. See [`Self::link`].
168    #[must_use]
169    pub fn with_link(mut self, link: impl Into<String>) -> Self {
170        self.link = Some(link.into());
171        self
172    }
173
174    /// Attaches the response's `ETag` header. See [`Self::etag`].
175    #[must_use]
176    pub fn with_etag(mut self, etag: impl Into<String>) -> Self {
177        self.etag = Some(etag.into());
178        self
179    }
180
181    /// Attaches the response's `Last-Modified` header. See [`Self::last_modified`].
182    #[must_use]
183    pub fn with_last_modified(mut self, last_modified: impl Into<String>) -> Self {
184        self.last_modified = Some(last_modified.into());
185        self
186    }
187
188    /// Overrides when the response was fetched — otherwise [`Self::new`] stamps
189    /// [`Instant::now`]. Lets external code (tests, benches) construct a backdated entry to
190    /// exercise TTL-expiry behavior, the one thing a direct struct literal used to allow.
191    #[must_use]
192    pub const fn with_fetched_at(mut self, fetched_at: Instant) -> Self {
193        self.fetched_at = fetched_at;
194        self
195    }
196}