use std::time::Duration;
use chrono::{DateTime, Utc};
#[derive(Debug, Clone, Copy)]
pub struct RenderFreshness {
age: u64,
max_age: Option<u64>,
timestamp: DateTime<Utc>,
}
impl RenderFreshness {
pub(crate) fn new(age: u64, max_age: u64, timestamp: DateTime<Utc>) -> Self {
Self {
age,
max_age: Some(max_age),
timestamp,
}
}
pub(crate) fn new_age(age: u64, timestamp: DateTime<Utc>) -> Self {
Self {
age,
max_age: None,
timestamp,
}
}
pub(crate) fn created_at(timestamp: DateTime<Utc>, max_age: Option<Duration>) -> Self {
Self {
age: timestamp
.signed_duration_since(Utc::now())
.num_seconds()
.unsigned_abs(),
max_age: max_age.map(|d| d.as_secs()),
timestamp,
}
}
pub fn now(max_age: Option<Duration>) -> Self {
Self {
age: 0,
max_age: max_age.map(|d| d.as_secs()),
timestamp: Utc::now(),
}
}
pub fn age(&self) -> u64 {
self.age
}
pub fn max_age(&self) -> Option<u64> {
self.max_age
}
pub fn timestamp(&self) -> DateTime<Utc> {
self.timestamp
}
pub fn write(&self, headers: &mut http::HeaderMap<http::HeaderValue>) {
let age = self.age();
headers.insert(http::header::AGE, age.into());
if let Some(max_age) = self.max_age() {
headers.insert(
http::header::CACHE_CONTROL,
http::HeaderValue::from_str(&format!("max-age={}", max_age)).unwrap(),
);
}
}
}