Skip to main content

schedr_api/series/
cache.rs

1//! The Metrics endpoints' buckets kept between requests: a bucket whose rows are all written
2//! doesn't change, so each request reads only the buckets since the last final one (the
3//! user, 2026-11-15: metrics mustn't weigh on schedr; 30 days of 100 processes took seconds a
4//! request on SQLite, and the Deployments page asks every 15 seconds in each tab).
5//!
6//! A bucket is final once it ended [`FINAL_AFTER`] ago: a minute sample is stored within the
7//! sampler's grace of its minute (a webserver's late one; `ROLL_GRACE`), a rollup once, and
8//! buckets are aligned to the epoch, so a later request's buckets are the same ones. A request
9//! for a key waits for one already reading it, so many tabs cost one read.
10
11use std::collections::{BTreeMap, HashMap};
12use std::sync::{Arc, Mutex, PoisonError};
13
14use jiff::{SignedDuration, Timestamp};
15use schedr_db::samples::{Bucket, Latest};
16
17use super::{Range, floor};
18
19#[cfg(test)]
20mod tests;
21
22/// How long after a bucket's end its rows are all stored: the sampler's grace (2 minutes)
23/// and a minute's write, with room for the clocks of the processes writing them to differ
24/// (Codex's review: a webserver stamps its own sample by its clock). A sample stored later than
25/// this misses its rollup too (2 minutes), and a webserver that read past it shows it once it
26/// starts again.
27pub const FINAL_AFTER: SignedDuration = SignedDuration::from_mins(15);
28
29/// The keys kept at most (each range, all processes or one): the least recently used go.
30const KEYS: usize = 64;
31
32/// The buckets kept for one key at most: past them a key isn't kept (a deployment of
33/// thousands of processes reads each time rather than hold them).
34const BUCKETS: usize = 100_000;
35
36/// What is asked for: the samples of each process (all, or one) or the totals, over a range.
37#[derive(Debug, Clone, PartialEq, Eq, Hash)]
38pub struct Key {
39    /// The totals (the sparkline) rather than each process's buckets.
40    pub totals: bool,
41    /// The range.
42    pub range: Range,
43    /// One process's only.
44    pub process: Option<String>,
45}
46
47/// One key's final buckets.
48#[derive(Debug, Default)]
49pub struct Entry {
50    /// The buckets before this are final and kept; none: nothing kept yet.
51    pub final_to: Option<Timestamp>,
52    /// The range's start when they were kept: a request starting before it (the clock went
53    /// back) reads all again.
54    pub kept_from: Option<Timestamp>,
55    /// Each process's final buckets, by process and time.
56    pub buckets: Vec<Bucket>,
57    /// The totals' final buckets, by time.
58    pub totals: Vec<(Timestamp, u64)>,
59    /// Each process's latest sample read (rows are only added: a later read replaces it with a
60    /// later one).
61    pub latest: BTreeMap<String, Latest>,
62}
63
64impl Entry {
65    /// Where to read from for a request over `[from, to)` in buckets of `bucket_s`: the
66    /// first bucket not kept (none kept, or the clock went back: `from`).
67    #[must_use]
68    pub fn read_from(&self, from: Timestamp, to: Timestamp) -> Timestamp {
69        match self.final_to {
70            Some(kept) if kept <= to => kept.max(from),
71            _ => from,
72        }
73    }
74
75    /// Forgets what is kept when a request over `[from, to)` isn't covered by it: the clock
76    /// went back past its end, or before its start (Codex's review of M5.1j).
77    fn clear_unless_covering(&mut self, from: Timestamp, to: Timestamp) {
78        if self.final_to.is_some_and(|kept| kept > to)
79            || self.kept_from.is_some_and(|start| from < start)
80        {
81            *self = Self::default();
82        }
83    }
84}
85
86/// The first bucket not final at `to`, in buckets of `bucket_s`, final `after` their end.
87#[must_use]
88pub fn final_to(to: Timestamp, bucket_s: u32, after: SignedDuration) -> Timestamp {
89    floor(to.checked_sub(after).unwrap_or(to), bucket_s)
90}
91
92/// A key's entry, shared by the requests asking for it, and when it was last used.
93type Slot = (u64, Arc<tokio::sync::Mutex<Entry>>);
94
95/// The kept buckets of every key.
96#[derive(Debug, Default)]
97pub struct SeriesCache {
98    entries: Mutex<HashMap<Key, Slot>>,
99    uses: std::sync::atomic::AtomicU64,
100    limits: CacheLimits,
101}
102
103/// When the cache's buckets are final, and how much it keeps (decision 493).
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct CacheLimits {
106    /// A bucket's age past its end when it is final
107    /// (`SCHEDR_HIDDEN__WEBSERVER__METRICS_FINAL_AFTER`).
108    pub final_after: SignedDuration,
109    /// The keys kept (`SCHEDR_HIDDEN__WEBSERVER__METRICS_CACHE_KEYS`).
110    pub keys: usize,
111    /// The buckets kept for one key (`SCHEDR_HIDDEN__WEBSERVER__METRICS_CACHE_BUCKETS`).
112    pub buckets: usize,
113}
114
115impl Default for CacheLimits {
116    /// [`FINAL_AFTER`], `KEYS` and `BUCKETS`.
117    fn default() -> Self {
118        Self {
119            final_after: FINAL_AFTER,
120            keys: KEYS,
121            buckets: BUCKETS,
122        }
123    }
124}
125
126impl SeriesCache {
127    /// An empty cache keeping as `limits` say.
128    #[must_use]
129    pub fn new(limits: CacheLimits) -> Self {
130        Self {
131            limits,
132            ..Self::default()
133        }
134    }
135
136    /// Its limits.
137    #[must_use]
138    pub const fn limits(&self) -> CacheLimits {
139        self.limits
140    }
141
142    /// `key`'s entry, locked: a request reading it holds it, the next waits.
143    pub async fn entry(
144        &self,
145        key: Key,
146        (from, to): (Timestamp, Timestamp),
147    ) -> tokio::sync::OwnedMutexGuard<Entry> {
148        let used = self.uses.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
149        let entry = {
150            let mut entries = self.entries.lock().unwrap_or_else(PoisonError::into_inner);
151            if !entries.contains_key(&key) && entries.len() >= self.limits.keys {
152                // Not one a request holds or waits for: another for its key would make a
153                // second lock beside it (Codex's review of M5.1j). All held: one key more.
154                let oldest = entries
155                    .iter()
156                    .filter(|(_, (_, slot))| Arc::strong_count(slot) == 1)
157                    .min_by_key(|(_, (used, _))| *used)
158                    .map(|(key, _)| key.clone());
159                if let Some(oldest) = oldest {
160                    entries.remove(&oldest);
161                }
162            }
163            let slot = entries.entry(key).or_default();
164            slot.0 = used;
165            Arc::clone(&slot.1)
166        };
167        let mut guard = entry.lock_owned().await;
168        guard.clear_unless_covering(from, to);
169        guard
170    }
171}
172
173/// `kept` and `read` (from where `kept` ends) as one list by process and time, those before
174/// `from` left out.
175#[must_use]
176pub fn merged(kept: &[Bucket], read: Vec<Bucket>, from: Timestamp) -> Vec<Bucket> {
177    let mut all: Vec<Bucket> = kept.iter().filter(|b| b.at >= from).cloned().collect();
178    all.extend(read);
179    all.sort_by(|a, b| a.process_id.cmp(&b.process_id).then(a.at.cmp(&b.at)));
180    all
181}
182
183/// Keeps `buckets`' final ones (before `final_to`) of a range starting `from` in `entry`,
184/// unless more than `most`.
185pub fn keep_buckets(
186    entry: &mut Entry,
187    buckets: &[Bucket],
188    (from, final_to): (Timestamp, Timestamp),
189    most: usize,
190) {
191    if buckets.len() > most {
192        *entry = Entry::default();
193        return;
194    }
195    entry.buckets = buckets
196        .iter()
197        .filter(|b| b.at < final_to)
198        .cloned()
199        .collect();
200    entry.final_to = Some(final_to);
201    entry.kept_from = Some(from);
202}
203
204/// `kept` and `read` totals as one list by time, those before `from` left out; the final
205/// ones kept in `entry`.
206pub fn merged_totals(
207    entry: &mut Entry,
208    read: Vec<(Timestamp, u64)>,
209    from: Timestamp,
210    final_to: Timestamp,
211) -> Vec<(Timestamp, u64)> {
212    let mut all: Vec<(Timestamp, u64)> = entry
213        .totals
214        .iter()
215        .filter(|(at, _)| *at >= from)
216        .copied()
217        .collect();
218    all.extend(read);
219    all.sort_by_key(|(at, _)| *at);
220    entry.totals = all
221        .iter()
222        .filter(|(at, _)| *at < final_to)
223        .copied()
224        .collect();
225    entry.final_to = Some(final_to);
226    entry.kept_from = Some(from);
227    all
228}
229
230/// Each process's latest sample: `kept`'s, replaced by a later one `read`, those before
231/// `from` left out.
232#[must_use]
233pub fn merged_latest(
234    kept: &BTreeMap<String, Latest>,
235    read: BTreeMap<String, Latest>,
236    from: Timestamp,
237) -> BTreeMap<String, Latest> {
238    let mut all: BTreeMap<String, Latest> = kept
239        .iter()
240        .filter(|(_, latest)| latest.at >= from)
241        .map(|(id, latest)| (id.clone(), latest.clone()))
242        .collect();
243    for (id, latest) in read {
244        if all.get(&id).is_none_or(|old| latest.at > old.at) {
245            all.insert(id, latest);
246        }
247    }
248    all
249}