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)]
45pub struct Response {
46 pub error: Option<Box<ResourceError>>,
48
49 pub no_content: bool,
52
53 pub not_modified: bool,
55
56 pub prior: bool,
60
61 pub tile_not_found: bool,
65
66 pub data: Option<Data>,
68
69 pub modified: Option<Timestamp>,
70 pub etag: Option<String>,
71
72 pub caching: Caching,
75 pub no_store: bool,
77}
78
79impl Response {
80 #[must_use]
81 pub fn new() -> Self {
82 Self::default()
83 }
84}
85
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
96pub struct Caching {
97 pub expires: Option<Timestamp>,
99 pub must_revalidate: bool,
102}
103
104impl Caching {
105 #[must_use]
108 pub fn is_fresh(&self, now: Timestamp) -> bool {
109 self.expires.is_none_or(|expires| expires > now)
110 }
111
112 #[must_use]
115 pub fn is_usable(&self, now: Timestamp) -> bool {
116 !self.must_revalidate || self.is_fresh(now)
117 }
118
119 #[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}