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    /// `n` seconds.
43    pub fn seconds(n: f64) -> Ttl {
44        Ttl::String(number::format(n) + "s")
45    }
46
47    /// `n` minutes.
48    pub fn minutes(n: f64) -> Ttl {
49        Ttl::String(number::format(n) + "m")
50    }
51
52    /// `n` hours.
53    pub fn hours(n: f64) -> Ttl {
54        Ttl::String(number::format(n) + "h")
55    }
56
57    /// `n` days.
58    pub fn days(n: f64) -> Ttl {
59        Ttl::String(number::format(n) + "d")
60    }
61
62    /// A TTL as JS holds it: a string or a number.
63    pub fn from_json(v: &Value) -> Option<Ttl> {
64        match v {
65            Value::Number(n) => Some(Ttl::Milliseconds(*n)),
66            Value::String(s) => Some(Ttl::from(s.as_str())),
67            _ => None,
68        }
69    }
70
71    /// The TTL as JS holds it.
72    pub fn to_json(&self) -> Value {
73        match self {
74            Ttl::None => "none".into(),
75            Ttl::Forever => "forever".into(),
76            Ttl::Milliseconds(n) => Value::Number(*n),
77            Ttl::String(s) => s.as_str().into(),
78        }
79    }
80
81    /// `parseTTL`: milliseconds, with `-1` for never expiring.
82    pub fn parsed(&self) -> f64 {
83        match self {
84            Ttl::None => 0.0,
85            Ttl::Forever => -1.0,
86            Ttl::Milliseconds(n) if n.is_nan() => 0.0,
87            Ttl::Milliseconds(n) if !n.is_finite() || *n < 0.0 => -1.0,
88            Ttl::Milliseconds(n) => *n,
89            Ttl::String(s) if s == "none" => 0.0,
90            Ttl::String(s) if s == "forever" => -1.0,
91            Ttl::String(s) => {
92                let Some(unit) = s.chars().last() else {
93                    return f64::NAN;
94                };
95                match multiplier(unit) {
96                    Some(m) => number::parse(&s[..s.len() - unit.len_utf8()]) * m,
97                    None => f64::NAN,
98                }
99            }
100        }
101    }
102
103    /// `compareTTL`: never-expiring sorts last.
104    pub fn compare(a: &Ttl, b: &Ttl) -> f64 {
105        let (ap, bp) = (a.parsed(), b.parsed());
106        match (ap == -1.0, bp == -1.0) {
107            (true, false) => 1.0,
108            (false, true) => -1.0,
109            _ => ap - bp,
110        }
111    }
112
113    /// `normalizeTTL`: the shortest equivalent spelling of a number of
114    /// milliseconds; strings are returned as is.
115    pub fn normalized(&self) -> Ttl {
116        let Ttl::Milliseconds(ttl) = *self else {
117            return self.clone();
118        };
119        if ttl < 0.0 {
120            return Ttl::Forever;
121        }
122        if ttl == 0.0 {
123            return Ttl::None;
124        }
125        let plain = number::format(ttl);
126        let mut shortest = plain.clone();
127        for unit in ['y', 'd', 'h', 'm', 's'] {
128            let candidate =
129                number::format(ttl / multiplier(unit).expect("unit")) + &unit.to_string();
130            if candidate.encode_utf16().count() < shortest.encode_utf16().count() {
131                shortest = candidate;
132            }
133        }
134        if shortest.len() < plain.len() {
135            Ttl::String(shortest)
136        } else {
137            self.clone()
138        }
139    }
140
141    /// `clampTTL`: milliseconds, at most 10 minutes; never-expiring becomes
142    /// 10 minutes.
143    pub fn clamped(&self) -> f64 {
144        let p = self.parsed();
145        if p == -1.0 || p > MAX_TTL_MILLISECONDS {
146            MAX_TTL_MILLISECONDS
147        } else {
148            p
149        }
150    }
151}
152
153impl From<&str> for Ttl {
154    fn from(s: &str) -> Ttl {
155        match s {
156            "none" => Ttl::None,
157            "forever" => Ttl::Forever,
158            s => Ttl::String(s.to_owned()),
159        }
160    }
161}
162
163impl Default for Ttl {
164    fn default() -> Ttl {
165        Ttl::String(Ttl::DEFAULT.to_owned())
166    }
167}