1use 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
31pub const REFRESH_INTERVAL: Duration = Duration::from_secs(15);
34
35const RECHECK: Duration = Duration::from_secs(60);
38
39pub const KEEP_ALIVE: Duration = Duration::from_secs(15);
41
42const RETRY: Duration = Duration::from_secs(1);
44
45const BACKLOG: usize = 1_024;
47
48#[derive(Debug, Clone, PartialEq, Eq)]
50pub enum Live {
51 Change(Change),
53 Refresh,
55}
56
57#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct EventTimings {
69 pub recheck: Duration,
71 pub keep_alive: Duration,
73 pub retry: Duration,
75 pub changes_poll: Duration,
77 pub changes_rows: usize,
79 pub backlog: usize,
82}
83
84impl Default for EventTimings {
85 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 #[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 #[must_use]
112 pub const fn keep_alive(&self) -> Duration {
113 self.timings.keep_alive
114 }
115
116 #[must_use]
118 pub fn with_timings(self, timings: EventTimings) -> Self {
119 Self { timings, ..self }
120 }
121
122 #[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 #[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
149async 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 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 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 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
243pub 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#[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 Err(broadcast::error::RecvError::Lagged(_)) => Live::Refresh,
276 Err(broadcast::error::RecvError::Closed) => return,
277 };
278 if sender.send(Ok(event(&live))).await.is_err() {
280 return;
281 }
282 }
283 });
284 (
286 [("x-accel-buffering", "no")],
287 Sse::new(ReceiverStream::new(receiver))
288 .keep_alive(KeepAlive::new().interval(state.feed.keep_alive())),
289 )
290}