Skip to main content

matrix_sdk_common/
ttl.rs

1// Copyright 2025 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Types to implement TTL caches which can be used to persist data for a fixed
16//! duration.
17
18use std::time::Duration;
19
20use ruma::time::SystemTime;
21use serde::{Deserialize, Serialize};
22
23/// A value that expires after some time.
24///
25/// This value is (de)serializable so it can be persisted in a store.
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct TtlValue<T> {
28    /// The data of the item.
29    #[serde(flatten)]
30    data: T,
31
32    /// Last time we fetched this data from the server, in milliseconds since
33    /// UNIX epoch.
34    ///
35    /// When this field is missing during deserialization, it defaults to `0.0`,
36    /// which means that the data is always expired. This allows to be
37    /// compatible with data that was persisted before deciding to add an
38    /// expiration time.
39    #[serde(default = "default_timestamp")]
40    last_fetch_ts: Option<f64>,
41}
42
43impl<T> TtlValue<T> {
44    /// The number of milliseconds after which the data is considered stale.
45    ///
46    /// This matches 1 day.
47    pub const STALE_THRESHOLD: f64 = (1000 * 60 * 60 * 24) as _;
48
49    /// Construct a new `TtlValue` with the given data.
50    pub fn new(data: T) -> Self {
51        Self { data, last_fetch_ts: Some(now_timestamp_ms()) }
52    }
53
54    /// Construct a new `TtlValue` with the given data that never expires.
55    pub fn without_expiry(data: T) -> Self {
56        Self { data, last_fetch_ts: None }
57    }
58
59    /// Converts from `&TtlValue<T>` to `TtlValue<&T>`.
60    pub fn as_ref(&self) -> TtlValue<&T> {
61        TtlValue { data: &self.data, last_fetch_ts: self.last_fetch_ts }
62    }
63
64    /// Transform the data of this `TtlValue` with the given function.
65    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    /// Whether this value has expired, using the default
73    /// [`Self::STALE_THRESHOLD`].
74    pub fn has_expired(&self) -> bool {
75        self.has_expired_with_threshold_ms(Self::STALE_THRESHOLD)
76    }
77
78    /// Whether this value has expired, using the given time-to-live instead of
79    /// the default [`Self::STALE_THRESHOLD`].
80    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    /// Mark this value has expired.
89    pub fn expire(&mut self) {
90        // We assume that the system time is always correct and we are far from
91        // the UNIX epoch so a timestamp of 0 should always be expired.
92        self.last_fetch_ts = Some(0.0)
93    }
94
95    /// Get a reference to the data of this value.
96    pub fn data(&self) -> &T {
97        &self.data
98    }
99
100    /// Get the data of this value.
101    pub fn into_data(self) -> T {
102        self.data
103    }
104}
105
106/// Get the current timestamp as the number of milliseconds since Unix Epoch.
107fn 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
115/// The default timestamp if it is missing during deserialization.
116///
117/// We expect that a value that was serialized always has an expiry time, so the
118/// default is `Some(0.0)`.
119fn 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        // Definitely stale.
135        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        // Definitely not stale.
142        let ttl_value = TtlValue::new(());
143        assert!(!ttl_value.has_expired());
144
145        // Cannot be stale.
146        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        // Stale with the custom TTL, but not with the default one.
156        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        // Not stale.
162        let ttl_value = TtlValue::new(());
163        assert!(!ttl_value.has_expired_after(ttl));
164
165        // Cannot be stale.
166        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        // With timestamp.
180        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        // Without timestamp the value is always expired in theory.
192        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}