1use jiff::Timestamp;
5
6use crate::database::{Database, DbError};
7use crate::query::{db_time, in_tx, on_pool, parse_time, sql};
8
9#[cfg(test)]
10mod tests;
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct WaitStepStrikes {
15 pub dag_id: String,
17 pub task_id: String,
19 pub strikes: u32,
21 pub one_chance: bool,
23 pub off_at: Option<Timestamp>,
25 pub off_code: Option<String>,
27}
28
29type Row = (String, String, i32, i32, Option<String>, Option<String>);
30
31fn stored(row: Row) -> Result<WaitStepStrikes, DbError> {
32 let (dag_id, task_id, strikes, one_chance, off_at, off_code) = row;
33 Ok(WaitStepStrikes {
34 dag_id,
35 task_id,
36 strikes: u32::try_from(strikes).unwrap_or(0),
37 one_chance: one_chance != 0,
38 off_at: off_at
39 .map(|at| parse_time("wait_step_strikes.off_at", &at))
40 .transpose()?,
41 off_code,
42 })
43}
44
45impl Database {
46 pub async fn wait_step_strikes(
52 &self,
53 dag_id: &str,
54 task_id: &str,
55 ) -> Result<Option<WaitStepStrikes>, DbError> {
56 const READ: &str = "SELECT dag_id, task_id, strikes, one_chance, off_at{text}, off_code \
57 FROM wait_step_strikes WHERE dag_id = $1 AND task_id = $2";
58 let row: Option<Row> = on_pool!(self, |pool, backend| {
59 sqlx::query_as(sql(backend, READ))
60 .bind(dag_id)
61 .bind(task_id)
62 .fetch_optional(pool)
63 .await?
64 });
65 row.map(stored).transpose()
66 }
67
68 pub async fn switched_off_wait_steps(&self) -> Result<Vec<WaitStepStrikes>, DbError> {
74 const LIST: &str = "SELECT dag_id, task_id, strikes, one_chance, off_at{text}, off_code \
75 FROM wait_step_strikes WHERE off_at IS NOT NULL \
76 ORDER BY dag_id, task_id";
77 let rows: Vec<Row> = on_pool!(self, |pool, backend| {
78 sqlx::query_as(sql(backend, LIST)).fetch_all(pool).await?
79 });
80 rows.into_iter().map(stored).collect()
81 }
82
83 pub async fn strike_wait_step(
90 &self,
91 (dag_id, task_id): (&str, &str),
92 limit: u32,
93 code: &str,
94 now: Timestamp,
95 ) -> Result<bool, DbError> {
96 const COUNT: &str = "INSERT INTO wait_step_strikes (dag_id, task_id, strikes) \
97 VALUES ($1, $2, 1) ON CONFLICT (dag_id, task_id) \
98 DO UPDATE SET strikes = wait_step_strikes.strikes + 1 \
99 RETURNING strikes, one_chance";
100 const OFF: &str = "UPDATE wait_step_strikes SET off_at = $1{ts}, off_code = $2, one_chance = 0 \
101 WHERE dag_id = $3 AND task_id = $4";
102 let at = db_time(now);
103 let off = in_tx!(self, |tx, backend| {
104 let (strikes, one_chance): (i32, i32) = sqlx::query_as(sql(backend, COUNT))
105 .bind(dag_id)
106 .bind(task_id)
107 .fetch_one(&mut *tx)
108 .await?;
109 let reached = limit > 0 && u32::try_from(strikes).unwrap_or(0) >= limit;
110 let off = reached || (limit > 0 && one_chance != 0);
111 if off {
112 sqlx::query(sql(backend, OFF))
113 .bind(&at)
114 .bind(code)
115 .bind(dag_id)
116 .bind(task_id)
117 .execute(&mut *tx)
118 .await?;
119 }
120 off
121 });
122 Ok(off)
123 }
124
125 pub async fn wait_step_on_new_code(&self, dag_id: &str, task_id: &str) -> Result<(), DbError> {
131 const ON: &str = "UPDATE wait_step_strikes \
132 SET off_at = NULL, off_code = NULL, one_chance = 1, strikes = 0 \
133 WHERE dag_id = $1 AND task_id = $2";
134 in_tx!(self, |tx, backend| {
135 sqlx::query(sql(backend, ON))
136 .bind(dag_id)
137 .bind(task_id)
138 .execute(&mut *tx)
139 .await?;
140 });
141 Ok(())
142 }
143
144 pub async fn clear_wait_steps(&self, dag_id: &str, task_ids: &[&str]) -> Result<(), DbError> {
151 const CLEAR: &str = "DELETE FROM wait_step_strikes \
152 WHERE dag_id = $1 AND task_id IN (SELECT value FROM {json_each}($2{json}))";
153 if task_ids.is_empty() {
154 return Ok(());
155 }
156 let list = crate::query::to_json(&task_ids);
157 in_tx!(self, |tx, backend| {
158 sqlx::query(sql(backend, CLEAR))
159 .bind(dag_id)
160 .bind(&list)
161 .execute(&mut *tx)
162 .await?;
163 });
164 Ok(())
165 }
166
167 pub async fn clear_wait_step(&self, dag_id: &str, task_id: &str) -> Result<bool, DbError> {
173 const CLEAR: &str = "DELETE FROM wait_step_strikes WHERE dag_id = $1 AND task_id = $2";
174 let changed = in_tx!(self, |tx, backend| {
175 sqlx::query(sql(backend, CLEAR))
176 .bind(dag_id)
177 .bind(task_id)
178 .execute(&mut *tx)
179 .await?
180 .rows_affected()
181 });
182 Ok(changed == 1)
183 }
184}