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/// `Response`. `Clone` is the C++ copy constructor (the error is copied,
43/// the data shared).
44#[derive(Clone, Debug, Default, PartialEq)]
45pub struct Response {
46    /// Why the request failed; `None` when it succeeded.
47    pub error: Option<Box<ResourceError>>,
48
49    /// The response has no body: a 204 No Content, or a 404 Not Found for a
50    /// tile.
51    pub no_content: bool,
52
53    /// A 304 Not Modified: the requester's copy is still current.
54    pub not_modified: bool,
55
56    /// The data is the copy the request carried (`Resource::prior_data`),
57    /// which a 304 delivered: a cache that stored that copy has its data
58    /// already.
59    pub prior: bool,
60
61    /// Set, with `no_content`, for a 404 Not Found for a tile, which the
62    /// tileset doesn't have, so a tile loader can tell it apart from a tile
63    /// with nothing in it.
64    pub tile_not_found: bool,
65
66    /// The body, except for an error, a 304 or no content.
67    pub data: Option<Data>,
68
69    pub modified: Option<Timestamp>,
70    pub etag: Option<String>,
71
72    /// How the data may be cached and reused. A response that never expires,
73    /// as a local file's, has the default rules.
74    pub caching: Caching,
75    /// The response must not be stored.
76    pub no_store: bool,
77}
78
79impl Response {
80    #[must_use]
81    pub fn new() -> Self {
82        Self::default()
83    }
84}
85
86/// How a copy of a resource may be reused (RFC 9111): when it stops being
87/// fresh, and whether it may be used once it is stale.
88///
89/// The map accepts a stale copy of any age, as RFC 9111 ยง5.2.1.2 lets a
90/// client (`max-stale` without a value): it shows the copy while it
91/// revalidates, and while the server can't be reached. Only the server can
92/// forbid that, with `must-revalidate` or `no-cache`. Its
93/// `stale-while-revalidate` and `stale-if-error` (RFC 5861) permit what the
94/// map accepts anyway, so they aren't read.
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
96pub struct Caching {
97    /// When it stops being fresh; `None` if it never does.
98    pub expires: Option<Timestamp>,
99    /// Once stale, it may not be used until it revalidates, not even while
100    /// the server can't be reached.
101    pub must_revalidate: bool,
102}
103
104impl Caching {
105    /// Whether the copy is fresh at `now`: it may be used without asking the
106    /// server.
107    #[must_use]
108    pub fn is_fresh(&self, now: Timestamp) -> bool {
109        self.expires.is_none_or(|expires| expires > now)
110    }
111
112    /// Whether the copy may be used at `now`: it is fresh, or it may be used
113    /// stale.
114    #[must_use]
115    pub fn is_usable(&self, now: Timestamp) -> bool {
116        !self.must_revalidate || self.is_fresh(now)
117    }
118
119    /// Until when the copy may be used; `None` if it always may.
120    #[must_use]
121    pub fn usable_until(&self) -> Option<Timestamp> {
122        if self.must_revalidate { self.expires } else { None }
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    fn at(secs: i64) -> Timestamp {
131        Timestamp::from_secs(1000 + secs)
132    }
133
134    #[test]
135    fn a_stale_copy_is_usable_unless_it_must_revalidate() {
136        let now = at(0);
137        let stale = Caching { expires: Some(at(-10)), must_revalidate: false };
138        let must_revalidate = Caching { must_revalidate: true, ..stale };
139        assert!(Caching::default().is_fresh(now) && Caching::default().is_usable(now));
140        assert!(!stale.is_fresh(now) && stale.is_usable(now));
141        assert!(!must_revalidate.is_usable(now));
142        assert!(Caching { expires: Some(at(10)), ..must_revalidate }.is_usable(now));
143        assert_eq!(stale.usable_until(), None);
144        assert_eq!(must_revalidate.usable_until(), Some(at(-10)));
145    }
146}