1use 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
22pub const FINAL_AFTER: SignedDuration = SignedDuration::from_mins(15);
28
29const KEYS: usize = 64;
31
32const BUCKETS: usize = 100_000;
35
36#[derive(Debug, Clone, PartialEq, Eq, Hash)]
38pub struct Key {
39 pub totals: bool,
41 pub range: Range,
43 pub process: Option<String>,
45}
46
47#[derive(Debug, Default)]
49pub struct Entry {
50 pub final_to: Option<Timestamp>,
52 pub kept_from: Option<Timestamp>,
55 pub buckets: Vec<Bucket>,
57 pub totals: Vec<(Timestamp, u64)>,
59 pub latest: BTreeMap<String, Latest>,
62}
63
64impl Entry {
65 #[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 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#[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
92type Slot = (u64, Arc<tokio::sync::Mutex<Entry>>);
94
95#[derive(Debug, Default)]
97pub struct SeriesCache {
98 entries: Mutex<HashMap<Key, Slot>>,
99 uses: std::sync::atomic::AtomicU64,
100 limits: CacheLimits,
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct CacheLimits {
106 pub final_after: SignedDuration,
109 pub keys: usize,
111 pub buckets: usize,
113}
114
115impl Default for CacheLimits {
116 fn default() -> Self {
118 Self {
119 final_after: FINAL_AFTER,
120 keys: KEYS,
121 buckets: BUCKETS,
122 }
123 }
124}
125
126impl SeriesCache {
127 #[must_use]
129 pub fn new(limits: CacheLimits) -> Self {
130 Self {
131 limits,
132 ..Self::default()
133 }
134 }
135
136 #[must_use]
138 pub const fn limits(&self) -> CacheLimits {
139 self.limits
140 }
141
142 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 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#[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
183pub 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
204pub 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#[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}