Skip to main content

mln_engine/storage/
response.rs

1use std::sync::Arc;
2
3use crate::storage::chrono::Timestamp;
4
5/// A shared response body, as bytes.
6pub type Data = Arc<Vec<u8>>;
7
8/// What made a resource request fail.
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
10#[repr(u8)]
11pub enum Reason {
12    Success = 1,
13    NotFound = 2,
14    Server = 3,
15    Connection = 4,
16    RateLimit = 5,
17    #[default]
18    Other = 6,
19}
20
21/// Why a resource request failed.
22#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
23#[error("{message}")]
24pub struct ResourceError {
25    pub reason: Reason,
26    /// An error message from the request handler, e.g. a server message or a
27    /// system message informing the user about the reason for the failure.
28    pub message: String,
29    pub(crate) retry_after: Option<Timestamp>,
30}
31
32impl ResourceError {
33    pub fn new(reason: Reason, message: impl Into<String>) -> Self {
34        ResourceError { reason, message: message.into(), retry_after: None }
35    }
36
37    pub fn with_retry_after(reason: Reason, message: impl Into<String>, retry_after: Option<Timestamp>) -> Self {
38        ResourceError { reason, message: message.into(), retry_after }
39    }
40}
41
42/// The answer to a request. A clone copies the error and shares the data.
43#[derive(Clone, Debug, Default, PartialEq)]
44pub struct Response {
45    /// Why the request failed; `None` when it succeeded.
46    pub error: Option<Box<ResourceError>>,
47
48    /// The response has no body: a 204 No Content, or a 404 Not Found for a
49    /// tile.
50    pub no_content: bool,
51
52    /// A 304 Not Modified: the requester's copy is still current.
53    pub not_modified: bool,
54
55    /// The data is the copy the request carried (`Resource::prior_data`),
56    /// which a 304 delivered: a cache that stored that copy has its data
57    /// already.
58    pub prior: bool,
59
60    /// Set, with `no_content`, for a 404 Not Found for a tile, which the
61    /// tileset doesn't have, so a tile loader can tell it apart from a tile
62    /// with nothing in it.
63    pub tile_not_found: bool,
64
65    /// The body, except for an error, a 304 or no content.
66    pub data: Option<Data>,
67
68    pub modified: Option<Timestamp>,
69    pub etag: Option<String>,
70
71    /// How the data may be cached and reused. A response that never expires,
72    /// as a local file's, has the default rules.
73    pub caching: Caching,
74    /// The response must not be stored.
75    pub no_store: bool,
76}
77
78impl Response {
79    #[must_use]
80    pub fn new() -> Self {
81        Self::default()
82    }
83}
84
85/// How a copy of a resource may be reused (RFC 9111): when it stops being
86/// fresh, and whether it may be used once it is stale.
87///
88/// The map accepts a stale copy of any age, as RFC 9111 ยง5.2.1.2 lets a
89/// client (`max-stale` without a value): it shows the copy while it
90/// revalidates, and while the server can't be reached. Only the server can
91/// forbid that, with `must-revalidate` or `no-cache`. Its
92/// `stale-while-revalidate` and `stale-if-error` (RFC 5861) permit what the
93/// map accepts anyway, so they aren't read.
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
95pub struct Caching {
96    /// When it stops being fresh; `None` if it never does.
97    pub expires: Option<Timestamp>,
98    /// Once stale, it may not be used until it revalidates, not even while
99    /// the server can't be reached.
100    pub must_revalidate: bool,
101}
102
103impl Caching {
104    /// Whether the copy is fresh at `now`: it may be used without asking the
105    /// server.
106    #[must_use]
107    pub fn is_fresh(&self, now: Timestamp) -> bool {
108        self.expires.is_none_or(|expires| expires > now)
109    }
110
111    /// Whether the copy may be used at `now`: it is fresh, or it may be used
112    /// stale.
113    #[must_use]
114    pub fn is_usable(&self, now: Timestamp) -> bool {
115        !self.must_revalidate || self.is_fresh(now)
116    }
117
118    /// Until when the copy may be used; `None` if it always may.
119    #[must_use]
120    pub fn usable_until(&self) -> Option<Timestamp> {
121        if self.must_revalidate { self.expires } else { None }
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    fn at(secs: i64) -> Timestamp {
130        Timestamp::from_secs(1000 + secs)
131    }
132
133    #[test]
134    fn a_stale_copy_is_usable_unless_it_must_revalidate() {
135        let now = at(0);
136        let stale = Caching { expires: Some(at(-10)), must_revalidate: false };
137        let must_revalidate = Caching { must_revalidate: true, ..stale };
138        assert!(Caching::default().is_fresh(now) && Caching::default().is_usable(now));
139        assert!(!stale.is_fresh(now) && stale.is_usable(now));
140        assert!(!must_revalidate.is_usable(now));
141        assert!(Caching { expires: Some(at(10)), ..must_revalidate }.is_usable(now));
142        assert_eq!(stale.usable_until(), None);
143        assert_eq!(must_revalidate.usable_until(), Some(at(-10)));
144    }
145}