1use std::time::Duration;
19
20use ruma::time::SystemTime;
21use serde::{Deserialize, Serialize};
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct TtlValue<T> {
28 #[serde(flatten)]
30 data: T,
31
32 #[serde(default = "default_timestamp")]
40 last_fetch_ts: Option<f64>,
41}
42
43impl<T> TtlValue<T> {
44 pub const STALE_THRESHOLD: f64 = (1000 * 60 * 60 * 24) as _;
48
49 pub fn new(data: T) -> Self {
51 Self { data, last_fetch_ts: Some(now_timestamp_ms()) }
52 }
53
54 pub fn without_expiry(data: T) -> Self {
56 Self { data, last_fetch_ts: None }
57 }
58
59 pub fn as_ref(&self) -> TtlValue<&T> {
61 TtlValue { data: &self.data, last_fetch_ts: self.last_fetch_ts }
62 }
63
64 pub fn map<U, F>(self, f: F) -> TtlValue<U>
66 where
67 F: FnOnce(T) -> U,
68 {
69 TtlValue { data: f(self.data), last_fetch_ts: self.last_fetch_ts }
70 }
71
72 pub fn has_expired(&self) -> bool {
75 self.has_expired_with_threshold_ms(Self::STALE_THRESHOLD)
76 }
77
78 pub fn has_expired_after(&self, ttl: Duration) -> bool {
81 self.has_expired_with_threshold_ms(ttl.as_secs_f64() * 1000.0)
82 }
83
84 fn has_expired_with_threshold_ms(&self, threshold_ms: f64) -> bool {
85 self.last_fetch_ts.is_some_and(|ts| now_timestamp_ms() - ts >= threshold_ms)
86 }
87
88 pub fn expire(&mut self) {
90 self.last_fetch_ts = Some(0.0)
93 }
94
95 pub fn data(&self) -> &T {
97 &self.data
98 }
99
100 pub fn into_data(self) -> T {
102 self.data
103 }
104}
105
106fn now_timestamp_ms() -> f64 {
108 SystemTime::now()
109 .duration_since(SystemTime::UNIX_EPOCH)
110 .expect("System clock was before 1970.")
111 .as_secs_f64()
112 * 1000.0
113}
114
115fn default_timestamp() -> Option<f64> {
120 Some(0.0)
121}
122
123#[cfg(test)]
124mod tests {
125 use std::time::Duration;
126
127 use serde::{Deserialize, Serialize};
128 use serde_json::json;
129
130 use super::{TtlValue, now_timestamp_ms};
131
132 #[test]
133 fn test_ttl_value_expiry() {
134 let ttl_value = TtlValue {
136 data: (),
137 last_fetch_ts: Some(now_timestamp_ms() - TtlValue::<()>::STALE_THRESHOLD - 1.0),
138 };
139 assert!(ttl_value.has_expired());
140
141 let ttl_value = TtlValue::new(());
143 assert!(!ttl_value.has_expired());
144
145 let ttl_value = TtlValue::without_expiry(());
147 assert!(!ttl_value.has_expired());
148 }
149
150 #[test]
151 fn test_ttl_value_expiry_with_custom_ttl() {
152 let ttl = Duration::from_secs(60 * 60);
153 let ttl_ms = ttl.as_secs_f64() * 1000.0;
154
155 let ttl_value =
157 TtlValue { data: (), last_fetch_ts: Some(now_timestamp_ms() - ttl_ms - 1.0) };
158 assert!(ttl_value.has_expired_after(ttl));
159 assert!(!ttl_value.has_expired());
160
161 let ttl_value = TtlValue::new(());
163 assert!(!ttl_value.has_expired_after(ttl));
164
165 let ttl_value = TtlValue::without_expiry(());
167 assert!(!ttl_value.has_expired_after(Duration::ZERO));
168 }
169
170 #[test]
171 fn test_ttl_value_serialize_roundtrip() {
172 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
173 struct Data {
174 foo: String,
175 }
176
177 let data = Data { foo: "bar".to_owned() };
178
179 let ttl_value = TtlValue { data: data.clone(), last_fetch_ts: Some(1000.0) };
181 let json = json!({
182 "foo": "bar",
183 "last_fetch_ts": 1000.0,
184 });
185 assert_eq!(serde_json::to_value(&ttl_value).unwrap(), json);
186
187 let deserialized = serde_json::from_value::<TtlValue<Data>>(json).unwrap();
188 assert_eq!(deserialized.data, data);
189 assert!(deserialized.last_fetch_ts.unwrap() - ttl_value.last_fetch_ts.unwrap() < 0.0001);
190
191 let json = json!({
193 "foo": "bar",
194 });
195 let deserialized = serde_json::from_value::<TtlValue<Data>>(json).unwrap();
196 assert_eq!(deserialized.data, data);
197 assert!(deserialized.last_fetch_ts.unwrap() - 0.0 < 0.0001);
198 }
199}