Skip to main content

schedr_db/
commands.rs

1//! Command rows: written by the webserver, applied by the master, kept as the audit trail.
2//!
3//! A command is decided once: `pending` becomes `applied` (with what it produced) or
4//! `rejected` (with a reason), and never changes again.
5//!
6//! On Postgres a new command also sends a notification on [`COMMANDS_CHANNEL`], so the master
7//! picks it up at once ([`Database::command_notifications`]); polling stays the fallback, and
8//! the only way on SQLite (see archive/PROJECT.md, Web UI and CLI).
9
10use std::time::Duration;
11
12use jiff::Timestamp;
13use schedr_model::commands::{Command, CommandStatus};
14use sqlx::Connection as _;
15use sqlx::postgres::PgListener;
16use uuid::Uuid;
17
18use crate::database::{Database, DbError, Pool};
19use crate::query::{
20    Starting, db_time, from_json, from_name, in_tx, on_pool, parse_time, sql, to_json,
21};
22
23/// The rows of pending commands: the read's `FROM ... WHERE` and its probe check's (decision 485).
24macro_rules! pending_from {
25    () => {
26        "FROM commands WHERE status = 'pending'"
27    };
28}
29pub(crate) use pending_from;
30
31#[cfg(test)]
32mod tests;
33
34/// How many times [`listening_is_safe`] tries to catch a pooler.
35const PROBE_ROUNDS: usize = 5;
36
37/// The check's time limit, in query limits (two connections opened and a few queries a round).
38const PROBE_LIMITS: u32 = 4;
39
40/// Whether a `LISTEN` on connection `y` would stay on one Postgres server process, as directly
41/// or through a pooler in session mode; `false` behind a pooler in transaction mode (B16).
42/// Each round it reads `y`'s server process, opens a transaction on `x` (a pooler then usually
43/// lends `x` the server connection `y` just gave back), and reads `y`'s again while `x` holds
44/// it: `x` on `y`'s process (two clients on one server process: only a pooler does that) or
45/// `y` on another one is a pooler in transaction mode. Repeated, so a pooler that happens to
46/// lend other connections still shows.
47///
48/// # Errors
49///
50/// [`sqlx::Error`] if a query fails.
51pub async fn listening_is_safe(
52    y: &mut sqlx::PgConnection,
53    x: &mut sqlx::PgConnection,
54) -> Result<bool, sqlx::Error> {
55    const PROCESS: &str = "SELECT pg_backend_pid()";
56    for _ in 0..PROBE_ROUNDS {
57        let before: i32 = sqlx::query_scalar(PROCESS).fetch_one(&mut *y).await?;
58        let mut held = sqlx::Connection::begin(&mut *x).await?;
59        let other: i32 = sqlx::query_scalar(PROCESS).fetch_one(&mut *held).await?;
60        let after: i32 = sqlx::query_scalar(PROCESS).fetch_one(&mut *y).await?;
61        held.rollback().await?;
62        if other == before || after != before {
63            return Ok(false);
64        }
65    }
66    Ok(true)
67}
68
69/// The Postgres notification channel a new command is announced on.
70pub const COMMANDS_CHANNEL: &str = "schedr_commands";
71
72/// The channel a named event posted through the API is announced on (decision 486): the
73/// master's trigger loop looks at once. A lost one is found by the next tick's probe (the post
74/// cleared its listeners' stored time).
75pub const EVENTS_CHANNEL: &str = "schedr_events";
76
77/// Notifications of new commands and posted named events (Postgres only): a dedicated
78/// connection listening on [`COMMANDS_CHANNEL`] and [`EVENTS_CHANNEL`].
79#[derive(Debug)]
80pub struct CommandNotifications {
81    listener: PgListener,
82}
83
84/// What a notification announced.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum Notified {
87    /// A new command ([`COMMANDS_CHANNEL`]).
88    Command,
89    /// A named event posted ([`EVENTS_CHANNEL`], decisions 486 and 487): whether it cleared
90    /// triggers' looks (the trigger loop's), and waiting steps' (the round's).
91    Event {
92        /// Triggers waiting for its name.
93        triggers: bool,
94        /// Steps waiting for it.
95        waiters: bool,
96    },
97}
98
99impl CommandNotifications {
100    /// Waits for the next notification. A lost connection is re-established (a notification
101    /// sent meanwhile is lost; polling picks the command up, the probe the event).
102    ///
103    /// # Errors
104    ///
105    /// [`DbError::Sqlx`] if the connection fails and can't be re-established.
106    pub async fn next(&mut self) -> Result<Notified, DbError> {
107        let notification = self.listener.recv().await?;
108        Ok(if notification.channel() == EVENTS_CHANNEL {
109            let payload = notification.payload();
110            Notified::Event {
111                triggers: payload.contains('t'),
112                waiters: payload.contains('w'),
113            }
114        } else {
115            Notified::Command
116        })
117    }
118
119    /// Takes the notifications that already arrived, without waiting: one tick handles every
120    /// pending command, so a burst needs one tick, not one per command. Returns whether an
121    /// event was among them.
122    pub async fn skip_arrived(&mut self) -> bool {
123        let mut event = false;
124        while let Ok(Ok(notification)) =
125            tokio::time::timeout(Duration::ZERO, self.listener.recv()).await
126        {
127            event |= notification.channel() == EVENTS_CHANNEL;
128        }
129        event
130    }
131}
132
133/// Whether there is a connection to listen through ([`Database::checked_listener`]).
134#[derive(Debug)]
135pub(crate) enum Listening {
136    /// SQLite: nothing to listen to.
137    NotPostgres,
138    /// `[database] notifications = false`.
139    Off,
140    /// The connection passes a pooler in transaction mode, through this setting's URL.
141    Unsafe {
142        /// `url` or `notifications_url`.
143        through: &'static str,
144    },
145    /// A connection, checked.
146    Ready(PgListener),
147}
148
149/// A pending command, as the master reads it.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct PendingCommand {
152    /// Its ID.
153    pub id: String,
154    /// The command, or why its stored payload doesn't read (then it is rejected).
155    pub command: Result<Command, String>,
156    /// Who asked for it.
157    pub requested_by: String,
158    /// When.
159    pub requested_at: Timestamp,
160    /// Whether it was being applied when a round failed (see [`Database::mark_applying`]).
161    pub applying: bool,
162}
163
164/// A command row, as the CLI and the UI read it.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct CommandRecord {
167    /// Its ID.
168    pub id: String,
169    /// Its kind (`trigger_run`, ...).
170    pub kind: String,
171    /// Where it stands.
172    pub status: CommandStatus,
173    /// Why it was rejected.
174    pub reason: Option<String>,
175    /// What it produced when applied (e.g. `{"run_id": ...}`).
176    pub result: Option<serde_json::Value>,
177    /// Who asked for it.
178    pub requested_by: String,
179    /// When.
180    pub requested_at: Timestamp,
181    /// When the master decided it.
182    pub decided_at: Option<Timestamp>,
183}
184
185/// What [`Database::submit_command`] did.
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub enum Submitted {
188    /// Stored: the new command's ID.
189    New(String),
190    /// Sent before with this key: the command stored then, unchanged.
191    Again(String),
192    /// The key was used by the same person for another command: nothing stored.
193    KeyTaken,
194}
195
196type RecordRow = (
197    String,
198    String,
199    String,
200    Option<String>,
201    Option<String>,
202    String,
203    String,
204    Option<String>,
205);
206
207impl Database {
208    /// Writes a command for the master; returns its ID.
209    ///
210    /// # Errors
211    ///
212    /// [`DbError::Sqlx`] if the statement fails.
213    pub async fn insert_command(
214        &self,
215        command: &Command,
216        requested_by: &str,
217        now: Timestamp,
218    ) -> Result<String, DbError> {
219        match self
220            .submit_command(command, requested_by, None, now)
221            .await?
222        {
223            Submitted::New(id) | Submitted::Again(id) => Ok(id),
224            Submitted::KeyTaken => unreachable!("a command without a key is always new"),
225        }
226    }
227
228    /// Writes a command for the master, once per `key` (the client's `Idempotency-Key`, B140):
229    /// a request sent again after its answer was lost finds the command it stored, as long as
230    /// the same person sends the same command with it.
231    ///
232    /// # Errors
233    ///
234    /// [`DbError`] if a statement fails or the stored command doesn't read.
235    pub async fn submit_command(
236        &self,
237        command: &Command,
238        requested_by: &str,
239        key: Option<&str>,
240        now: Timestamp,
241    ) -> Result<Submitted, DbError> {
242        const INSERT: &str = "INSERT INTO commands \
243            (id, kind, payload, requested_by, requested_at, request_key) \
244            VALUES ($1{uuid}, $2, $3{json}, $4, $5{ts}, $6) \
245            ON CONFLICT (requested_by, request_key) WHERE request_key IS NOT NULL DO NOTHING";
246        const BY_KEY: &str = "SELECT id{text}, payload{text} FROM commands \
247            WHERE requested_by = $1 AND request_key = $2";
248        let id = Uuid::now_v7().to_string();
249        let payload = to_json(command);
250        let earlier: Option<(String, String)> = in_tx!(self, |tx, backend| {
251            let inserted = sqlx::query(sql(backend, INSERT))
252                .bind(&id)
253                .bind(command.kind())
254                .bind(&payload)
255                .bind(requested_by)
256                .bind(db_time(now))
257                .bind(key)
258                .execute(&mut *tx)
259                .await?
260                .rows_affected();
261            if inserted == 1 {
262                None
263            } else {
264                Some(
265                    sqlx::query_as(sql(backend, BY_KEY))
266                        .bind(requested_by)
267                        .bind(key)
268                        .fetch_one(&mut *tx)
269                        .await?,
270                )
271            }
272        });
273        if let Some((earlier, stored)) = earlier {
274            // The same command again (its payload names its kind), or another under its key.
275            let stored: serde_json::Value = from_json("commands.payload", &stored)?;
276            let sent: serde_json::Value = from_json("commands.payload", &payload)?;
277            return Ok(if stored == sent {
278                Submitted::Again(earlier)
279            } else {
280                Submitted::KeyTaken
281            });
282        }
283        self.notify(COMMANDS_CHANNEL, &id).await;
284        Ok(Submitted::New(id))
285    }
286
287    /// Announces `id`, stored already, on `channel` (Postgres, notifications on): a failed
288    /// notification only delays it to the master's next poll, so it isn't an error (a retried
289    /// request would store it twice).
290    pub(crate) async fn notify(&self, channel: &str, id: &str) {
291        if let Pool::Postgres(pool) = self.pool()
292            && self.notifications().on
293            && let Err(error) = sqlx::query("SELECT pg_notify($1, $2)")
294                .bind(channel)
295                .bind(id)
296                .execute(pool)
297                .await
298        {
299            tracing::warn!(%error, channel, id, "stored, its notification failed");
300        }
301    }
302
303    /// Listens for new commands: notifications on Postgres, through `notifications_url` if
304    /// set, else this database's own connections; `None` (the master polls) on SQLite, which
305    /// has none, with notifications off, or when the connection it would listen through
306    /// passes a pooler in transaction mode: there a `LISTEN` holds on to a server connection
307    /// that the pooler lends to other clients, whose queries then fail on notifications they
308    /// don't expect (B16). That is checked first ([`listening_is_safe`]); found, it says so
309    /// and how to have notifications all the same.
310    ///
311    /// # Errors
312    ///
313    /// [`DbError::Sqlx`] if the listening connection can't be opened or checked.
314    pub async fn command_notifications(&self) -> Result<Option<CommandNotifications>, DbError> {
315        let mut listener = match self.checked_listener().await? {
316            Listening::NotPostgres => return Ok(None),
317            Listening::Off => {
318                tracing::info!(
319                    "notifications off (`[database] notifications = false`): new commands are \
320                     picked up by polling, every round"
321                );
322                return Ok(None);
323            }
324            Listening::Unsafe { through } => {
325                tracing::warn!(
326                    through,
327                    "the connection the master would listen through passes a connection pooler \
328                     in transaction mode (PgBouncer or similar), where listening breaks other \
329                     connections: notifications off, new commands are picked up by polling, \
330                     every round. For immediate commands set `[database] notifications_url` to \
331                     a connection straight to Postgres; `notifications = false` silences this"
332                );
333                return Ok(None);
334            }
335            Listening::Ready(listener) => listener,
336        };
337        listener
338            .listen_all([COMMANDS_CHANNEL, EVENTS_CHANNEL])
339            .await?;
340        Ok(Some(CommandNotifications { listener }))
341    }
342
343    /// A connection to listen through (Postgres's `LISTEN`), once it is checked not to pass a
344    /// connection pooler in transaction mode ([`listening_is_safe`]); or why there is none.
345    ///
346    /// # Errors
347    ///
348    /// [`DbError::Sqlx`] if the connection can't be opened or checked;
349    /// [`DbError::QueryTimeout`] if the check can't finish in time (the database may only be
350    /// slow: the caller polls and tries again later).
351    pub(crate) async fn checked_listener(&self) -> Result<Listening, DbError> {
352        let Pool::Postgres(pool) = self.pool() else {
353            return Ok(Listening::NotPostgres);
354        };
355        let notifications = self.notifications();
356        if !notifications.on {
357            return Ok(Listening::Off);
358        }
359        let url = notifications.url.as_deref();
360        let checked = self
361            .limited(self.query_timeout() * PROBE_LIMITS, async {
362                Ok(if let Some(url) = url {
363                    let mut y = sqlx::PgConnection::connect(url).await?;
364                    let mut x = sqlx::PgConnection::connect(url).await?;
365                    listening_is_safe(&mut y, &mut x).await?
366                } else {
367                    // Guarded: a check cut short (its time up) closes them, never handing back
368                    // `x` inside the transaction it was starting (B84).
369                    let mut y = Starting::new(pool.acquire().await?);
370                    let mut x = Starting::new(pool.acquire().await?);
371                    let safe = listening_is_safe(y.conn(), x.conn()).await?;
372                    y.completed();
373                    x.completed();
374                    safe
375                })
376            })
377            .await;
378        // A check that can't finish isn't a verdict: the database may only be slow (a pooler
379        // with one server connection can't pass it either). The caller polls, and tries again
380        // later (`Hub::with_listen_retry`).
381        let safe = match checked {
382            Ok(safe) => safe,
383            Err(error @ DbError::QueryTimeout(_)) => {
384                tracing::warn!(
385                    %error,
386                    "couldn't check whether a listening connection passes a connection pooler \
387                     in transaction mode (the database answered too slowly): polling for now"
388                );
389                return Err(error);
390            }
391            Err(error) => return Err(error),
392        };
393        if !safe {
394            return Ok(Listening::Unsafe {
395                through: if url.is_some() {
396                    "notifications_url"
397                } else {
398                    "url"
399                },
400            });
401        }
402        Ok(Listening::Ready(match url {
403            Some(url) => PgListener::connect(url).await?,
404            None => PgListener::connect_with(pool).await?,
405        }))
406    }
407
408    /// The oldest `limit` pending commands, oldest first: a backlog is read a round's worth at
409    /// a time, not whole each round (B52).
410    ///
411    /// # Errors
412    ///
413    /// [`DbError::Sqlx`] if the query fails.
414    pub async fn pending_commands(&self, limit: u32) -> Result<Vec<PendingCommand>, DbError> {
415        const PENDING: &str = concat!(
416            "SELECT id{text}, payload{text}, requested_by, \
417            {ts<}requested_at{>ts}, {ts<}applying_at{>ts} ",
418            pending_from!(),
419            " ORDER BY requested_at, id LIMIT $1"
420        );
421        type Row = (String, String, String, String, Option<String>);
422        if self.skipped(crate::probe::Check::Commands).await? {
423            return Ok(Vec::new());
424        }
425        let rows: Vec<Row> = on_pool!(self, |pool, backend| {
426            sqlx::query_as(sql(backend, PENDING))
427                .bind(i64::from(limit))
428                .fetch_all(pool)
429                .await?
430        });
431        rows.into_iter()
432            .map(|(id, payload, requested_by, requested_at, applying_at)| {
433                Ok(PendingCommand {
434                    id,
435                    command: serde_json::from_str(&payload).map_err(|e| e.to_string()),
436                    requested_by,
437                    requested_at: parse_time("commands.requested_at", &requested_at)?,
438                    applying: applying_at.is_some(),
439                })
440            })
441            .collect()
442    }
443
444    /// Marks a pending command as being applied, before its first write: if its round fails
445    /// before it is decided, the next one knows it may find its own work done (B7).
446    ///
447    /// # Errors
448    ///
449    /// [`DbError::Sqlx`] if the statement fails.
450    pub async fn mark_applying(&self, id: &str, now: Timestamp) -> Result<(), DbError> {
451        const MARK: &str = "UPDATE commands SET applying_at = $1{ts} \
452            WHERE id = $2{uuid} AND status = 'pending'";
453        in_tx!(self, |tx, backend| {
454            sqlx::query(sql(backend, MARK))
455                .bind(db_time(now))
456                .bind(id)
457                .execute(&mut *tx)
458                .await?
459                .rows_affected()
460        });
461        Ok(())
462    }
463
464    /// Decides a pending command: `applied` with its result, or `rejected` with a reason.
465    /// Returns whether it was still pending.
466    ///
467    /// # Errors
468    ///
469    /// [`DbError::Sqlx`] if the statement fails.
470    pub async fn decide_command(
471        &self,
472        id: &str,
473        status: CommandStatus,
474        reason: Option<&str>,
475        result: Option<&serde_json::Value>,
476        now: Timestamp,
477    ) -> Result<bool, DbError> {
478        const DECIDE: &str = "UPDATE commands SET status = $1, reason = $2, result = $3{json}, \
479            decided_at = $4{ts} WHERE id = $5{uuid} AND status = 'pending'";
480        let decided = in_tx!(self, |tx, backend| {
481            sqlx::query(sql(backend, DECIDE))
482                .bind(
483                    serde_json::to_value(status)
484                        .ok()
485                        .and_then(|v| v.as_str().map(str::to_owned)),
486                )
487                .bind(reason)
488                .bind(result.map(to_json))
489                .bind(db_time(now))
490                .bind(id)
491                .execute(&mut *tx)
492                .await?
493                .rows_affected()
494        });
495        Ok(decided == 1)
496    }
497
498    /// Replaces an applied command's result: a connections command's, as its workers answer
499    /// (the master the only writer, one answer at a time). Whether it was applied.
500    ///
501    /// # Errors
502    ///
503    /// [`DbError`] if the update fails.
504    pub async fn set_command_result(
505        &self,
506        id: &str,
507        result: &serde_json::Value,
508    ) -> Result<bool, DbError> {
509        const SET: &str =
510            "UPDATE commands SET result = $1{json} WHERE id = $2{uuid} AND status = 'applied'";
511        let set = in_tx!(self, |tx, backend| {
512            sqlx::query(sql(backend, SET))
513                .bind(to_json(result))
514                .bind(id)
515                .execute(&mut *tx)
516                .await?
517                .rows_affected()
518        });
519        Ok(set == 1)
520    }
521
522    /// A command row by ID.
523    ///
524    /// # Errors
525    ///
526    /// [`DbError`] if the query fails or stored data doesn't read.
527    pub async fn command(&self, id: &str) -> Result<Option<CommandRecord>, DbError> {
528        const ONE: &str = "SELECT id{text}, kind, status, reason, result{text}, requested_by, \
529            {ts<}requested_at{>ts}, {ts<}decided_at{>ts} FROM commands WHERE id = $1{uuid}";
530        let row: Option<RecordRow> = on_pool!(self, |pool, backend| {
531            sqlx::query_as(sql(backend, ONE))
532                .bind(id)
533                .fetch_optional(pool)
534                .await?
535        });
536        row.map(record).transpose()
537    }
538
539    /// The commands about a run, oldest first: those naming it (cancel it, cancel or retry one
540    /// of its tasks), the trigger that made it (its result names it) and a pause that cancelled
541    /// it (its result lists it). `run_id` as schedr writes IDs (lowercase).
542    ///
543    /// # Errors
544    ///
545    /// [`DbError`] if the query fails or stored data doesn't read.
546    pub async fn run_commands(&self, run_id: &str) -> Result<Vec<CommandRecord>, DbError> {
547        const OF_RUN: &str = "SELECT id{text}, kind, status, reason, result{text}, \
548            requested_by, {ts<}requested_at{>ts}, {ts<}decided_at{>ts} FROM commands \
549            WHERE payload ->> 'run_id' = $1 OR result ->> 'run_id' = $1 \
550            OR (kind = 'pause_dag' AND result{text} LIKE $2) \
551            ORDER BY requested_at, commands.id";
552        let rows: Vec<RecordRow> = on_pool!(self, |pool, backend| {
553            sqlx::query_as(sql(backend, OF_RUN))
554                .bind(run_id)
555                // A UUID has no `%` or `_`; quoted, it is one element of `cancelled_runs`.
556                .bind(format!("%\"{run_id}\"%"))
557                .fetch_all(pool)
558                .await?
559        });
560        rows.into_iter().map(record).collect()
561    }
562
563    /// Marks every job still `running` in a connections command's result `lost`, with
564    /// `why`: at a master's start, the answers to an earlier master's jobs never come. How
565    /// many commands it changed.
566    ///
567    /// # Errors
568    ///
569    /// [`DbError`] if a query fails or stored data doesn't read.
570    pub async fn connections_commands_lost(&self, why: &str) -> Result<usize, DbError> {
571        const RUNNING: &str = "SELECT id{text}, kind, status, reason, result{text}, \
572            requested_by, {ts<}requested_at{>ts}, {ts<}decided_at{>ts} FROM commands \
573            WHERE status = 'applied' AND kind IN ('check_connections', 'test_connection') \
574            AND result{text} LIKE '%\"running\"%'";
575        let rows: Vec<RecordRow> = on_pool!(self, |pool, backend| {
576            sqlx::query_as(sql(backend, RUNNING))
577                .fetch_all(pool)
578                .await?
579        });
580        let mut changed = 0;
581        for row in rows {
582            let command = record(row)?;
583            let Some(mut result) = command.result else {
584                continue;
585            };
586            let mut lost = false;
587            let jobs = result
588                .get_mut("jobs")
589                .and_then(serde_json::Value::as_array_mut);
590            for job in jobs.into_iter().flatten() {
591                if job.get("state").and_then(serde_json::Value::as_str) == Some("running") {
592                    job["state"] = "lost".into();
593                    job["reason"] = why.into();
594                    lost = true;
595                }
596            }
597            if lost && self.set_command_result(&command.id, &result).await? {
598                changed += 1;
599            }
600        }
601        Ok(changed)
602    }
603}
604
605fn record(row: RecordRow) -> Result<CommandRecord, DbError> {
606    let (id, kind, status, reason, result, requested_by, requested_at, decided_at) = row;
607    Ok(CommandRecord {
608        id,
609        kind,
610        status: from_name("commands.status", status)?,
611        reason,
612        result: result
613            .map(|r| from_json("commands.result", &r))
614            .transpose()?,
615        requested_by,
616        requested_at: parse_time("commands.requested_at", &requested_at)?,
617        decided_at: decided_at
618            .map(|t| parse_time("commands.decided_at", &t))
619            .transpose()?,
620    })
621}