Skip to main content

schedr_db/
triggers.rs

1//! Event-triggered DAGs' triggers and what they found (M4.11b): each new key starts a run, and the
2//! last key acted on is the bookmark a trigger starts again from.
3
4use jiff::Timestamp;
5use schedr_model::RunEvent;
6
7use crate::database::{Database, DbError};
8use crate::query::{db_time, in_tx, on_pool, optional_time, sql, to_json};
9use crate::runs::NewRun;
10
11/// The rows of queued event runs: the read's `FROM ... WHERE` and its probe check's (decision 485).
12macro_rules! queued_event_from {
13    () => {
14        "FROM runs WHERE state = 'queued' AND kind = 'event'"
15    };
16}
17pub(crate) use queued_event_from;
18
19/// The rows the master's trigger pass looks after: a switched-on trigger of an event or `RunOf` DAG, or a trigger running on a worker: the read's `FROM ... WHERE` and its probe check's (decision 485).
20macro_rules! trigger_pass_from {
21    () => {
22        "FROM dag_triggers WHERE (NOT paused AND kind IN ('run_of', 'event')) OR EXISTS (SELECT 1 FROM trigger_progress p WHERE p.instance_id IS NOT NULL)"
23    };
24}
25pub(crate) use trigger_pass_from;
26
27/// The rows of the triggers the trigger loop looks after (`RunOf`, events) switched on whose
28/// stored next moment has come or isn't known (decision 486): what the tick's probe wakes
29/// the loop for.
30macro_rules! triggers_due_from {
31    () => {
32        "FROM dag_triggers WHERE kind IN ('run_of', 'event') AND NOT paused AND (next_fire_at IS NULL OR next_fire_at <= $1{ts})"
33    };
34}
35pub(crate) use triggers_due_from;
36
37#[cfg(test)]
38mod tests;
39
40/// An event as stored.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct StoredEvent {
43    /// The event.
44    pub event: RunEvent,
45    /// When the master got it.
46    pub received_at: Timestamp,
47}
48
49type EventRow = (String, String, Option<String>, String);
50
51fn stored_event((key, data, at, received_at): EventRow) -> Result<StoredEvent, DbError> {
52    Ok(StoredEvent {
53        event: RunEvent {
54            key,
55            data: crate::query::from_json("events.data", &data)?,
56            at: optional_time("events.at", at)?,
57        },
58        received_at: crate::query::parse_time("events.received_at", &received_at)?,
59    })
60}
61
62/// A DAG's trigger.
63#[derive(Debug, Clone, PartialEq, Eq, Default)]
64pub struct TriggerRecord {
65    /// Its DAG.
66    pub dag_id: String,
67    /// This run of it, while a worker has it.
68    pub instance_id: Option<String>,
69    /// The worker that has it.
70    pub worker_id: Option<String>,
71    /// The DAG version it runs: a new one starts it again.
72    pub dag_version_id: Option<String>,
73    /// The hash of the root it runs from: other code starts it again.
74    pub code_hash: Option<String>,
75    /// The last key acted on: its `after` when it starts.
76    pub bookmark: Option<String>,
77    /// `planned_for` of the last event's run: the next one's `since`.
78    pub last_planned_for: Option<Timestamp>,
79    /// Why it ended last, if it failed.
80    pub last_error: Option<String>,
81    /// Its failures in a row.
82    pub failures: u32,
83    /// Not started again before this moment.
84    pub not_before: Option<Timestamp>,
85    /// Why it isn't to run although its DAG wants it.
86    pub stopped_why: Option<String>,
87    /// What it stopped on: its DAG version and code.
88    pub stopped_on: Option<String>,
89    /// When this run of it started.
90    pub started_at: Option<Timestamp>,
91    /// When it last found something, new or not.
92    pub last_event_at: Option<Timestamp>,
93    /// When it was last started again for finding nothing for too long.
94    pub last_restart_at: Option<Timestamp>,
95    /// When a poke's call last ended.
96    pub last_poked_at: Option<Timestamp>,
97}
98
99/// Why a trigger isn't to run: too many queued event runs, until they have started.
100pub const STOPPED_BACK_PRESSURE: &str = "back_pressure";
101/// Why a trigger isn't to run: its generator returned, until a new version or new code.
102pub const STOPPED_RETURNED: &str = "returned";
103
104type Row = (
105    String,
106    Option<String>,
107    Option<String>,
108    Option<String>,
109    Option<String>,
110    Option<String>,
111    Option<String>,
112    Option<String>,
113    i32,
114    Option<String>,
115    Option<String>,
116    Option<String>,
117    Option<String>,
118    Option<String>,
119    Option<String>,
120    Option<String>,
121);
122
123fn record(row: Row) -> Result<TriggerRecord, DbError> {
124    let (
125        dag_id,
126        instance_id,
127        worker_id,
128        version,
129        code_hash,
130        bookmark,
131        last,
132        last_error,
133        failures,
134        not_before,
135        stopped_why,
136        stopped_on,
137        started_at,
138        last_event_at,
139        last_restart_at,
140        last_poked_at,
141    ) = row;
142    Ok(TriggerRecord {
143        dag_id,
144        instance_id,
145        worker_id,
146        dag_version_id: version,
147        code_hash,
148        bookmark,
149        last_planned_for: optional_time("trigger_progress.last_planned_for", last)?,
150        last_error,
151        failures: u32::try_from(failures).unwrap_or(0),
152        not_before: optional_time("trigger_progress.not_before", not_before)?,
153        stopped_why,
154        stopped_on,
155        started_at: optional_time("trigger_progress.started_at", started_at)?,
156        last_event_at: optional_time("trigger_progress.last_event_at", last_event_at)?,
157        last_restart_at: optional_time("trigger_progress.last_restart_at", last_restart_at)?,
158        last_poked_at: optional_time("trigger_progress.last_poked_at", last_poked_at)?,
159    })
160}
161
162impl Database {
163    /// Every trigger the master has run, by DAG.
164    ///
165    /// # Errors
166    ///
167    /// [`DbError`] if the query fails or stored data doesn't read.
168    pub async fn triggers(&self) -> Result<Vec<TriggerRecord>, DbError> {
169        const ALL: &str = "SELECT dag_id, instance_id{text}, worker_id, dag_version_id{text}, \
170            code_hash, bookmark, {ts<}last_planned_for{>ts}, last_error, failures, {ts<}not_before{>ts}, \
171            stopped_why, stopped_on, {ts<}started_at{>ts}, {ts<}last_event_at{>ts}, \
172            {ts<}last_restart_at{>ts}, {ts<}last_poked_at{>ts} \
173            FROM trigger_progress ORDER BY dag_id";
174        let rows: Vec<Row> = on_pool!(self, |pool, backend| {
175            sqlx::query_as(sql(backend, ALL)).fetch_all(pool).await?
176        });
177        rows.into_iter().map(record).collect()
178    }
179
180    /// A DAG's trigger, if it has run or found anything.
181    ///
182    /// # Errors
183    ///
184    /// [`DbError`] if the query fails or stored data doesn't read.
185    pub async fn trigger(&self, dag_id: &str) -> Result<Option<TriggerRecord>, DbError> {
186        const ONE: &str = "SELECT dag_id, instance_id{text}, worker_id, dag_version_id{text}, \
187            code_hash, bookmark, {ts<}last_planned_for{>ts}, last_error, failures, {ts<}not_before{>ts}, \
188            stopped_why, stopped_on, {ts<}started_at{>ts}, {ts<}last_event_at{>ts}, \
189            {ts<}last_restart_at{>ts}, {ts<}last_poked_at{>ts} \
190            FROM trigger_progress WHERE dag_id = $1";
191        let row: Option<Row> = on_pool!(self, |pool, backend| {
192            sqlx::query_as(sql(backend, ONE))
193                .bind(dag_id)
194                .fetch_optional(pool)
195                .await?
196        });
197        row.map(record).transpose()
198    }
199
200    /// Records that a worker was given a DAG's trigger.
201    ///
202    /// # Errors
203    ///
204    /// [`DbError::Sqlx`] if the statement fails.
205    pub async fn trigger_assigned(
206        &self,
207        dag_id: &str,
208        instance_id: &str,
209        worker_id: &str,
210        dag_version_id: &str,
211        code_hash: &str,
212        now: Timestamp,
213    ) -> Result<(), DbError> {
214        const SET: &str = "INSERT INTO trigger_progress \
215            (dag_id, instance_id, worker_id, dag_version_id, code_hash, started_at) \
216            VALUES ($1, $2, $3, $4, $5, $6{ts}) ON CONFLICT (dag_id) DO UPDATE SET \
217            instance_id = excluded.instance_id, worker_id = excluded.worker_id, \
218            dag_version_id = excluded.dag_version_id, code_hash = excluded.code_hash, \
219            started_at = excluded.started_at, stopped_why = NULL, stopped_on = NULL";
220        in_tx!(self, |tx, backend| {
221            sqlx::query(sql(backend, SET))
222                .bind(dag_id)
223                .bind(instance_id)
224                .bind(worker_id)
225                .bind(dag_version_id)
226                .bind(code_hash)
227                .bind(db_time(now))
228                .execute(&mut *tx)
229                .await?;
230        });
231        Ok(())
232    }
233
234    /// Records that this run of a DAG's trigger ended, with why if it failed, and when it may
235    /// start again; what isn't this run any more is left alone. Gives whether it was.
236    ///
237    /// # Errors
238    ///
239    /// [`DbError::Sqlx`] if the statement fails.
240    pub async fn trigger_ended(
241        &self,
242        dag_id: &str,
243        instance_id: &str,
244        error: Option<&str>,
245        not_before: Option<Timestamp>,
246    ) -> Result<bool, DbError> {
247        const END: &str = "UPDATE trigger_progress SET instance_id = NULL, worker_id = NULL, \
248            dag_version_id = NULL, code_hash = NULL, last_error = COALESCE($1, last_error), \
249            failures = failures + $2, not_before = $3{ts} \
250            WHERE dag_id = $4 AND instance_id = $5";
251        let ended = in_tx!(self, |tx, backend| {
252            sqlx::query(sql(backend, END))
253                .bind(error)
254                .bind(i32::from(error.is_some()))
255                .bind(not_before.map(db_time))
256                .bind(dag_id)
257                .bind(instance_id)
258                .execute(&mut *tx)
259                .await?
260                .rows_affected()
261        });
262        Ok(ended == 1)
263    }
264
265    /// Stores what a trigger found, in one transaction: the event; for a key not seen before,
266    /// `run`; and the key as the bookmark, whichever it was. Gives the run's ID, `None` for a
267    /// repeat.
268    ///
269    /// # Errors
270    ///
271    /// [`DbError::Sqlx`] if a statement fails.
272    pub async fn store_event(
273        &self,
274        run_id: &str,
275        run: &NewRun<'_>,
276        event: &RunEvent,
277    ) -> Result<Option<String>, DbError> {
278        const EVENT: &str = "INSERT INTO events (dag_id, key, data, at, received_at) \
279            VALUES ($1, $2, $3{json}, $4{ts}, $5{ts}) ON CONFLICT (dag_id, key) DO NOTHING";
280        const BOOKMARK: &str = "INSERT INTO trigger_progress \
281            (dag_id, bookmark, last_planned_for, failures, last_event_at) \
282            VALUES ($1, $2, $3{ts}, 0, $4{ts}) ON CONFLICT (dag_id) DO UPDATE SET \
283            bookmark = excluded.bookmark, failures = 0, last_error = NULL, \
284            last_event_at = excluded.last_event_at, \
285            last_planned_for = COALESCE(excluded.last_planned_for, trigger_progress.last_planned_for)";
286        let dag_id = run.dag_id.as_str();
287        Box::pin(self.atomically(async {
288            let new = in_tx!(self, |tx, backend| {
289                sqlx::query(sql(backend, EVENT))
290                    .bind(dag_id)
291                    .bind(&event.key)
292                    .bind(to_json(&event.data))
293                    .bind(event.at.map(db_time))
294                    .bind(db_time(run.triggered_at))
295                    .execute(&mut *tx)
296                    .await?
297                    .rows_affected()
298            }) == 1;
299            if new {
300                self.insert_run_as(run_id, run).await?;
301            }
302            in_tx!(self, |tx, backend| {
303                sqlx::query(sql(backend, BOOKMARK))
304                    .bind(dag_id)
305                    .bind(&event.key)
306                    .bind(new.then(|| db_time(run.planned_for)))
307                    .bind(db_time(run.triggered_at))
308                    .execute(&mut *tx)
309                    .await?;
310            });
311            Ok(new.then(|| run_id.to_owned()))
312        }))
313        .await
314    }
315
316    /// Stores a batch a trigger found (`@trigger.poke(batch=...)`, decision 352), in one
317    /// transaction: each item as an event of its own; for the items whose keys weren't seen
318    /// before, `run`, its event their list as stored (`raw`), keyed by the last of them; and the
319    /// batch's `key`, its last item's, as the bookmark. Gives the run's ID, `None` when every item
320    /// was seen before (B188: a window ending with a repeat lost the new items before it).
321    ///
322    /// # Errors
323    ///
324    /// [`DbError::Sqlx`] if a statement fails.
325    pub async fn store_batch(
326        &self,
327        run_id: &str,
328        run: &NewRun<'_>,
329        key: &str,
330        items: &[(RunEvent, serde_json::Value)],
331    ) -> Result<Option<String>, DbError> {
332        const EVENT: &str = "INSERT INTO events (dag_id, key, data, at, received_at) \
333            VALUES ($1, $2, $3{json}, $4{ts}, $5{ts}) ON CONFLICT (dag_id, key) DO NOTHING";
334        const BOOKMARK: &str = "INSERT INTO trigger_progress \
335            (dag_id, bookmark, last_planned_for, failures, last_event_at) \
336            VALUES ($1, $2, $3{ts}, 0, $4{ts}) ON CONFLICT (dag_id) DO UPDATE SET \
337            bookmark = excluded.bookmark, failures = 0, last_error = NULL, \
338            last_event_at = excluded.last_event_at, \
339            last_planned_for = COALESCE(excluded.last_planned_for, trigger_progress.last_planned_for)";
340        let dag_id = run.dag_id.as_str();
341        Box::pin(self.atomically(async {
342            let mut new = Vec::new();
343            for (item, raw) in items {
344                let stored = in_tx!(self, |tx, backend| {
345                    sqlx::query(sql(backend, EVENT))
346                        .bind(dag_id)
347                        .bind(&item.key)
348                        .bind(to_json(&item.data))
349                        .bind(item.at.map(db_time))
350                        .bind(db_time(run.triggered_at))
351                        .execute(&mut *tx)
352                        .await?
353                        .rows_affected()
354                }) == 1;
355                if stored {
356                    new.push((item, raw));
357                }
358            }
359            let started = new.last().map(|(last, _)| RunEvent {
360                key: last.key.clone(),
361                data: serde_json::Value::Array(new.iter().map(|(_, raw)| (*raw).clone()).collect()),
362                at: None,
363            });
364            if let Some(event) = &started {
365                let run = NewRun {
366                    event: Some(event),
367                    ..run.clone()
368                };
369                self.insert_run_as(run_id, &run).await?;
370            }
371            in_tx!(self, |tx, backend| {
372                sqlx::query(sql(backend, BOOKMARK))
373                    .bind(dag_id)
374                    .bind(key)
375                    .bind(started.is_some().then(|| db_time(run.planned_for)))
376                    .bind(db_time(run.triggered_at))
377                    .execute(&mut *tx)
378                    .await?;
379            });
380            Ok(started.map(|_| run_id.to_owned()))
381        }))
382        .await
383    }
384
385    /// Says why a trigger isn't to run although its DAG wants it, and on what it stopped; `None`:
386    /// it may run again.
387    ///
388    /// # Errors
389    ///
390    /// [`DbError::Sqlx`] if the statement fails.
391    pub async fn set_trigger_stopped(
392        &self,
393        dag_id: &str,
394        why: Option<(&str, &str)>,
395    ) -> Result<(), DbError> {
396        const SET: &str =
397            "UPDATE trigger_progress SET stopped_why = $1, stopped_on = $2 WHERE dag_id = $3";
398        in_tx!(self, |tx, backend| {
399            sqlx::query(sql(backend, SET))
400                .bind(why.map(|(why, _)| why))
401                .bind(why.map(|(_, on)| on))
402                .bind(dag_id)
403                .execute(&mut *tx)
404                .await?;
405        });
406        Ok(())
407    }
408
409    /// Records that a trigger was started again for finding nothing for too long.
410    ///
411    /// # Errors
412    ///
413    /// [`DbError::Sqlx`] if the statement fails.
414    pub async fn trigger_idle_restart(&self, dag_id: &str, now: Timestamp) -> Result<(), DbError> {
415        const SET: &str = "UPDATE trigger_progress SET last_restart_at = $1{ts} WHERE dag_id = $2";
416        in_tx!(self, |tx, backend| {
417            sqlx::query(sql(backend, SET))
418                .bind(db_time(now))
419                .bind(dag_id)
420                .execute(&mut *tx)
421                .await?;
422        });
423        Ok(())
424    }
425
426    /// How a poke's calls have gone: its failures in a row, and why the last one failed; one that
427    /// went well clears them.
428    ///
429    /// # Errors
430    ///
431    /// [`DbError::Sqlx`] if the statement fails.
432    pub async fn trigger_poked(
433        &self,
434        dag_id: &str,
435        instance_id: &str,
436        at: Timestamp,
437        error: Option<&str>,
438        failures: u32,
439    ) -> Result<(), DbError> {
440        const SET: &str = "UPDATE trigger_progress SET last_poked_at = $1{ts}, last_error = $2, \
441            failures = $3 WHERE dag_id = $4 AND instance_id = $5";
442        in_tx!(self, |tx, backend| {
443            sqlx::query(sql(backend, SET))
444                .bind(db_time(at))
445                .bind(error)
446                .bind(i32::try_from(failures).unwrap_or(i32::MAX))
447                .bind(dag_id)
448                .bind(instance_id)
449                .execute(&mut *tx)
450                .await?;
451        });
452        Ok(())
453    }
454
455    /// The queued runs of kind `event`, by DAG.
456    ///
457    /// # Errors
458    ///
459    /// [`DbError::Sqlx`] if the query fails.
460    pub async fn queued_event_runs(&self) -> Result<Vec<(String, i64)>, DbError> {
461        const COUNT: &str = concat!(
462            "SELECT dag_id, COUNT(*) ",
463            queued_event_from!(),
464            " GROUP BY dag_id"
465        );
466        if self.skipped(crate::probe::Check::QueuedEventRuns).await? {
467            return Ok(Vec::new());
468        }
469        let rows: Vec<(String, i64)> = on_pool!(self, |pool, backend| {
470            sqlx::query_as(sql(backend, COUNT)).fetch_all(pool).await?
471        });
472        Ok(rows)
473    }
474
475    /// Asks for a trigger to start again, whatever stopped it: what it waited for is forgotten,
476    /// and one running looks as if of an older version, so the next pass stops it. `None` when it
477    /// never ran.
478    ///
479    /// # Errors
480    ///
481    /// [`DbError::Sqlx`] if the statement fails.
482    pub async fn restart_trigger(&self, dag_id: &str) -> Result<(), DbError> {
483        const SET: &str = "UPDATE trigger_progress SET stopped_why = NULL, stopped_on = NULL, \
484            not_before = NULL, dag_version_id = NULL WHERE dag_id = $1";
485        in_tx!(self, |tx, backend| {
486            sqlx::query(sql(backend, SET))
487                .bind(dag_id)
488                .execute(&mut *tx)
489                .await?;
490        });
491        Ok(())
492    }
493
494    /// An event of a DAG by its key, as stored.
495    ///
496    /// # Errors
497    ///
498    /// [`DbError`] if the query fails or stored data doesn't read.
499    pub async fn stored_event(&self, dag_id: &str, key: &str) -> Result<Option<RunEvent>, DbError> {
500        const ONE: &str = "SELECT key, data{text}, {ts<}at{>ts}, {ts<}received_at{>ts} FROM events \
501            WHERE dag_id = $1 AND key = $2";
502        let row: Option<EventRow> = on_pool!(self, |pool, backend| {
503            sqlx::query_as(sql(backend, ONE))
504                .bind(dag_id)
505                .bind(key)
506                .fetch_optional(pool)
507                .await?
508        });
509        Ok(row.map(stored_event).transpose()?.map(|found| found.event))
510    }
511
512    /// A DAG's events, newest received first (then by key), to `limit`; those after the one at
513    /// `after`, its time and key.
514    ///
515    /// # Errors
516    ///
517    /// [`DbError`] if the query fails or stored data doesn't read.
518    pub async fn events(
519        &self,
520        dag_id: &str,
521        limit: u32,
522        after: Option<(Timestamp, &str)>,
523    ) -> Result<Vec<StoredEvent>, DbError> {
524        const ALL: &str = "SELECT key, data{text}, {ts<}at{>ts}, {ts<}received_at{>ts} FROM events \
525            WHERE dag_id = $1 AND ($2{ts} IS NULL OR received_at < $2{ts} \
526                OR (received_at = $2{ts} AND key > $3{text})) \
527            ORDER BY received_at DESC, key LIMIT $4";
528        let rows: Vec<EventRow> = on_pool!(self, |pool, backend| {
529            sqlx::query_as(sql(backend, ALL))
530                .bind(dag_id)
531                .bind(after.map(|(at, _)| db_time(at)))
532                .bind(after.map(|(_, key)| key))
533                .bind(i64::from(limit))
534                .fetch_all(pool)
535                .await?
536        });
537        rows.into_iter().map(stored_event).collect()
538    }
539
540    /// A DAG's queued runs of kind `event`.
541    ///
542    /// # Errors
543    ///
544    /// [`DbError::Sqlx`] if the query fails.
545    pub async fn queued_event_runs_of(&self, dag_id: &str) -> Result<i64, DbError> {
546        const COUNT: &str = "SELECT COUNT(*) FROM runs \
547            WHERE state = 'queued' AND kind = 'event' AND dag_id = $1";
548        let count: i64 = on_pool!(self, |pool, backend| {
549            sqlx::query_scalar(sql(backend, COUNT))
550                .bind(dag_id)
551                .fetch_one(pool)
552                .await?
553        });
554        Ok(count)
555    }
556
557    /// The event that started a run; `None` for a run no event started.
558    ///
559    /// # Errors
560    ///
561    /// [`DbError`] if the query fails or stored data doesn't read.
562    pub async fn run_event(&self, run_id: &str) -> Result<Option<RunEvent>, DbError> {
563        const EVENT: &str = "SELECT event{text} FROM runs WHERE id = $1{uuid}";
564        let text: Option<Option<String>> = on_pool!(self, |pool, backend| {
565            sqlx::query_scalar(sql(backend, EVENT))
566                .bind(run_id)
567                .fetch_optional(pool)
568                .await?
569        });
570        text.flatten()
571            .map(|t| crate::query::from_json("runs.event", &t))
572            .transpose()
573    }
574}