1use jiff::Timestamp;
6use uuid::Uuid;
7
8use crate::database::{Database, DbError};
9use crate::query::{db_time, from_json, in_tx, on_pool, parse_time, sql, to_json};
10
11#[cfg(test)]
12mod tests;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct NewNotification {
17 pub dag_id: String,
19 pub channel: String,
21 pub kind: String,
23 pub url: Option<String>,
25 pub event: String,
27 pub body: serde_json::Value,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Notification {
34 pub id: String,
36 pub dag_id: String,
38 pub channel: String,
40 pub kind: String,
42 pub url: Option<String>,
44 pub event: String,
46 pub body: serde_json::Value,
48 pub created_at: Timestamp,
50 pub tries: u32,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct FailedTask {
57 pub task_id: String,
59 pub map_index: i32,
61 pub error: Option<String>,
63}
64
65type Row = (
66 String,
67 String,
68 String,
69 String,
70 Option<String>,
71 String,
72 String,
73 String,
74 i32,
75);
76
77impl Database {
78 pub async fn queue_notifications(
84 &self,
85 notifications: &[NewNotification],
86 now: Timestamp,
87 ) -> Result<(), DbError> {
88 const INSERT: &str = "INSERT INTO notifications \
89 (id, dag_id, channel, kind, url, event, body, created_at, next_try_at) \
90 VALUES ($1{uuid}, $2, $3, $4, $5, $6, $7{json}, $8{ts}, $8{ts})";
91 if notifications.is_empty() {
92 return Ok(());
93 }
94 in_tx!(self, |tx, backend| {
95 for notification in notifications {
96 sqlx::query(sql(backend, INSERT))
97 .bind(Uuid::now_v7().to_string())
98 .bind(¬ification.dag_id)
99 .bind(¬ification.channel)
100 .bind(¬ification.kind)
101 .bind(¬ification.url)
102 .bind(¬ification.event)
103 .bind(to_json(¬ification.body))
104 .bind(db_time(now))
105 .execute(&mut *tx)
106 .await?;
107 }
108 });
109 Ok(())
110 }
111
112 pub async fn due_notifications(
118 &self,
119 now: Timestamp,
120 limit: u32,
121 ) -> Result<Vec<Notification>, DbError> {
122 const DUE: &str = "SELECT id{text}, dag_id, channel, kind, url, event, body{text}, \
123 created_at{text}, tries FROM notifications WHERE next_try_at <= $1{ts} \
124 ORDER BY next_try_at, id LIMIT $2";
125 let rows: Vec<Row> = on_pool!(self, |pool, backend| {
126 sqlx::query_as(sql(backend, DUE))
127 .bind(db_time(now))
128 .bind(i64::from(limit))
129 .fetch_all(pool)
130 .await?
131 });
132 rows.into_iter()
133 .map(
134 |(id, dag_id, channel, kind, url, event, body, created_at, tries)| {
135 Ok(Notification {
136 id,
137 dag_id,
138 channel,
139 kind,
140 url,
141 event,
142 body: from_json("notifications.body", &body)?,
143 created_at: parse_time("notifications.created_at", &created_at)?,
144 tries: u32::try_from(tries).unwrap_or(0),
145 })
146 },
147 )
148 .collect()
149 }
150
151 pub async fn delete_notification(&self, id: &str) -> Result<(), DbError> {
157 const DELETE: &str = "DELETE FROM notifications WHERE id = $1{uuid}";
158 in_tx!(self, |tx, backend| {
159 sqlx::query(sql(backend, DELETE))
160 .bind(id)
161 .execute(&mut *tx)
162 .await?;
163 });
164 Ok(())
165 }
166
167 pub async fn retry_notification(
173 &self,
174 id: &str,
175 next_try_at: Timestamp,
176 error: &str,
177 ) -> Result<(), DbError> {
178 const RETRY: &str = "UPDATE notifications SET tries = tries + 1, \
179 next_try_at = $1{ts}, last_error = $2 WHERE id = $3{uuid}";
180 in_tx!(self, |tx, backend| {
181 sqlx::query(sql(backend, RETRY))
182 .bind(db_time(next_try_at))
183 .bind(error)
184 .bind(id)
185 .execute(&mut *tx)
186 .await?;
187 });
188 Ok(())
189 }
190
191 pub async fn count_attempt_notification(
198 &self,
199 attempt_id: &str,
200 max: u32,
201 ) -> Result<bool, DbError> {
202 const COUNT: &str = "UPDATE attempts SET notifications_sent = notifications_sent + 1 \
203 WHERE id = $1{uuid} AND notifications_sent < $2";
204 let counted = in_tx!(self, |tx, backend| {
205 sqlx::query(sql(backend, COUNT))
206 .bind(attempt_id)
207 .bind(i64::from(max))
208 .execute(&mut *tx)
209 .await?
210 .rows_affected()
211 });
212 Ok(counted == 1)
213 }
214
215 pub async fn first_notification_request(
222 &self,
223 attempt_id: &str,
224 request_key: &str,
225 ) -> Result<bool, DbError> {
226 const INSERT: &str = "INSERT INTO notification_requests (attempt_id, request_key) \
227 VALUES ($1{uuid}, $2) ON CONFLICT DO NOTHING";
228 let inserted = in_tx!(self, |tx, backend| {
229 sqlx::query(sql(backend, INSERT))
230 .bind(attempt_id)
231 .bind(request_key)
232 .execute(&mut *tx)
233 .await?
234 .rows_affected()
235 });
236 Ok(inserted == 1)
237 }
238
239 pub async fn previous_run_failed(&self, dag_id: &str, run_id: &str) -> Result<bool, DbError> {
245 const PREVIOUS: &str = "SELECT state FROM runs WHERE dag_id = $1 AND id <> $2{uuid} \
246 AND ended_at IS NOT NULL AND state IN ('success', 'failed') \
247 ORDER BY ended_at DESC, id DESC LIMIT 1";
248 let state: Option<(String,)> = on_pool!(self, |pool, backend| {
249 sqlx::query_as(sql(backend, PREVIOUS))
250 .bind(dag_id)
251 .bind(run_id)
252 .fetch_optional(pool)
253 .await?
254 });
255 Ok(state.is_some_and(|(state,)| state == "failed"))
256 }
257
258 pub async fn failed_tasks(&self, run_id: &str, limit: u32) -> Result<Vec<FailedTask>, DbError> {
266 const FAILED: &str = "SELECT ti.task_id, ti.map_index, \
267 (SELECT a.error_summary{text} FROM attempts a WHERE a.task_instance_id = ti.id \
268 ORDER BY a.try_number DESC LIMIT 1) \
269 FROM task_instances ti WHERE ti.run_id = $1{uuid} AND ti.state = 'failed' \
270 AND (ti.map_index >= 0 OR NOT EXISTS (SELECT 1 FROM task_instances c \
271 WHERE c.run_id = ti.run_id AND c.task_id = ti.task_id AND c.map_index >= 0 \
272 AND c.state = 'failed')) \
273 ORDER BY ti.task_id, ti.map_index LIMIT $2";
274 let rows: Vec<(String, i32, Option<String>)> = on_pool!(self, |pool, backend| {
275 sqlx::query_as(sql(backend, FAILED))
276 .bind(run_id)
277 .bind(i64::from(limit))
278 .fetch_all(pool)
279 .await?
280 });
281 Ok(rows
282 .into_iter()
283 .map(|(task_id, map_index, error)| FailedTask {
284 task_id,
285 map_index,
286 error: error.as_deref().map(readable),
287 })
288 .collect())
289 }
290
291 pub async fn instance_error(&self, instance_id: &str) -> Result<Option<String>, DbError> {
297 const ERROR: &str = "SELECT error_summary{text} FROM attempts \
298 WHERE task_instance_id = $1{uuid} ORDER BY try_number DESC LIMIT 1";
299 let row: Option<(Option<String>,)> = on_pool!(self, |pool, backend| {
300 sqlx::query_as(sql(backend, ERROR))
301 .bind(instance_id)
302 .fetch_optional(pool)
303 .await?
304 });
305 Ok(row.and_then(|(error,)| error).as_deref().map(readable))
306 }
307}
308
309#[must_use]
311pub fn readable(stored: &str) -> String {
312 let Ok(value) = serde_json::from_str::<serde_json::Value>(stored) else {
313 return stored.to_owned();
314 };
315 let field = |name: &str| value.get(name).and_then(serde_json::Value::as_str);
316 match (field("exception"), field("message")) {
317 (Some(exception), Some(message)) if !message.is_empty() => {
318 format!("{exception}: {message}")
319 }
320 (Some(exception), _) => exception.to_owned(),
321 _ => value
322 .as_str()
323 .map_or_else(|| stored.to_owned(), str::to_owned),
324 }
325}