Skip to main content

schedr_api/
events.rs

1//! `GET /api/v1/changes`: what changed, as server-sent events, for the UI's live pages (see
2//! archive/PROJECT.md, Web UI: 34A). Only what changed, never the new state: a client reads that
3//! from the other endpoints.
4//!
5//! Events: `run` (`{"run_id", "dag_id"}`: the run, its tasks or attempts), `dag`
6//! (`{"dag_id"}`), `workers` (`{}`), and `refresh` (`{}`: anything may have changed, when
7//! changes were missed or can't be followed; then every `refresh_interval`, 15 s
8//! by default). A comment
9//! every [`KEEP_ALIVE`] keeps idle connections open through proxies.
10//!
11//! One follower per webserver reads the database's changes ([`Database::changes`]), started
12//! by the first subscriber, and hands them to every connection.
13
14use std::convert::Infallible;
15use std::sync::{Arc, OnceLock};
16use std::time::Duration;
17
18use axum::extract::State;
19use axum::response::sse::{Event, KeepAlive, Sse};
20use schedr_db::Database;
21use schedr_db::changes::Change;
22use serde_json::json;
23use tokio::sync::{broadcast, mpsc};
24use tokio_stream::wrappers::ReceiverStream;
25
26use crate::state::ApiState;
27
28#[cfg(test)]
29mod tests;
30
31/// How often `refresh` is sent when the database's changes can't be followed, unless set
32/// otherwise (`refresh_interval`).
33pub const REFRESH_INTERVAL: Duration = Duration::from_secs(15);
34
35/// How often a follower checks that the database still announces its changes (turned off by
36/// `schedr db migrate` meanwhile, the pages are refreshed instead).
37const RECHECK: Duration = Duration::from_secs(60);
38
39/// How often an idle connection gets a comment.
40pub const KEEP_ALIVE: Duration = Duration::from_secs(15);
41
42/// How long the follower waits after the database fails before trying again.
43const RETRY: Duration = Duration::from_secs(1);
44
45/// Changes a slow connection may fall behind by before it gets `refresh` instead.
46const BACKLOG: usize = 1_024;
47
48/// What the follower hands out.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum Live {
51    /// Something changed.
52    Change(Change),
53    /// Anything may have changed.
54    Refresh,
55}
56
57/// The webserver's feed of changes: a follower started by the first subscriber.
58#[derive(Debug, Clone)]
59pub struct Feed {
60    db: Database,
61    refresh: Duration,
62    timings: EventTimings,
63    sender: Arc<OnceLock<broadcast::Sender<Live>>>,
64}
65
66/// How the webserver follows the database's changes.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct EventTimings {
69    /// How often whether they are announced is looked at (`events_recheck`).
70    pub recheck: Duration,
71    /// How often a stream gets a comment (`events_keep_alive`).
72    pub keep_alive: Duration,
73    /// How soon a failure is tried again (`events_retry`).
74    pub retry: Duration,
75    /// How often changes are read where they aren't announced (`changes_poll_interval`).
76    pub changes_poll: Duration,
77    /// The most rows of SQLite's `changes` one read takes (`DATABASE__CHANGES_POLL_ROWS`).
78    pub changes_rows: usize,
79    /// The changes a slow stream may fall behind by before it gets `refresh`
80    /// (`WEBSERVER__EVENTS_BACKLOG`).
81    pub backlog: usize,
82}
83
84impl Default for EventTimings {
85    /// What every webserver runs with.
86    fn default() -> Self {
87        Self {
88            recheck: RECHECK,
89            keep_alive: KEEP_ALIVE,
90            retry: RETRY,
91            changes_poll: schedr_db::changes::POLL_INTERVAL,
92            changes_rows: schedr_db::changes::POLL_ROWS,
93            backlog: BACKLOG,
94        }
95    }
96}
97
98impl Feed {
99    /// A feed over `db`, not following it yet.
100    #[must_use]
101    pub fn new(db: Database) -> Self {
102        Self {
103            db,
104            refresh: REFRESH_INTERVAL,
105            timings: EventTimings::default(),
106            sender: Arc::new(OnceLock::new()),
107        }
108    }
109
110    /// How often a stream gets a comment.
111    #[must_use]
112    pub const fn keep_alive(&self) -> Duration {
113        self.timings.keep_alive
114    }
115
116    /// This feed, following changes as `timings` say.
117    #[must_use]
118    pub fn with_timings(self, timings: EventTimings) -> Self {
119        Self { timings, ..self }
120    }
121
122    /// This feed sending `refresh` every `interval` when changes can't be followed.
123    #[must_use]
124    pub fn with_refresh(self, interval: Duration) -> Self {
125        Self {
126            refresh: interval.max(Duration::from_secs(1)),
127            ..self
128        }
129    }
130
131    /// The changes from now on (the follower started if it isn't).
132    #[must_use]
133    pub fn subscribe(&self) -> broadcast::Receiver<Live> {
134        self.sender
135            .get_or_init(|| {
136                let (sender, _) = broadcast::channel(self.timings.backlog.max(1));
137                tokio::spawn(follow(
138                    self.db.clone(),
139                    sender.clone(),
140                    self.refresh,
141                    self.timings,
142                ));
143                sender
144            })
145            .subscribe()
146    }
147}
148
149/// Reads the database's changes for as long as the webserver runs, sending each; when they
150/// can't be followed, `refresh` every [`REFRESH_INTERVAL`] instead. A failure is `refresh`, then
151/// another try.
152async fn follow(
153    db: Database,
154    sender: broadcast::Sender<Live>,
155    refresh: Duration,
156    timings: EventTimings,
157) {
158    loop {
159        let on = match db.change_notifications().await {
160            Ok(on) => on,
161            Err(error) => {
162                tracing::warn!(%error, "can't read whether the database announces its changes");
163                tokio::time::sleep(timings.retry).await;
164                continue;
165            }
166        };
167        let changes = if on {
168            db.changes_reading(timings.changes_poll, timings.changes_rows)
169                .await
170        } else {
171            Ok(None)
172        };
173        match changes {
174            Ok(Some(mut changes)) => {
175                let mut check = tokio::time::interval_at(
176                    tokio::time::Instant::now() + timings.recheck,
177                    timings.recheck,
178                );
179                loop {
180                    tokio::select! {
181                        batch = changes.next() => match batch {
182                            Ok(batch) => {
183                                for change in batch {
184                                    let live = match change {
185                                        Change::Missed => Live::Refresh,
186                                        change => Live::Change(change),
187                                    };
188                                    // No one listening is fine.
189                                    let _ = sender.send(live);
190                                }
191                            }
192                            Err(error) => {
193                                tracing::warn!(%error, "following the database's changes failed");
194                                let _ = sender.send(Live::Refresh);
195                                tokio::time::sleep(timings.retry).await;
196                                break;
197                            }
198                        },
199                        _ = check.tick() => {
200                            // Turned off meanwhile (`schedr db migrate`): no more changes will
201                            // come, so the pages are refreshed instead.
202                            if matches!(db.change_notifications().await, Ok(false)) {
203                                let _ = sender.send(Live::Refresh);
204                                break;
205                            }
206                        }
207                    }
208                }
209            }
210            Ok(None) => {
211                if on {
212                    tracing::info!(
213                        "the database's changes can't be followed (notifications off, or a \
214                         pooler in transaction mode): live pages refresh every {} s",
215                        refresh.as_secs()
216                    );
217                } else {
218                    tracing::info!(
219                        "the database doesn't announce its changes (`[database] \
220                         change_notifications = false`): live pages refresh every {} s",
221                        refresh.as_secs()
222                    );
223                }
224                let mut ticks =
225                    tokio::time::interval_at(tokio::time::Instant::now() + refresh, refresh);
226                loop {
227                    ticks.tick().await;
228                    let _ = sender.send(Live::Refresh);
229                    // Turned on meanwhile: followed from now on.
230                    if !on && matches!(db.change_notifications().await, Ok(true)) {
231                        break;
232                    }
233                }
234            }
235            Err(error) => {
236                tracing::warn!(%error, "can't follow the database's changes; trying again");
237                tokio::time::sleep(timings.retry).await;
238            }
239        }
240    }
241}
242
243/// `live` as a server-sent event.
244pub fn event(live: &Live) -> Event {
245    let (name, data) = match live {
246        Live::Change(Change::Run { run_id, dag_id }) => {
247            ("run", json!({"run_id": run_id, "dag_id": dag_id.as_str()}))
248        }
249        Live::Change(Change::Dag { dag_id }) => ("dag", json!({"dag_id": dag_id.as_str()})),
250        Live::Change(Change::Workers) => ("workers", json!({})),
251        Live::Change(Change::Missed) | Live::Refresh => ("refresh", json!({})),
252    };
253    Event::default().event(name).data(data.to_string())
254}
255
256/// What changed, as it happens: `run`, `dag`, `workers` and `refresh` events (see the module
257/// documentation).
258#[utoipa::path(get, path = "/api/v1/changes", tag = "runs",
259    responses((status = 200, content_type = "text/event-stream",
260        description = "Server-sent events: `run` (`{\"run_id\", \"dag_id\"}`), `dag` \
261            (`{\"dag_id\"}`), `workers` (`{}`) and `refresh` (`{}`: anything may have \
262            changed)")))]
263pub async fn events(State(state): State<ApiState>) -> impl axum::response::IntoResponse {
264    let mut changes = state.feed.subscribe();
265    let (sender, receiver) = mpsc::channel::<Result<Event, Infallible>>(16);
266    tokio::spawn(async move {
267        loop {
268            let next = tokio::select! {
269                () = sender.closed() => return,
270                next = changes.recv() => next,
271            };
272            let live = match next {
273                Ok(live) => live,
274                // Fell behind: what was skipped may be anything.
275                Err(broadcast::error::RecvError::Lagged(_)) => Live::Refresh,
276                Err(broadcast::error::RecvError::Closed) => return,
277            };
278            // The client went away.
279            if sender.send(Ok(event(&live))).await.is_err() {
280                return;
281            }
282        }
283    });
284    // Proxies asked not to buffer it (nginx's header; others may anyway: the UI then polls).
285    (
286        [("x-accel-buffering", "no")],
287        Sse::new(ReceiverStream::new(receiver))
288            .keep_alive(KeepAlive::new().interval(state.feed.keep_alive())),
289    )
290}