Skip to main content

zero_client/
ttl.rs

1//! Query time-to-live (`packages/zql/src/query/ttl.ts`).
2
3use crate::json::{Value, number};
4
5/// How long a query stays cached after its last use.
6///
7/// `Forever` and negative durations never expire, `None` expires
8/// immediately. Durations are clamped to 10 minutes when sent to the server.
9#[derive(Clone, Debug, PartialEq)]
10pub enum Ttl {
11    /// Expires as soon as nothing uses the query.
12    None,
13    /// Never expires.
14    Forever,
15    /// A duration in milliseconds.
16    Milliseconds(f64),
17    /// A duration string as JS accepts it: a number followed by `s`, `m`,
18    /// `h`, `d`, or `y` (for example `"5m"`).
19    String(String),
20}
21
22/// The TTL a query gets when it doesn't name one: five minutes.
23pub const DEFAULT_TTL_MILLISECONDS: f64 = 5.0 * 60.0 * 1000.0;
24/// The longest TTL the server keeps a query for: ten minutes.
25pub const MAX_TTL_MILLISECONDS: f64 = 10.0 * 60.0 * 1000.0;
26
27fn multiplier(unit: char) -> Option<f64> {
28    Some(match unit {
29        's' => 1000.0,
30        'm' => 60.0 * 1000.0,
31        'h' => 60.0 * 60.0 * 1000.0,
32        'd' => 24.0 * 60.0 * 60.0 * 1000.0,
33        'y' => 365.0 * 24.0 * 60.0 * 60.0 * 1000.0,
34        _ => return None,
35    })
36}
37
38impl Ttl {
39    /// The default TTL as a string.
40    pub const DEFAULT: &str = "5m";
41
42    /// The TTL JS's `preload` uses when it isn't given one: the query
43    /// stops being synced as soon as its preload is cleaned up.
44    /// [`Ttl::default`] is the default of views and `run`.
45    pub const DEFAULT_PRELOAD: Ttl = Ttl::None;
46
47    /// `n` seconds.
48    pub fn seconds(n: f64) -> Ttl {
49        Ttl::String(number::format(n) + "s")
50    }
51
52    /// `n` minutes.
53    pub fn minutes(n: f64) -> Ttl {
54        Ttl::String(number::format(n) + "m")
55    }
56
57    /// `n` hours.
58    pub fn hours(n: f64) -> Ttl {
59        Ttl::String(number::format(n) + "h")
60    }
61
62    /// `n` days.
63    pub fn days(n: f64) -> Ttl {
64        Ttl::String(number::format(n) + "d")
65    }
66
67    /// A TTL as JS holds it: a string or a number.
68    pub fn from_json(v: &Value) -> Option<Ttl> {
69        match v {
70            Value::Number(n) => Some(Ttl::Milliseconds(*n)),
71            Value::String(s) => Some(Ttl::from(s.as_str())),
72            _ => None,
73        }
74    }
75
76    /// The TTL as JS holds it.
77    pub fn to_json(&self) -> Value {
78        match self {
79            Ttl::None => "none".into(),
80            Ttl::Forever => "forever".into(),
81            Ttl::Milliseconds(n) => Value::Number(*n),
82            Ttl::String(s) => s.as_str().into(),
83        }
84    }
85
86    /// `parseTTL`: milliseconds, with `-1` for never expiring.
87    pub fn parsed(&self) -> f64 {
88        match self {
89            Ttl::None => 0.0,
90            Ttl::Forever => -1.0,
91            Ttl::Milliseconds(n) if n.is_nan() => 0.0,
92            Ttl::Milliseconds(n) if !n.is_finite() || *n < 0.0 => -1.0,
93            Ttl::Milliseconds(n) => *n,
94            Ttl::String(s) if s == "none" => 0.0,
95            Ttl::String(s) if s == "forever" => -1.0,
96            Ttl::String(s) => {
97                let Some(unit) = s.chars().last() else {
98                    return f64::NAN;
99                };
100                match multiplier(unit) {
101                    Some(m) => number::parse(&s[..s.len() - unit.len_utf8()]) * m,
102                    None => f64::NAN,
103                }
104            }
105        }
106    }
107
108    /// `compareTTL`: never-expiring sorts last.
109    pub fn compare(a: &Ttl, b: &Ttl) -> f64 {
110        let (ap, bp) = (a.parsed(), b.parsed());
111        match (ap == -1.0, bp == -1.0) {
112            (true, false) => 1.0,
113            (false, true) => -1.0,
114            _ => ap - bp,
115        }
116    }
117
118    /// `normalizeTTL`: the shortest equivalent spelling of a number of
119    /// milliseconds; strings are returned as is.
120    pub fn normalized(&self) -> Ttl {
121        let Ttl::Milliseconds(ttl) = *self else {
122            return self.clone();
123        };
124        if ttl < 0.0 {
125            return Ttl::Forever;
126        }
127        if ttl == 0.0 {
128            return Ttl::None;
129        }
130        let plain = number::format(ttl);
131        let mut shortest = plain.clone();
132        for unit in ['y', 'd', 'h', 'm', 's'] {
133            let candidate =
134                number::format(ttl / multiplier(unit).expect("unit")) + &unit.to_string();
135            if candidate.encode_utf16().count() < shortest.encode_utf16().count() {
136                shortest = candidate;
137            }
138        }
139        if shortest.len() < plain.len() {
140            Ttl::String(shortest)
141        } else {
142            self.clone()
143        }
144    }
145
146    /// `clampTTL`: milliseconds, at most 10 minutes; never-expiring becomes
147    /// 10 minutes.
148    pub fn clamped(&self) -> f64 {
149        let p = self.parsed();
150        if p == -1.0 || p > MAX_TTL_MILLISECONDS {
151            MAX_TTL_MILLISECONDS
152        } else {
153            p
154        }
155    }
156}
157
158impl From<&str> for Ttl {
159    fn from(s: &str) -> Ttl {
160        match s {
161            "none" => Ttl::None,
162            "forever" => Ttl::Forever,
163            s => Ttl::String(s.to_owned()),
164        }
165    }
166}
167
168impl Default for Ttl {
169    fn default() -> Ttl {
170        Ttl::String(Ttl::DEFAULT.to_owned())
171    }
172}