1use std::collections::BTreeSet;
7
8use jiff::Timestamp;
9use schedr_model::{DagId, RunState};
10
11use crate::database::{Database, DbError};
12use crate::query::{db_time, from_name, in_tx, on_pool, parse_time, sql};
13
14#[cfg(test)]
15mod tests;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct NewBackfill<'a> {
20 pub id: &'a str,
22 pub dag_id: &'a DagId,
24 pub range_from: Timestamp,
26 pub range_to: Timestamp,
28 pub all_fire_times: bool,
30 pub requested_by: &'a str,
32 pub created_at: Timestamp,
34 pub fire_times: u32,
36 pub created_runs: u32,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct BackfillRecord {
43 pub id: String,
45 pub dag_id: DagId,
47 pub range_from: Timestamp,
49 pub range_to: Timestamp,
51 pub all_fire_times: bool,
53 pub requested_by: String,
55 pub created_at: Timestamp,
57 pub fire_times: u32,
59 pub created_runs: u32,
61 pub runs: Vec<(RunState, u32)>,
63}
64
65impl BackfillRecord {
66 #[must_use]
68 pub fn unfinished(&self) -> bool {
69 self.runs
70 .iter()
71 .any(|(state, count)| !state.is_final() && *count > 0)
72 }
73}
74
75type Row = (
76 String,
77 String,
78 String,
79 String,
80 bool,
81 String,
82 String,
83 i32,
84 i32,
85);
86
87impl Database {
88 pub async fn insert_backfill(&self, backfill: &NewBackfill<'_>) -> Result<bool, DbError> {
94 const INSERT: &str = "INSERT INTO backfills (id, dag_id, range_from, range_to, \
95 all_fire_times, requested_by, created_at, fire_times, created_runs) \
96 VALUES ($1{uuid}, $2, $3{ts}, $4{ts}, $5, $6, $7{ts}, $8, $9) ON CONFLICT DO NOTHING";
97 let inserted = in_tx!(self, |tx, backend| {
98 sqlx::query(sql(backend, INSERT))
99 .bind(backfill.id)
100 .bind(backfill.dag_id.as_str())
101 .bind(db_time(backfill.range_from))
102 .bind(db_time(backfill.range_to))
103 .bind(backfill.all_fire_times)
104 .bind(backfill.requested_by)
105 .bind(db_time(backfill.created_at))
106 .bind(i64::from(backfill.fire_times))
107 .bind(i64::from(backfill.created_runs))
108 .execute(&mut *tx)
109 .await?
110 .rows_affected()
111 });
112 Ok(inserted == 1)
113 }
114
115 pub async fn covered_times(
122 &self,
123 dag_id: &DagId,
124 from: Timestamp,
125 to: Timestamp,
126 ) -> Result<BTreeSet<Timestamp>, DbError> {
127 const COVERED: &str = "SELECT DISTINCT {ts<}planned_for{>ts} FROM runs \
128 WHERE dag_id = $1 AND planned_for >= $2{ts} AND planned_for <= $3{ts} \
129 AND state IN ('success', 'queued', 'running')";
130 let rows: Vec<(String,)> = on_pool!(self, |pool, backend| {
131 sqlx::query_as(sql(backend, COVERED))
132 .bind(dag_id.as_str())
133 .bind(db_time(from))
134 .bind(db_time(to))
135 .fetch_all(pool)
136 .await?
137 });
138 rows.iter()
139 .map(|(at,)| parse_time("runs.planned_for", at))
140 .collect()
141 }
142
143 pub async fn succeeded_times(
150 &self,
151 dag_id: &DagId,
152 from: Timestamp,
153 to: Timestamp,
154 ) -> Result<BTreeSet<Timestamp>, DbError> {
155 const SUCCEEDED: &str = "SELECT DISTINCT {ts<}planned_for{>ts} FROM runs \
156 WHERE dag_id = $1 AND planned_for >= $2{ts} AND planned_for <= $3{ts} \
157 AND state = 'success'";
158 let rows: Vec<(String,)> = on_pool!(self, |pool, backend| {
159 sqlx::query_as(sql(backend, SUCCEEDED))
160 .bind(dag_id.as_str())
161 .bind(db_time(from))
162 .bind(db_time(to))
163 .fetch_all(pool)
164 .await?
165 });
166 rows.iter()
167 .map(|(at,)| parse_time("runs.planned_for", at))
168 .collect()
169 }
170
171 pub async fn backfill(&self, id: &str) -> Result<Option<BackfillRecord>, DbError> {
177 const ONE: &str = "SELECT id{text}, dag_id, {ts<}range_from{>ts}, {ts<}range_to{>ts}, \
178 all_fire_times, requested_by, {ts<}created_at{>ts}, fire_times, created_runs \
179 FROM backfills WHERE id = $1{uuid}";
180 const COUNTS: &str =
181 "SELECT state, COUNT(*) FROM runs WHERE backfill_id = $1{uuid} GROUP BY state";
182 let row: Option<Row> = on_pool!(self, |pool, backend| {
183 sqlx::query_as(sql(backend, ONE))
184 .bind(id)
185 .fetch_optional(pool)
186 .await?
187 });
188 let Some(row) = row else {
189 return Ok(None);
190 };
191 let counts: Vec<(String, i64)> = on_pool!(self, |pool, backend| {
192 sqlx::query_as(sql(backend, COUNTS))
193 .bind(&row.0)
194 .fetch_all(pool)
195 .await?
196 });
197 record(row, counts).map(Some)
198 }
199
200 pub async fn dag_backfills(
206 &self,
207 dag_id: &DagId,
208 limit: u32,
209 ) -> Result<Vec<BackfillRecord>, DbError> {
210 const OF_DAG: &str = "SELECT id{text}, dag_id, {ts<}range_from{>ts}, {ts<}range_to{>ts}, \
211 all_fire_times, requested_by, {ts<}created_at{>ts}, fire_times, created_runs \
212 FROM backfills WHERE dag_id = $1 ORDER BY created_at DESC, id DESC LIMIT $2";
213 const COUNTS: &str = "SELECT backfill_id{text}, state, COUNT(*) FROM runs \
215 WHERE backfill_id IN (SELECT id FROM backfills WHERE dag_id = $1 \
216 ORDER BY created_at DESC, id DESC LIMIT $2) GROUP BY backfill_id, state";
217 let rows: Vec<Row> = on_pool!(self, |pool, backend| {
218 sqlx::query_as(sql(backend, OF_DAG))
219 .bind(dag_id.as_str())
220 .bind(i64::from(limit))
221 .fetch_all(pool)
222 .await?
223 });
224 let counts: Vec<(String, String, i64)> = on_pool!(self, |pool, backend| {
225 sqlx::query_as(sql(backend, COUNTS))
226 .bind(dag_id.as_str())
227 .bind(i64::from(limit))
228 .fetch_all(pool)
229 .await?
230 });
231 rows.into_iter()
232 .map(|row| {
233 let of_it: Vec<(String, i64)> = counts
234 .iter()
235 .filter(|(id, _, _)| *id == row.0)
236 .map(|(_, state, count)| (state.clone(), *count))
237 .collect();
238 record(row, of_it)
239 })
240 .collect()
241 }
242
243 pub async fn unfinished_backfill_runs(&self, id: &str) -> Result<Vec<String>, DbError> {
250 const UNFINISHED: &str = "SELECT id{text} FROM runs WHERE backfill_id = $1{uuid} \
251 AND state IN ('queued', 'running') ORDER BY planned_for, id";
252 let rows: Vec<(String,)> = on_pool!(self, |pool, backend| {
253 sqlx::query_as(sql(backend, UNFINISHED))
254 .bind(id)
255 .fetch_all(pool)
256 .await?
257 });
258 Ok(rows.into_iter().map(|(id,)| id).collect())
259 }
260}
261
262fn record(
264 row: Row,
265 counts: impl IntoIterator<Item = (String, i64)>,
266) -> Result<BackfillRecord, DbError> {
267 let (id, dag_id, from, to, all, by, at, fire_times, created) = row;
268 let mut runs = Vec::new();
269 for (state, count) in counts {
270 runs.push((
271 from_name("runs.state", state)?,
272 u32::try_from(count).unwrap_or(u32::MAX),
273 ));
274 }
275 Ok(BackfillRecord {
276 id,
277 dag_id: DagId::new(dag_id).map_err(|e| DbError::InvalidData {
278 what: "backfills.dag_id",
279 reason: e.to_string(),
280 })?,
281 range_from: parse_time("backfills.range_from", &from)?,
282 range_to: parse_time("backfills.range_to", &to)?,
283 all_fire_times: all,
284 requested_by: by,
285 created_at: parse_time("backfills.created_at", &at)?,
286 fire_times: u32::try_from(fire_times).unwrap_or(0),
287 created_runs: u32::try_from(created).unwrap_or(0),
288 runs,
289 })
290}