Skip to main content

schedr_db/
backfills.rs

1//! Backfills (decisions 363, 364, 400-404): a run per fire time of a range that has no
2//! successful, queued or running run (or every fire time), created together with the backfill,
3//! oldest first behind the other kinds of runs. The backfill's ID is the command's that asked
4//! for it.
5
6use 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/// A backfill to store, with its runs (stored alongside, in the same transaction).
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct NewBackfill<'a> {
20    /// Its ID (the command's).
21    pub id: &'a str,
22    /// The DAG.
23    pub dag_id: &'a DagId,
24    /// The first moment of its range.
25    pub range_from: Timestamp,
26    /// The last moment of its range (now, for a range ending later).
27    pub range_to: Timestamp,
28    /// Whether every fire time got a run (`--all`).
29    pub all_fire_times: bool,
30    /// Who asked for it.
31    pub requested_by: &'a str,
32    /// When.
33    pub created_at: Timestamp,
34    /// How many fire times its range has.
35    pub fire_times: u32,
36    /// How many of them got a run.
37    pub created_runs: u32,
38}
39
40/// A backfill as stored, with its runs counted by state.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct BackfillRecord {
43    /// Its ID.
44    pub id: String,
45    /// The DAG.
46    pub dag_id: DagId,
47    /// The first moment of its range.
48    pub range_from: Timestamp,
49    /// The last moment of its range.
50    pub range_to: Timestamp,
51    /// Whether every fire time got a run (`--all`).
52    pub all_fire_times: bool,
53    /// Who asked for it.
54    pub requested_by: String,
55    /// When.
56    pub created_at: Timestamp,
57    /// How many fire times its range has.
58    pub fire_times: u32,
59    /// How many of them got a run (the others were skipped).
60    pub created_runs: u32,
61    /// Its runs by state, each state once, in the order the query gave them.
62    pub runs: Vec<(RunState, u32)>,
63}
64
65impl BackfillRecord {
66    /// Whether some of its runs haven't finished.
67    #[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    /// Stores a backfill; `false` if one with its ID is there already (a command applied again).
89    ///
90    /// # Errors
91    ///
92    /// [`DbError::Sqlx`] if the write fails.
93    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    /// The `planned_for`s in `[from, to]` of the DAG's runs that succeeded or haven't finished:
116    /// the fire times a backfill skips without `--all` (decision 400).
117    ///
118    /// # Errors
119    ///
120    /// [`DbError`] if the query fails or a stored time doesn't read.
121    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    /// As [`Self::covered_times`], by successful runs only: the fire times no scheduled run
144    /// will take any more (decision 485).
145    ///
146    /// # Errors
147    ///
148    /// [`DbError`] if the query fails or a stored time doesn't read.
149    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    /// A backfill, with its runs counted by state; `None` for an unknown ID.
172    ///
173    /// # Errors
174    ///
175    /// [`DbError`] if a query fails or stored data doesn't read.
176    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    /// The DAG's backfills, newest first, at most `limit`.
201    ///
202    /// # Errors
203    ///
204    /// [`DbError`] if a query fails or stored data doesn't read.
205    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        // Their runs, counted in one query, not one per backfill.
214        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    /// The backfill's runs that haven't finished, oldest first: what cancelling it cancels
244    /// (decision 402).
245    ///
246    /// # Errors
247    ///
248    /// [`DbError::Sqlx`] if the query fails.
249    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
262/// A backfill's row with its runs' `counts` by state.
263fn 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}