dioxus_isrg/
freshness.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::time::Duration;

use chrono::{DateTime, Utc};

/// Information about the freshness of a rendered response
#[derive(Debug, Clone, Copy)]
pub struct RenderFreshness {
    /// The age of the rendered response
    age: u64,
    /// The maximum age of the rendered response
    max_age: Option<u64>,
    /// The time the response was rendered
    timestamp: DateTime<Utc>,
}

impl RenderFreshness {
    /// Create new freshness information
    pub(crate) fn new(age: u64, max_age: u64, timestamp: DateTime<Utc>) -> Self {
        Self {
            age,
            max_age: Some(max_age),
            timestamp,
        }
    }

    /// Create new freshness information with only the age
    pub(crate) fn new_age(age: u64, timestamp: DateTime<Utc>) -> Self {
        Self {
            age,
            max_age: None,
            timestamp,
        }
    }

    /// Create new freshness information from a 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,
        }
    }

    /// Create new freshness information at the current time
    pub fn now(max_age: Option<Duration>) -> Self {
        Self {
            age: 0,
            max_age: max_age.map(|d| d.as_secs()),
            timestamp: Utc::now(),
        }
    }

    /// Get the age of the rendered response in seconds
    pub fn age(&self) -> u64 {
        self.age
    }

    /// Get the maximum age of the rendered response in seconds
    pub fn max_age(&self) -> Option<u64> {
        self.max_age
    }

    /// Get the time the response was rendered
    pub fn timestamp(&self) -> DateTime<Utc> {
        self.timestamp
    }

    /// Write the freshness to the response headers.
    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(),
            );
        }
    }
}