Skip to main content

schedr_db/
changes.rs

1//! What changed, for the UI's live pages (see archive/PROJECT.md, Web UI: 34A): which run, which
2//! DAG, or the workers. Only what changed, never the new state: the UI reads that from the API.
3//!
4//! The writes signal it themselves (triggers in the migrations): on Postgres a notification on
5//! [`CHANGES_CHANNEL`] when the writing transaction commits, read through a listening
6//! connection; on SQLite a row in `changes`, read by polling about once a second.
7
8use std::collections::BTreeSet;
9use std::time::Duration;
10
11use schedr_model::DagId;
12use sqlx::postgres::PgListener;
13
14use crate::commands::Listening;
15use crate::database::{Database, DbError, Pool};
16use crate::query::{on_pool, sql};
17
18#[cfg(test)]
19mod tests;
20
21/// The Postgres notification channel changes are announced on.
22pub const CHANGES_CHANNEL: &str = "schedr_changes";
23
24/// How often SQLite's `changes` table is read.
25pub const POLL_INTERVAL: Duration = Duration::from_secs(1);
26
27/// At most this many rows of `changes` a read.
28pub const POLL_ROWS: usize = 1_000;
29
30/// Something that changed.
31#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
32pub enum Change {
33    /// A run: itself, its tasks or their attempts.
34    Run {
35        /// The run.
36        run_id: String,
37        /// Its DAG.
38        dag_id: DagId,
39    },
40    /// A DAG: defined, changed, paused, removed.
41    Dag {
42        /// The DAG.
43        dag_id: DagId,
44    },
45    /// The workers: one registered, changed state, or was seen.
46    Workers,
47    /// Changes were missed (more came than were kept): everything may have changed.
48    Missed,
49}
50
51impl Change {
52    /// A change as the triggers write it: `run <run id> <dag id>`, `dag <dag id>`, `workers`;
53    /// `None` for anything else.
54    #[must_use]
55    pub fn parse(text: &str) -> Option<Self> {
56        let mut words = text.split(' ');
57        let change = match (words.next()?, words.next(), words.next()) {
58            ("run", Some(run_id), Some(dag_id)) => Self::Run {
59                run_id: run_id.to_owned(),
60                dag_id: DagId::new(dag_id).ok()?,
61            },
62            ("dag", Some(dag_id), None) => Self::Dag {
63                dag_id: DagId::new(dag_id).ok()?,
64            },
65            ("workers", None, None) => Self::Workers,
66            _ => return None,
67        };
68        words.next().is_none().then_some(change)
69    }
70}
71
72/// The changes as they happen: [`Changes::next`] waits for the next ones.
73#[derive(Debug)]
74pub struct Changes {
75    source: Source,
76}
77
78#[derive(Debug)]
79enum Source {
80    /// A listening connection; `lost`: it was lost and isn't listening again yet.
81    Listen { listener: PgListener, lost: bool },
82    Poll {
83        db: Database,
84        after: i64,
85        interval: Duration,
86        rows: i64,
87    },
88}
89
90impl Database {
91    /// The changes from now on; `None` when they can't be followed (Postgres with
92    /// notifications off, or behind a connection pooler in transaction mode without a
93    /// `notifications_url`): the UI then refreshes on a timer.
94    ///
95    /// # Errors
96    ///
97    /// [`DbError`] if the database can't be reached or checked.
98    pub async fn changes(&self, poll: Duration) -> Result<Option<Changes>, DbError> {
99        self.changes_reading(poll, POLL_ROWS).await
100    }
101
102    /// As [`Self::changes`], SQLite's polls reading at most `rows` rows each
103    /// (`SCHEDR_HIDDEN__DATABASE__CHANGES_POLL_ROWS`).
104    ///
105    /// # Errors
106    ///
107    /// As [`Self::changes`].
108    pub async fn changes_reading(
109        &self,
110        poll: Duration,
111        rows: usize,
112    ) -> Result<Option<Changes>, DbError> {
113        match self.checked_listener().await? {
114            Listening::NotPostgres => {
115                const LAST: &str = "SELECT COALESCE(MAX(seq), 0) FROM changes";
116                let after: i64 = on_pool!(self, |pool, backend| {
117                    sqlx::query_scalar(sql(backend, LAST))
118                        .fetch_one(pool)
119                        .await?
120                });
121                Ok(Some(Changes {
122                    source: Source::Poll {
123                        db: self.clone(),
124                        after,
125                        interval: poll,
126                        rows: i64::try_from(rows).unwrap_or(i64::MAX),
127                    },
128                }))
129            }
130            Listening::Off | Listening::Unsafe { .. } => Ok(None),
131            Listening::Ready(mut listener) => {
132                // A lost connection is re-established by `next`, not inside the read that finds
133                // it lost: a read cut short there (the drain's zero timeout, a caller's) would
134                // drop the loss (B85).
135                listener.eager_reconnect(false);
136                listener.listen(CHANGES_CHANNEL).await?;
137                Ok(Some(Changes {
138                    source: Source::Listen {
139                        listener,
140                        lost: false,
141                    },
142                }))
143            }
144        }
145    }
146}
147
148/// The change triggers on Postgres, by table (`[database] change_notifications` turns them on
149/// and off: [`Database::set_change_notifications`]).
150const POSTGRES_TRIGGERS: [(&str, &str); 19] = [
151    ("runs", "runs_inserted"),
152    ("runs", "runs_updated"),
153    ("task_instances", "task_instances_inserted"),
154    ("task_instances", "task_instances_updated"),
155    ("attempts", "attempts_inserted"),
156    ("attempts", "attempts_updated"),
157    ("dags", "dags_inserted"),
158    ("dags", "dags_updated"),
159    ("dag_triggers", "dag_triggers_inserted"),
160    ("dag_triggers", "dag_triggers_updated"),
161    ("dag_triggers", "dag_triggers_deleted"),
162    ("wait_step_strikes", "wait_step_strikes_inserted"),
163    ("wait_step_strikes", "wait_step_strikes_updated"),
164    ("wait_step_strikes", "wait_step_strikes_deleted"),
165    ("trigger_progress", "trigger_progress_inserted"),
166    ("trigger_progress", "trigger_progress_updated"),
167    ("workers", "workers_inserted"),
168    ("workers", "workers_updated"),
169    ("workers", "workers_deleted"),
170];
171
172impl Database {
173    /// Whether the writes announce their changes (the change triggers are on): on Postgres all
174    /// of them enabled, on SQLite the `changes_switch` row.
175    ///
176    /// # Errors
177    ///
178    /// [`DbError`] if the query fails.
179    pub async fn change_notifications(&self) -> Result<bool, DbError> {
180        match self.pool() {
181            Pool::Postgres(pool) => {
182                let names: Vec<&str> = triggers().map(|(_, name)| name).collect();
183                let on: i64 = sqlx::query_scalar(
184                    "SELECT COUNT(*) FROM pg_trigger WHERE tgname = ANY($1) AND tgenabled <> 'D'",
185                )
186                .bind(&names)
187                .fetch_one(pool)
188                .await?;
189                Ok(usize::try_from(on).is_ok_and(|on| on == names.len()))
190            }
191            Pool::Sqlite(pool) => {
192                let on: i64 = sqlx::query_scalar("SELECT notify FROM changes_switch")
193                    .fetch_one(pool)
194                    .await?;
195                Ok(on != 0)
196            }
197        }
198    }
199
200    /// Turns the change triggers on or off (`[database] change_notifications`), only if they
201    /// aren't so already; whether anything changed. On Postgres it alters the tables (a brief
202    /// exclusive lock on each): `schedr db migrate` and `--migrate` call it, holding the
203    /// master's lease, never a running master.
204    ///
205    /// # Errors
206    ///
207    /// [`DbError`] if a statement fails.
208    pub async fn set_change_notifications(&self, on: bool) -> Result<bool, DbError> {
209        if self.change_notifications().await? == on {
210            return Ok(false);
211        }
212        match self.pool() {
213            Pool::Postgres(pool) => {
214                let verb = if on { "ENABLE" } else { "DISABLE" };
215                // Not `pool.begin()`: a start cut short mustn't go back to the pool (B84).
216                let mut starting = crate::query::Starting::new(pool.acquire().await?);
217                let mut tx = starting.begin("BEGIN").await?;
218                for (table, name) in triggers() {
219                    let statement = format!("ALTER TABLE {table} {verb} TRIGGER {name}");
220                    sqlx::query(sqlx::AssertSqlSafe(statement))
221                        .execute(&mut *tx)
222                        .await?;
223                }
224                tx.commit().await?;
225            }
226            Pool::Sqlite(pool) => {
227                sqlx::query("UPDATE changes_switch SET notify = $1")
228                    .bind(i64::from(on))
229                    .execute(pool)
230                    .await?;
231            }
232        }
233        Ok(true)
234    }
235}
236
237/// [`POSTGRES_TRIGGERS`] (fixed names: formatting them into SQL is safe).
238fn triggers() -> impl Iterator<Item = (&'static str, &'static str)> {
239    POSTGRES_TRIGGERS.into_iter()
240}
241
242impl Changes {
243    /// Waits for the next changes, each once, in order. A lost listening connection is
244    /// re-established, and what changed meanwhile comes as [`Change::Missed`], once the
245    /// connection listens again.
246    ///
247    /// # Errors
248    ///
249    /// [`DbError`] if the database fails (polling) or the connection can't be re-established.
250    pub async fn next(&mut self) -> Result<Vec<Change>, DbError> {
251        match &mut self.source {
252            Source::Listen { listener, lost } => {
253                let mut changes = BTreeSet::new();
254                if !*lost {
255                    match listener.try_recv().await? {
256                        Some(first) => changes.extend(Change::parse(first.payload())),
257                        None => *lost = true,
258                    }
259                }
260                // Those that already arrived come with it. A connection lost meanwhile is
261                // missed changes too (B85): the loss is read only once.
262                while !*lost {
263                    match tokio::time::timeout(Duration::ZERO, listener.try_recv()).await {
264                        Ok(Ok(Some(more))) => changes.extend(Change::parse(more.payload())),
265                        Ok(Ok(None) | Err(_)) => *lost = true,
266                        Err(_) => return Ok(changes.into_iter().collect()),
267                    }
268                }
269                // Listening again before the loss is reported, so what changes after the
270                // report is heard; a call cut short here reports it the next time.
271                listener.listen_all(std::iter::empty::<&str>()).await?;
272                *lost = false;
273                changes.insert(Change::Missed);
274                Ok(changes.into_iter().collect())
275            }
276            Source::Poll {
277                db,
278                after,
279                interval,
280                rows,
281            } => loop {
282                tokio::time::sleep(*interval).await;
283                let changes = read_after(db, after, *rows).await?;
284                if !changes.is_empty() {
285                    return Ok(changes);
286                }
287            },
288        }
289    }
290}
291
292/// The `changes` rows after `after`, each change once; moves `after` past them. A gap before
293/// the first (rows pruned unread) is [`Change::Missed`].
294async fn read_after(db: &Database, after: &mut i64, rows: i64) -> Result<Vec<Change>, DbError> {
295    const AFTER: &str = "SELECT seq, change FROM changes WHERE seq > $1 ORDER BY seq LIMIT $2";
296    let rows: Vec<(i64, String)> = on_pool!(db, |pool, backend| {
297        sqlx::query_as(sql(backend, AFTER))
298            .bind(*after)
299            .bind(rows)
300            .fetch_all(pool)
301            .await?
302    });
303    let mut changes = BTreeSet::new();
304    // `seq` counts from 1 and only the oldest rows are pruned: a first row past the next one
305    // means rows were pruned unread (from an empty table's cursor, 0, too).
306    if let Some((first, _)) = rows.first()
307        && *first > *after + 1
308    {
309        changes.insert(Change::Missed);
310    }
311    if let Some((last, _)) = rows.last() {
312        *after = *last;
313    }
314    changes.extend(rows.iter().filter_map(|(_, text)| Change::parse(text)));
315    Ok(changes.into_iter().collect())
316}