1use std::collections::{BTreeMap, HashMap};
6use std::sync::{Arc, Mutex, PoisonError};
7
8use axum::Json;
9use axum::extract::rejection::QueryRejection;
10use axum::extract::{Query, State};
11use jiff::{SignedDuration, Timestamp};
12use schedr_db::task_flow::{EndedCount, StartLatency};
13use serde::Deserialize;
14use utoipa::IntoParams;
15
16use crate::error::ApiError;
17use crate::routes::ApiResult;
18use crate::series::{Range, cache::final_to};
19use crate::state::ApiState;
20use crate::views::{TaskFlowList, TaskFlowView};
21
22#[cfg(test)]
23mod tests;
24
25#[derive(Debug, Deserialize, IntoParams)]
27#[into_params(parameter_in = Query)]
28pub struct FlowQuery {
29 pub range: Option<String>,
31}
32
33#[derive(Debug, Default)]
35pub struct FlowEntry {
36 kept_from: Option<Timestamp>,
37 final_to: Option<Timestamp>,
38 ended: Vec<EndedCount>,
39 latency: Vec<StartLatency>,
40}
41
42impl FlowEntry {
43 fn read_from(&mut self, from: Timestamp, to: Timestamp) -> Timestamp {
46 match (self.kept_from, self.final_to) {
47 (Some(kept_from), Some(final_to)) if kept_from <= from && final_to <= to => {
48 final_to.max(from)
49 }
50 _ => {
51 *self = Self::default();
52 from
53 }
54 }
55 }
56}
57
58#[derive(Debug, Default)]
61pub struct FlowCache {
62 entries: Mutex<HashMap<Range, Arc<tokio::sync::Mutex<FlowEntry>>>>,
63}
64
65impl FlowCache {
66 pub async fn entry(&self, range: Range) -> tokio::sync::OwnedMutexGuard<FlowEntry> {
68 let slot = Arc::clone(
69 self.entries
70 .lock()
71 .unwrap_or_else(PoisonError::into_inner)
72 .entry(range)
73 .or_default(),
74 );
75 slot.lock_owned().await
76 }
77}
78
79fn counts(status: &str) -> (u64, u64, u64) {
81 match status {
82 "success" => (1, 0, 0),
83 "failed" | "timed_out" | "oom_killed" => (0, 1, 0),
84 _ => (0, 0, 1),
85 }
86}
87
88fn merged<T: Clone>(kept: &[T], read: Vec<T>, from: Timestamp, at: fn(&T) -> Timestamp) -> Vec<T> {
90 kept.iter()
91 .filter(|row| at(row) >= from)
92 .cloned()
93 .chain(read)
94 .collect()
95}
96
97#[utoipa::path(get, path = "/api/v1/metrics/tasks", tag = "workers", params(FlowQuery),
104 responses((status = 200, body = TaskFlowList), (status = 400, body = crate::views::ErrorBody)))]
105pub async fn task_flow(
106 State(state): State<ApiState>,
107 query: Result<Query<FlowQuery>, QueryRejection>,
108) -> ApiResult<TaskFlowList> {
109 let Query(query) = query.map_err(|e| ApiError::BadRequest(e.body_text()))?;
110 let range = crate::series::range_of(query.range.as_deref())?;
111 let to = (state.clock)();
112 let from = range.from(to);
113 let bucket_s = range.bucket_s();
114 let mut entry = state.flow.entry(range).await;
115 let read_from = entry.read_from(from, to);
116 let ended = state.db.attempts_ended((read_from, to), bucket_s).await?;
117 let latency = state.db.start_latency((read_from, to), bucket_s).await?;
118 let ended = merged(&entry.ended, ended, from, |row| row.at);
119 let latency = merged(&entry.latency, latency, from, |row| row.at);
120 let final_to = final_to(to, bucket_s, state.series.limits().final_after);
121 *entry = FlowEntry {
122 kept_from: Some(from),
123 final_to: Some(final_to),
124 ended: ended
125 .iter()
126 .filter(|row| row.at < final_to)
127 .cloned()
128 .collect(),
129 latency: latency
130 .iter()
131 .filter(|row| row.at < final_to)
132 .copied()
133 .collect(),
134 };
135 drop(entry);
136 let mut views: BTreeMap<Timestamp, TaskFlowView> = BTreeMap::new();
137 let mut at = from;
138 while at <= to {
139 views.insert(
140 at,
141 TaskFlowView {
142 at,
143 succeeded: 0,
144 failed: 0,
145 stopped: 0,
146 started: 0,
147 start_p50_ms: None,
148 start_p95_ms: None,
149 },
150 );
151 at = at
152 .checked_add(SignedDuration::from_secs(i64::from(bucket_s)))
153 .unwrap_or(Timestamp::MAX);
154 }
155 for row in &ended {
156 if let Some(bucket) = views.get_mut(&row.at) {
157 let (succeeded, failed, stopped) = counts(&row.status);
158 bucket.succeeded += succeeded * row.count;
159 bucket.failed += failed * row.count;
160 bucket.stopped += stopped * row.count;
161 }
162 }
163 for row in &latency {
164 if let Some(bucket) = views.get_mut(&row.at) {
165 bucket.started = row.started;
166 bucket.start_p50_ms = Some(row.p50_ms);
167 bucket.start_p95_ms = Some(row.p95_ms);
168 }
169 }
170 Ok(Json(TaskFlowList {
171 range: range.name().to_owned(),
172 step_s: bucket_s,
173 from,
174 to,
175 buckets: views.into_values().collect(),
176 }))
177}