1#![expect(
4 clippy::missing_errors_doc,
5 reason = "handler docs become OpenAPI descriptions; errors are listed as responses"
6)]
7
8use axum::Json;
9use axum::extract::rejection::QueryRejection;
10use axum::extract::{Query, State};
11use jiff::{SignedDuration, Timestamp};
12use schedr_db::samples::{Bucket, MINUTE, ROLLUP};
13
14use crate::error::ApiError;
15use crate::routes::ApiResult;
16use crate::state::ApiState;
17use crate::views::{
18 CoverageView, MemoryPointView, MemoryTotals, PartsPointView, ProcessSamplesView,
19 SamplePointView, SampleSeriesList, TaskMemoryView, WorkerPartsView,
20};
21
22pub mod cache;
23#[cfg(test)]
24mod tests;
25
26const PARTS_WITHIN: SignedDuration = SignedDuration::from_mins(5);
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
31pub enum Range {
32 Hour,
34 Day,
36 Week,
38 Month,
40}
41
42impl Range {
43 pub const ALL: [Self; 4] = [Self::Hour, Self::Day, Self::Week, Self::Month];
45
46 #[must_use]
48 pub fn parse(name: &str) -> Option<Self> {
49 Self::ALL.into_iter().find(|range| range.name() == name)
50 }
51
52 #[must_use]
54 pub const fn name(self) -> &'static str {
55 match self {
56 Self::Hour => "1h",
57 Self::Day => "24h",
58 Self::Week => "7d",
59 Self::Month => "30d",
60 }
61 }
62
63 #[must_use]
65 pub const fn span_s(self) -> i64 {
66 match self {
67 Self::Hour => 3600,
68 Self::Day => 86_400,
69 Self::Week => 7 * 86_400,
70 Self::Month => 30 * 86_400,
71 }
72 }
73
74 #[must_use]
76 pub const fn source(self) -> u32 {
77 match self {
78 Self::Hour | Self::Day => MINUTE,
79 Self::Week | Self::Month => ROLLUP,
80 }
81 }
82
83 #[must_use]
85 pub const fn bucket_s(self) -> u32 {
86 match self {
87 Self::Hour => 60,
88 Self::Day => 360,
89 Self::Week => 2700,
90 Self::Month => 10_800,
91 }
92 }
93
94 #[must_use]
97 pub fn from(self, to: Timestamp) -> Timestamp {
98 floor(to, self.bucket_s())
99 .checked_sub(SignedDuration::from_secs(
100 self.span_s() - i64::from(self.bucket_s()),
101 ))
102 .unwrap_or(Timestamp::UNIX_EPOCH)
103 }
104
105 #[must_use]
111 pub fn cut(self, to: Timestamp, rolled: Option<Timestamp>) -> Timestamp {
112 let from = self.from(to);
113 if self.source() == MINUTE {
114 return from;
115 }
116 rolled.map_or(from, |rolled| rolled.clamp(from, to))
117 }
118
119 async fn bounds(
121 self,
122 db: &schedr_db::Database,
123 to: Timestamp,
124 ) -> Result<(Timestamp, Timestamp, Timestamp), ApiError> {
125 let rolled = if self.source() == MINUTE {
126 None
127 } else {
128 db.rolled_up_to().await?
129 };
130 Ok((self.from(to), self.cut(to, rolled), to))
131 }
132}
133
134#[derive(Debug, serde::Deserialize, utoipa::IntoParams)]
136#[into_params(parameter_in = Query)]
137pub struct SeriesQuery {
138 pub range: Option<String>,
140 pub process: Option<String>,
142}
143
144pub(crate) fn range_of(name: Option<&str>) -> Result<Range, ApiError> {
146 name.map_or(Ok(Range::Day), |name| {
147 Range::parse(name).ok_or_else(|| {
148 ApiError::BadRequest(format!(
149 "`range` is one of 1h, 24h, 7d and 30d, not `{name}`"
150 ))
151 })
152 })
153}
154
155#[utoipa::path(get, path = "/api/v1/metrics/samples", tag = "workers", params(SeriesQuery),
158 responses((status = 200, body = SampleSeriesList), (status = 400, body = crate::views::ErrorBody)))]
159pub async fn list_samples(
160 State(state): State<ApiState>,
161 query: Result<Query<SeriesQuery>, QueryRejection>,
162) -> ApiResult<SampleSeriesList> {
163 let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
164 let range = range_of(query.range.as_deref())?;
165 let to = (state.clock)();
166 let bounds = range.bounds(&state.db, to).await?;
167 let (from, cut, _) = bounds;
168 let process = query.process.as_deref();
169 let key = cache::Key {
174 totals: false,
175 range,
176 process: query.process.clone(),
177 };
178 let mut entry = state.series.entry(key, (from, to)).await;
179 let read_from = entry.read_from(from, to);
180 let read = state
181 .db
182 .sample_buckets((read_from, cut, to), range.bucket_s(), process)
183 .await?;
184 let buckets = cache::merged(&entry.buckets, read, from);
185 let limits = state.series.limits();
186 let final_to = cache::final_to(to, range.bucket_s(), limits.final_after);
187 let read_latest = state.db.latest_of(read_from, to, process).await?;
188 let mut latest_of = cache::merged_latest(&entry.latest, read_latest, from);
189 entry.latest.clone_from(&latest_of);
190 cache::keep_buckets(&mut entry, &buckets, (from, final_to), limits.buckets);
191 drop(entry);
192 let coverage: Vec<CoverageView> = buckets
195 .iter()
196 .map(|b| (b.at, b.covered))
197 .collect::<std::collections::BTreeMap<_, _>>()
198 .into_iter()
199 .map(|(at, minutes)| CoverageView { at, minutes })
200 .collect();
201 let parts_since = to.checked_sub(PARTS_WITHIN).unwrap_or(to);
204 let sampled_since = to.checked_sub(state.limits.sampled_within).unwrap_or(to);
205 let latest = state
206 .db
207 .samples_of(MINUTE, parts_since.min(sampled_since), to, process)
208 .await?;
209 let mut processes: Vec<ProcessSamplesView> = Vec::new();
210 for bucket in buckets {
211 if processes
212 .last()
213 .is_none_or(|p| p.process_id != bucket.process_id)
214 {
215 let sampled = latest
216 .iter()
217 .any(|s| s.process_id == bucket.process_id && s.at >= sampled_since);
218 processes.push(ProcessSamplesView {
219 container_limit: latest_of
220 .get(&bucket.process_id)
221 .and_then(|l| l.container_limit),
222 ended: !sampled,
223 roles: latest_of
224 .remove(&bucket.process_id)
225 .map(|l| l.roles)
226 .unwrap_or_default(),
227 process_id: bucket.process_id.clone(),
228 points: Vec::new(),
229 parts: None,
230 });
231 }
232 if let Some(process) = processes.last_mut() {
233 process.points.push(point(&bucket));
234 }
235 }
236 for process in &mut processes {
237 let last = latest
238 .iter()
239 .rev()
240 .find(|s| s.process_id == process.process_id && s.at >= parts_since);
241 process.parts = last.and_then(|s| {
242 s.parts.clone().map(|parts| WorkerPartsView {
243 at: s.at,
244 fork_servers_bytes: parts.fork_servers_bytes,
245 watcher_hosts_bytes: parts.watcher_hosts_bytes,
246 tasks_bytes: parts.tasks_bytes,
247 largest_tasks: parts
248 .largest_tasks
249 .into_iter()
250 .map(TaskMemoryView::from)
251 .collect(),
252 })
253 });
254 }
255 Ok(Json(SampleSeriesList {
256 coverage,
257 range: range.name().to_owned(),
258 step_s: range.bucket_s(),
259 from,
260 to,
261 processes,
262 }))
263}
264
265#[utoipa::path(get, path = "/api/v1/metrics/memory", tag = "workers", params(SeriesQuery),
267 responses((status = 200, body = MemoryTotals), (status = 400, body = crate::views::ErrorBody)))]
268pub async fn memory_totals(
269 State(state): State<ApiState>,
270 query: Result<Query<SeriesQuery>, QueryRejection>,
271) -> ApiResult<MemoryTotals> {
272 let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
273 let range = range_of(query.range.as_deref())?;
274 let to = (state.clock)();
275 let from = range.from(to);
276 let (_, cut, _) = range.bounds(&state.db, to).await?;
277 let key = cache::Key {
278 totals: true,
279 range,
280 process: None,
281 };
282 let mut entry = state.series.entry(key, (from, to)).await;
283 let read_from = entry.read_from(from, to);
284 let read = state
285 .db
286 .memory_totals((read_from, cut, to), range.bucket_s())
287 .await?;
288 let totals = cache::merged_totals(
289 &mut entry,
290 read,
291 from,
292 cache::final_to(to, range.bucket_s(), state.series.limits().final_after),
293 );
294 drop(entry);
295 Ok(Json(MemoryTotals {
296 step_s: range.bucket_s(),
297 from,
298 to,
299 points: totals
300 .into_iter()
301 .map(|(at, resident)| MemoryPointView { at, resident })
302 .collect(),
303 }))
304}
305
306fn floor(at: Timestamp, step_s: u32) -> Timestamp {
308 let step = i64::from(step_s.max(1));
309 Timestamp::from_second(at.as_second().div_euclid(step) * step).unwrap_or(at)
310}
311
312fn point(bucket: &Bucket) -> SamplePointView {
314 SamplePointView {
315 at: bucket.at,
316 resident_avg: bucket.resident_avg,
317 resident_peak: bucket.resident_peak,
318 memory_avg: bucket.memory_avg,
319 memory_peak: bucket.memory_peak,
320 minutes: bucket.minutes,
321 cpu_avg: bucket.cpu_avg,
322 cpu_peak: bucket.cpu_peak,
323 container_avg: bucket.container_avg,
324 container_peak: bucket.container_peak,
325 container_limit: bucket.container_limit,
326 parts: bucket.parts.map(|(forks, hosts, tasks)| PartsPointView {
327 fork_servers_bytes: forks,
328 watcher_hosts_bytes: hosts,
329 tasks_bytes: tasks,
330 }),
331 }
332}