mln_engine/storage/
response.rs1use std::sync::Arc;
2
3use crate::storage::chrono::Timestamp;
4
5pub type Data = Arc<Vec<u8>>;
7
8#[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#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
23#[error("{message}")]
24pub struct ResourceError {
25 pub reason: Reason,
26 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#[derive(Clone, Debug, Default, PartialEq)]
44pub struct Response {
45 pub error: Option<Box<ResourceError>>,
47
48 pub no_content: bool,
51
52 pub not_modified: bool,
54
55 pub prior: bool,
59
60 pub tile_not_found: bool,
64
65 pub data: Option<Data>,
67
68 pub modified: Option<Timestamp>,
69 pub etag: Option<String>,
70
71 pub caching: Caching,
74 pub no_store: bool,
76}
77
78impl Response {
79 #[must_use]
80 pub fn new() -> Self {
81 Self::default()
82 }
83}
84
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
95pub struct Caching {
96 pub expires: Option<Timestamp>,
98 pub must_revalidate: bool,
101}
102
103impl Caching {
104 #[must_use]
107 pub fn is_fresh(&self, now: Timestamp) -> bool {
108 self.expires.is_none_or(|expires| expires > now)
109 }
110
111 #[must_use]
114 pub fn is_usable(&self, now: Timestamp) -> bool {
115 !self.must_revalidate || self.is_fresh(now)
116 }
117
118 #[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}