Skip to main content

schedr_db/
notifications.rs

1//! Notifications to deliver (decision 410): the outbox. A notification is written in the
2//! transaction that records its event; the master's sender delivers it and deletes it, or
3//! retries it later, or gives up on it.
4
5use 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/// A notification to queue.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct NewNotification {
17    /// The DAG it is about.
18    pub dag_id: String,
19    /// The channel's name.
20    pub channel: String,
21    /// How it is sent: `webhook` (the body is posted) or `email` (the body holds the email).
22    pub kind: String,
23    /// A DAG webhook's URL; `None` for a server channel, looked up when it is sent.
24    pub url: Option<String>,
25    /// The event's name (`RUN_FAILED`, `MESSAGE`).
26    pub event: String,
27    /// The JSON to post, filled in.
28    pub body: serde_json::Value,
29}
30
31/// A notification waiting to be delivered.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Notification {
34    /// Its ID.
35    pub id: String,
36    /// The DAG it is about.
37    pub dag_id: String,
38    /// The channel's name.
39    pub channel: String,
40    /// How it is sent: `webhook` or `email`.
41    pub kind: String,
42    /// A DAG webhook's URL; `None` for a server channel.
43    pub url: Option<String>,
44    /// The event's name.
45    pub event: String,
46    /// The JSON to post.
47    pub body: serde_json::Value,
48    /// When it was queued.
49    pub created_at: Timestamp,
50    /// How many deliveries failed so far.
51    pub tries: u32,
52}
53
54/// A failed task of a run, for a message.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct FailedTask {
57    /// Its ID.
58    pub task_id: String,
59    /// Its instance's index, for a mapped task; -1 otherwise.
60    pub map_index: i32,
61    /// Its last attempt's error summary (masked by the agent), if any.
62    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    /// Queues `notifications`, due now.
79    ///
80    /// # Errors
81    ///
82    /// [`DbError::Sqlx`] if a statement fails.
83    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(&notification.dag_id)
99                    .bind(&notification.channel)
100                    .bind(&notification.kind)
101                    .bind(&notification.url)
102                    .bind(&notification.event)
103                    .bind(to_json(&notification.body))
104                    .bind(db_time(now))
105                    .execute(&mut *tx)
106                    .await?;
107            }
108        });
109        Ok(())
110    }
111
112    /// At most `limit` notifications due at `now`, the earliest due first.
113    ///
114    /// # Errors
115    ///
116    /// [`DbError`] if the query fails or a row doesn't read.
117    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    /// Deletes notification `id`: delivered, or given up on.
152    ///
153    /// # Errors
154    ///
155    /// [`DbError::Sqlx`] if the statement fails.
156    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    /// Notification `id` failed with `error`: tried again from `next_try_at`.
168    ///
169    /// # Errors
170    ///
171    /// [`DbError::Sqlx`] if the statement fails.
172    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    /// Counts a notification attempt `attempt_id` sends itself, if it has sent fewer than
192    /// `max`: whether it may.
193    ///
194    /// # Errors
195    ///
196    /// [`DbError::Sqlx`] if the statement fails.
197    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    /// Records attempt `attempt_id`'s call `request_key`: whether it is new (one sent again
216    /// isn't).
217    ///
218    /// # Errors
219    ///
220    /// [`DbError::Sqlx`] if the statement fails.
221    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    /// Whether the DAG's run that ended last before `run_id` failed (for `RUN_RECOVERED`).
240    ///
241    /// # Errors
242    ///
243    /// [`DbError::Sqlx`] if the query fails.
244    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    /// At most `limit` failed tasks of run `run_id`, with their last attempt's error summary:
259    /// a mapped task's failed instances one by one (its own row only when none of them failed:
260    /// it failed as a whole, its expansion say).
261    ///
262    /// # Errors
263    ///
264    /// [`DbError::Sqlx`] if the query fails.
265    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    /// The error summary of task instance `instance_id`'s last attempt, if it has one.
292    ///
293    /// # Errors
294    ///
295    /// [`DbError::Sqlx`] if the query fails.
296    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/// An error summary as one line of text: `exception: message` (stored as JSON).
310#[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}