Skip to main content

schedr_ui/
live.rs

1//! Live pages (M3.3, decisions 34A and 23A): what changed in each deployment, relayed to the
2//! browsers, and a running attempt's log as it grows.
3//!
4//! - **Relays:** one per deployment, started by the first browser that wants its changes: it
5//!   reads the webserver's `GET /api/v1/changes` and hands each change to every browser
6//!   following that deployment; when the stream ends or can't be opened it tries again (after
7//!   1 s, doubling to 30 s), and once it is back sends `refresh`, since anything may have
8//!   changed meanwhile.
9//! - **`GET /events`:** a browser's one stream (decision 175: its pages share it through a
10//!   `SharedWorker`, `assets/live.js`): every deployment's changes, each page deciding which
11//!   concern it and reading its live parts again (`hx-trigger="live:change"`).
12//! - **The log tail:** `GET /d/<deployment>/runs/<run>/tasks/<task>/tail?try=&from=` answers
13//!   the log's next part (HTML, colours converted) and the element reading the one after it,
14//!   polled about once a second while the attempt runs (no connection held).
15
16use std::convert::Infallible;
17use std::fmt::Write as _;
18use std::sync::atomic::{AtomicI64, Ordering};
19use std::sync::{Arc, OnceLock};
20use std::time::Duration;
21
22use axum::Extension;
23use axum::extract::rejection::QueryRejection;
24use axum::extract::{OriginalUri, Path, Query, State};
25use axum::http::{HeaderMap, StatusCode, header};
26use axum::response::sse::{Event, KeepAlive, Sse};
27use axum::response::{IntoResponse, Response};
28use schedr_client::{ClientError, ServerEvent, Transport};
29use serde::Deserialize;
30use tokio::sync::{broadcast, mpsc};
31use tokio_stream::wrappers::ReceiverStream;
32
33use crate::page::prefix;
34use crate::{Ui, ansi};
35
36#[cfg(test)]
37mod tests;
38
39/// How the live pages are paced.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct UiTimings {
42    /// How often a stream gets a `ping` (`keep_alive`).
43    pub keep_alive: Duration,
44    /// A stream sends at most one `change` this often (`coalesce`).
45    pub coalesce: Duration,
46    /// How often the log tail reads the log (`tail_interval`).
47    pub tail_interval: Duration,
48    /// How long it tries a log out of reach (`tail_give_up`).
49    pub tail_give_up: Duration,
50    /// A Runs page read longer than this is slow (`slow_read`).
51    pub slow_read: Duration,
52    /// How often a page whose read was slow reads again at most (`slow_read_wait`).
53    pub slow_read_wait: Duration,
54    /// The first wait before a relay opens its stream again (`relay_retry_first`).
55    pub retry_first: Duration,
56    /// The longest one (`relay_retry_max`).
57    pub retry_max: Duration,
58    /// The changes a slow browser may fall behind by before it gets `refresh`
59    /// (`UI__EVENTS_BACKLOG`).
60    pub backlog: usize,
61}
62
63impl Default for UiTimings {
64    /// What every UI runs with.
65    fn default() -> Self {
66        Self {
67            keep_alive: KEEP_ALIVE,
68            coalesce: COALESCE,
69            tail_interval: TAIL_INTERVAL,
70            tail_give_up: TAIL_GIVE_UP,
71            slow_read: SLOW_READ,
72            slow_read_wait: SLOW_READ_WAIT,
73            retry_first: RETRY_FIRST,
74            retry_max: RETRY_MAX,
75            backlog: BACKLOG,
76        }
77    }
78}
79
80/// How often a page's stream gets a `ping` (and the log tail a comment).
81pub const KEEP_ALIVE: Duration = Duration::from_secs(15);
82
83/// A Runs page read longer than this is slow: the page then reads again at most every
84/// [`SLOW_READ_WAIT`] (a name filter matching DAGs with long histories: 114 ms over 500,000 runs,
85/// against 0.3 ms unfiltered; the user, 2026-11-16).
86pub const SLOW_READ: Duration = Duration::from_millis(50);
87
88/// How often a page whose last read was slow reads again at most.
89pub const SLOW_READ_WAIT: Duration = Duration::from_secs(5);
90
91/// A page's stream sends at most one `change` this often (per deployment).
92pub const COALESCE: Duration = Duration::from_secs(1);
93
94/// How often the log tail reads the log.
95pub const TAIL_INTERVAL: Duration = Duration::from_secs(1);
96
97/// How long the log tail keeps trying a log out of reach before it says so and stops.
98pub const TAIL_GIVE_UP: Duration = Duration::from_secs(30);
99
100/// At most this much of a log a read: the API's longest part, so a line is cut only past it
101/// (the API passes whole lines only, a longer one cut; decision 131).
102const TAIL_PART: u64 = schedr_model::logs::MAX_CHUNK;
103
104/// The first wait before a relay opens its stream again; it doubles up to [`RETRY_MAX`].
105const RETRY_FIRST: Duration = Duration::from_secs(1);
106
107/// The longest wait between a relay's attempts.
108const RETRY_MAX: Duration = Duration::from_secs(30);
109
110/// Changes a slow browser may fall behind by before it gets `refresh` instead.
111const BACKLOG: usize = 1_024;
112
113/// A change in a deployment, as its webserver announced it.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub enum Change {
116    /// A run (itself, its tasks or attempts).
117    Run {
118        /// The run.
119        run_id: String,
120        /// Its DAG.
121        dag_id: String,
122    },
123    /// A DAG.
124    Dag {
125        /// The DAG.
126        dag_id: String,
127    },
128    /// The workers.
129    Workers,
130    /// Anything may have changed.
131    Refresh,
132}
133
134impl Change {
135    /// The change a webserver's event says; `None` for one this UI doesn't know.
136    #[must_use]
137    pub fn of(event: &ServerEvent) -> Option<Self> {
138        let data: serde_json::Value = serde_json::from_str(&event.data).unwrap_or_default();
139        let text = |key: &str| data[key].as_str().map(str::to_owned);
140        Some(match event.name.as_str() {
141            "run" => Self::Run {
142                run_id: text("run_id")?,
143                dag_id: text("dag_id")?,
144            },
145            "dag" => Self::Dag {
146                dag_id: text("dag_id")?,
147            },
148            "workers" => Self::Workers,
149            "refresh" => Self::Refresh,
150            _ => return None,
151        })
152    }
153}
154
155/// The relays, one per deployment (in the order of [`Ui::deployments`]), each started by its
156/// first subscriber.
157#[derive(Debug)]
158pub struct Relays {
159    senders: Vec<OnceLock<broadcast::Sender<Change>>>,
160    /// When each deployment last changed, in milliseconds since the epoch: its last change
161    /// relayed, or its relay's start (what came before that isn't known).
162    changed: Vec<Arc<AtomicI64>>,
163}
164
165impl Relays {
166    /// Relays for `deployments` deployments, none started.
167    #[must_use]
168    pub fn new(deployments: usize) -> Self {
169        Self {
170            senders: (0..deployments).map(|_| OnceLock::new()).collect(),
171            changed: (0..deployments)
172                .map(|_| Arc::new(AtomicI64::new(0)))
173                .collect(),
174        }
175    }
176
177    /// Whether deployment `index` may have changed after `since` (milliseconds since the
178    /// epoch), by what its relay has seen.
179    fn changed_after(&self, index: usize, since: i64) -> bool {
180        self.changed[index].load(Ordering::Relaxed) > since
181    }
182
183    /// Deployment `index`'s changes from now on (its relay started if it isn't).
184    fn subscribe<T: Transport + Send + Sync + 'static>(
185        &self,
186        ui: &Arc<Ui<T>>,
187        index: usize,
188    ) -> broadcast::Receiver<Change> {
189        self.senders[index]
190            .get_or_init(|| {
191                let (sender, _) = broadcast::channel(ui.timings.backlog.max(1));
192                let changed = Arc::clone(&self.changed[index]);
193                changed.store(now_millis(), Ordering::Relaxed);
194                tokio::spawn(relay(Arc::clone(ui), index, sender.clone(), changed));
195                sender
196            })
197            .subscribe()
198    }
199}
200
201/// Reads deployment `index`'s events for as long as the UI runs (see the module's comment).
202async fn relay<T: Transport + Send + Sync>(
203    ui: Arc<Ui<T>>,
204    index: usize,
205    sender: broadcast::Sender<Change>,
206    changed: Arc<AtomicI64>,
207) {
208    let deployment = &ui.deployments[index];
209    let timings = ui.timings;
210    let mut wait = timings.retry_first;
211    let mut lost = false;
212    loop {
213        match deployment.client.events().await {
214            Ok(mut events) => {
215                if lost {
216                    changed.store(now_millis(), Ordering::Relaxed);
217                    let _ = sender.send(Change::Refresh);
218                }
219                wait = timings.retry_first;
220                while let Some(Ok(event)) = events.next().await {
221                    if let Some(change) = Change::of(&event) {
222                        changed.store(now_millis(), Ordering::Relaxed);
223                        // No one listening is fine.
224                        let _ = sender.send(change);
225                    }
226                }
227                tracing::debug!(
228                    deployment = deployment.name,
229                    "its events ended; opening again"
230                );
231            }
232            Err(error) => {
233                tracing::debug!(deployment = deployment.name, %error, "can't follow its events");
234            }
235        }
236        lost = true;
237        tokio::time::sleep(wait).await;
238        wait = (wait * 2).min(timings.retry_max);
239    }
240}
241
242/// `GET /events`'s query.
243#[derive(Debug, Clone, Default, Deserialize)]
244pub struct Follow {
245    /// When the page opening the stream was made, in milliseconds since the epoch: a
246    /// deployment changed after it is sent a `refresh` as soon as the stream opens (one the
247    /// page may not show, B144).
248    #[serde(default)]
249    pub since: Option<i64>,
250}
251
252impl Change {
253    /// The change as a stream sends it: what changed, in which deployment, and when it was
254    /// relayed (milliseconds since the epoch, this UI's clock, as a page's `since`).
255    fn json(&self, deployment: &str, at: i64) -> String {
256        let (kind, run, dag) = match self {
257            Self::Run { run_id, dag_id } => ("run", Some(run_id), Some(dag_id)),
258            Self::Dag { dag_id } => ("dag", None, Some(dag_id)),
259            Self::Workers => ("workers", None, None),
260            Self::Refresh => ("refresh", None, None),
261        };
262        serde_json::json!({
263            "deployment": deployment,
264            "kind": kind,
265            "run": run,
266            "dag": dag,
267            "at": at,
268        })
269        .to_string()
270    }
271}
272
273/// `GET /events`: one browser's stream of every deployment's changes (decision 175: its tabs
274/// share it, and each page decides which concern it). First a `hello` (now, in milliseconds
275/// since the epoch), then a `change` event for each change (JSON: `deployment`, `kind`
276/// `run`/`dag`/`workers`/`refresh`, `run`, `dag`, `at`), the same change at most once a
277/// [`COALESCE`] per deployment (never dropped: sent when that time is up), and a `ping` every
278/// [`KEEP_ALIVE`] (a page polls when even those stop coming: a proxy buffering the stream).
279pub async fn events<T: Transport + Send + Sync + 'static>(
280    State(ui): State<Arc<Ui<T>>>,
281    Extension(relays): Extension<Arc<Relays>>,
282    follow: Result<Query<Follow>, QueryRejection>,
283) -> Response {
284    let Ok(Query(follow)) = follow else {
285        return StatusCode::BAD_REQUEST.into_response();
286    };
287    let (sender, receiver) = mpsc::channel::<Result<Event, Infallible>>(64);
288    // Sent before any change: the channel is empty.
289    let _ = sender.try_send(Ok(Event::default()
290        .event("hello")
291        .data(now_millis().to_string())));
292    for (index, deployment) in ui.deployments.iter().enumerate() {
293        let changes = relays.subscribe(&ui, index);
294        let missed = follow
295            .since
296            .is_some_and(|since| relays.changed_after(index, since));
297        tokio::spawn(forward(
298            (changes, missed),
299            sender.clone(),
300            deployment.name.clone(),
301            ui.timings,
302        ));
303    }
304    streamed(receiver, ui.timings.keep_alive)
305}
306
307/// Hands one deployment's changes to a browser's stream until it goes away: a change at once,
308/// the same change again at most once a [`COALESCE`] (sent when that time is up, so the last is
309/// never missed).
310async fn forward(
311    (mut changes, missed): (broadcast::Receiver<Change>, bool),
312    sender: mpsc::Sender<Result<Event, Infallible>>,
313    deployment: String,
314    timings: UiTimings,
315) {
316    // When each change (still held back, or not) was last sent.
317    let mut sent: Vec<(Change, tokio::time::Instant)> = Vec::new();
318    // Changes held back, in order, each once.
319    let mut held: Vec<Change> = Vec::new();
320    if missed {
321        held.push(Change::Refresh);
322    }
323    let mut pings = tokio::time::interval_at(
324        tokio::time::Instant::now() + timings.keep_alive,
325        timings.keep_alive,
326    );
327    loop {
328        let now = tokio::time::Instant::now();
329        sent.retain(|(_, at)| now.duration_since(*at) < timings.coalesce);
330        // Those held back whose time is up, and when the next one's is.
331        let (due, waiting): (Vec<Change>, Vec<Change>) = held
332            .drain(..)
333            .partition(|change| !sent.iter().any(|(c, _)| c == change));
334        held = waiting;
335        for change in due {
336            sent.push((change.clone(), now));
337            let event = Event::default()
338                .event("change")
339                .data(change.json(&deployment, now_millis()));
340            if sender.send(Ok(event)).await.is_err() {
341                return;
342            }
343        }
344        let next = held
345            .iter()
346            .filter_map(|change| sent.iter().find(|(c, _)| c == change))
347            .map(|(_, at)| *at + timings.coalesce)
348            .min();
349        let ping = tokio::select! {
350            () = sender.closed() => return,
351            _ = pings.tick() => true,
352            () = tokio::time::sleep_until(next.unwrap_or(now)), if next.is_some() => false,
353            change = changes.recv() => {
354                let change = match change {
355                    Ok(change) => change,
356                    Err(broadcast::error::RecvError::Lagged(_)) => Change::Refresh,
357                    Err(broadcast::error::RecvError::Closed) => return,
358                };
359                if !held.contains(&change) {
360                    held.push(change);
361                }
362                false
363            }
364        };
365        if ping
366            && sender
367                .send(Ok(Event::default().event("ping").data("")))
368                .await
369                .is_err()
370        {
371            return;
372        }
373    }
374}
375
376/// Now, in milliseconds since the epoch.
377fn now_millis() -> i64 {
378    jiff::Timestamp::now().as_millisecond()
379}
380
381/// `receiver`'s events as a server-sent stream, a comment every [`KEEP_ALIVE`], proxies asked
382/// not to buffer it (`X-Accel-Buffering: no`, nginx's).
383fn streamed(receiver: mpsc::Receiver<Result<Event, Infallible>>, keep_alive: Duration) -> Response {
384    (
385        [("x-accel-buffering", "no")],
386        Sse::new(ReceiverStream::new(receiver)).keep_alive(KeepAlive::new().interval(keep_alive)),
387    )
388        .into_response()
389}
390
391/// The line ending a tail that gave up, saying why.
392fn gave_up(reason: &str) -> String {
393    format!(
394        "\n<span class=\"error\">The log can't be followed any more: {}</span>\n",
395        ansi::to_html(reason)
396    )
397}
398
399/// The log tail's query: which try, where its log continues, and how it was shown.
400#[derive(Debug, Clone, Deserialize)]
401pub struct TailQuery {
402    /// The try.
403    #[serde(rename = "try")]
404    pub try_number: u32,
405    /// The first byte not shown yet.
406    pub from: u64,
407    /// The instance of a mapped task.
408    #[serde(default)]
409    pub map_index: Option<u32>,
410    /// The colours in force where the log continues (`ansi::Converter::sgr`).
411    #[serde(default)]
412    pub style: String,
413    /// Since when the log has been out of reach, in milliseconds since the epoch.
414    #[serde(default)]
415    pub out: Option<i64>,
416}
417
418/// `GET /d/<deployment>/runs/<run>/tasks/<task>/tail?try=&from=` (decision 175: polled, so
419/// it holds no connection): the log from `from` as HTML, the colours carried from the part
420/// before (`style`), followed by the element reading the next part (in [`TAIL_INTERVAL`], at
421/// once when more is waiting), which replaces itself with the answer. Nothing follows once the
422/// attempt has ended and all of it is shown, or once the log can't be read (said where it is
423/// shown): gone, or out of reach for [`TAIL_GIVE_UP`].
424pub async fn tail<T: Transport + Send + Sync + 'static>(
425    State(ui): State<Arc<Ui<T>>>,
426    Path((deployment, run_id, task_id)): Path<(String, String, String)>,
427    query: Result<Query<TailQuery>, QueryRejection>,
428    uri: OriginalUri,
429    headers: HeaderMap,
430) -> Response {
431    let Ok(Query(query)) = query else {
432        return StatusCode::BAD_REQUEST.into_response();
433    };
434    let Some(deployment) = ui.deployments.iter().find(|d| d.name == deployment) else {
435        return StatusCode::NOT_FOUND.into_response();
436    };
437    let part = deployment
438        .client
439        .instance_log_part(
440            &run_id,
441            (&task_id, query.map_index),
442            query.try_number,
443            query.from,
444            TAIL_PART,
445        )
446        .await;
447    let mut colours = ansi::Converter::resume(&query.style);
448    let (html, next) = match part {
449        Ok(part) => {
450            let html = colours.push(&part.content);
451            // Bytes of an escape sequence cut at the part's end: read again with the rest.
452            let from = part
453                .next
454                .saturating_sub(colours.held() as u64)
455                .max(query.from);
456            let done = !part.running && part.next >= part.size;
457            // Most of a part read (whole lines only: rarely all of it), and more past it:
458            // read on at once.
459            let now =
460                part.next.saturating_sub(query.from) >= TAIL_PART / 2 && part.next < part.size;
461            (html, (!done).then_some((from, None, now)))
462        }
463        // Gone for good: the attempt has no such log (any more), or the request is wrong.
464        Err(ClientError::Server { status, message }) if status != 503 => (gave_up(&message), None),
465        // Out of reach (the worker, or the webserver): tried again for a while.
466        Err(error) => {
467            let out = query.out.unwrap_or_else(now_millis);
468            let given = i64::try_from(ui.timings.tail_give_up.as_millis()).unwrap_or(i64::MAX);
469            if now_millis().saturating_sub(out) >= given {
470                (gave_up(&error.to_string()), None)
471            } else {
472                (String::new(), Some((query.from, Some(out), false)))
473            }
474        }
475    };
476    let mut body = html;
477    if let Some((from, out, now)) = next {
478        let mut url = format!(
479            "{}{}?try={}&from={from}",
480            prefix(&headers),
481            uri.path(),
482            query.try_number
483        );
484        if let Some(index) = query.map_index {
485            let _ = write!(url, "&map_index={index}");
486        }
487        let style = colours.sgr();
488        if !style.is_empty() {
489            let _ = write!(url, "&style={}", style.replace(';', "%3B"));
490        }
491        if let Some(out) = out {
492            let _ = write!(url, "&out={out}");
493        }
494        body.push_str(&tail_reader(&url, now, ui.timings.tail_interval));
495    }
496    (
497        [
498            (header::CONTENT_TYPE, "text/html; charset=utf-8"),
499            (header::CACHE_CONTROL, "no-store"),
500        ],
501        body,
502    )
503        .into_response()
504}
505
506/// The element reading a log's next part from `url` (with the prefix): in [`TAIL_INTERVAL`],
507/// or at once; again a second after the UI didn't answer (`retry`, sent by the page).
508#[must_use]
509pub fn tail_reader(url: &str, now: bool, interval: Duration) -> String {
510    let wait = if now { 0 } else { interval.as_millis() };
511    format!(
512        "<span class=\"log-tail\" hx-get=\"{}\" hx-trigger=\"load delay:{wait}ms, retry delay:1s\" \
513         hx-target=\"this\" hx-swap=\"outerHTML\" hx-disinherit=\"*\"></span>",
514        url.replace('&', "&amp;").replace('"', "&quot;")
515    )
516}