use bytes::Bytes;
use reqwest::header;
use std::hash::Hash;
use std::time::Instant;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RevalidationFailure {
#[default]
ServeStale,
Fail,
}
const UNREADABLE_LINK: &str = r#"<>; rel="next""#;
pub(super) struct ResponseValidators {
etag: Option<String>,
last_modified: Option<String>,
link: Option<String>,
}
impl ResponseValidators {
pub(super) fn from_headers(headers: &header::HeaderMap) -> Self {
let single = |name: header::HeaderName| {
headers
.get(name)
.and_then(|v| v.to_str().ok())
.map(String::from)
};
let links: Vec<&str> = headers
.get_all(header::LINK)
.iter()
.map(|v| v.to_str().unwrap_or(UNREADABLE_LINK))
.collect();
Self {
etag: single(header::ETAG),
last_modified: single(header::LAST_MODIFIED),
link: (!links.is_empty()).then(|| links.join(", ")),
}
}
pub(super) fn into_response(self, body: Bytes) -> CachedResponse {
CachedResponse {
body,
etag: self.etag,
last_modified: self.last_modified,
link: self.link,
fetched_at: Instant::now(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CredentialPartition(u64);
impl CredentialPartition {
#[must_use]
pub const fn new(raw: u64) -> Self {
Self(raw)
}
pub(super) const fn get(self) -> u64 {
self.0
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct CachedResponse {
pub body: Bytes,
pub etag: Option<String>,
pub last_modified: Option<String>,
pub link: Option<String>,
pub fetched_at: Instant,
}
impl CachedResponse {
#[must_use]
pub fn new(body: Bytes) -> Self {
Self {
body,
etag: None,
last_modified: None,
link: None,
fetched_at: Instant::now(),
}
}
#[must_use]
pub fn with_link(mut self, link: impl Into<String>) -> Self {
self.link = Some(link.into());
self
}
#[must_use]
pub fn with_etag(mut self, etag: impl Into<String>) -> Self {
self.etag = Some(etag.into());
self
}
#[must_use]
pub fn with_last_modified(mut self, last_modified: impl Into<String>) -> Self {
self.last_modified = Some(last_modified.into());
self
}
#[must_use]
pub const fn with_fetched_at(mut self, fetched_at: Instant) -> Self {
self.fetched_at = fetched_at;
self
}
}