1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct UiTimings {
42 pub keep_alive: Duration,
44 pub coalesce: Duration,
46 pub tail_interval: Duration,
48 pub tail_give_up: Duration,
50 pub slow_read: Duration,
52 pub slow_read_wait: Duration,
54 pub retry_first: Duration,
56 pub retry_max: Duration,
58 pub backlog: usize,
61}
62
63impl Default for UiTimings {
64 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
80pub const KEEP_ALIVE: Duration = Duration::from_secs(15);
82
83pub const SLOW_READ: Duration = Duration::from_millis(50);
87
88pub const SLOW_READ_WAIT: Duration = Duration::from_secs(5);
90
91pub const COALESCE: Duration = Duration::from_secs(1);
93
94pub const TAIL_INTERVAL: Duration = Duration::from_secs(1);
96
97pub const TAIL_GIVE_UP: Duration = Duration::from_secs(30);
99
100const TAIL_PART: u64 = schedr_model::logs::MAX_CHUNK;
103
104const RETRY_FIRST: Duration = Duration::from_secs(1);
106
107const RETRY_MAX: Duration = Duration::from_secs(30);
109
110const BACKLOG: usize = 1_024;
112
113#[derive(Debug, Clone, PartialEq, Eq)]
115pub enum Change {
116 Run {
118 run_id: String,
120 dag_id: String,
122 },
123 Dag {
125 dag_id: String,
127 },
128 Workers,
130 Refresh,
132}
133
134impl Change {
135 #[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#[derive(Debug)]
158pub struct Relays {
159 senders: Vec<OnceLock<broadcast::Sender<Change>>>,
160 changed: Vec<Arc<AtomicI64>>,
163}
164
165impl Relays {
166 #[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 fn changed_after(&self, index: usize, since: i64) -> bool {
180 self.changed[index].load(Ordering::Relaxed) > since
181 }
182
183 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
201async 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 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#[derive(Debug, Clone, Default, Deserialize)]
244pub struct Follow {
245 #[serde(default)]
249 pub since: Option<i64>,
250}
251
252impl Change {
253 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
273pub 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 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
307async 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 let mut sent: Vec<(Change, tokio::time::Instant)> = Vec::new();
318 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 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
376fn now_millis() -> i64 {
378 jiff::Timestamp::now().as_millisecond()
379}
380
381fn 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
391fn 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#[derive(Debug, Clone, Deserialize)]
401pub struct TailQuery {
402 #[serde(rename = "try")]
404 pub try_number: u32,
405 pub from: u64,
407 #[serde(default)]
409 pub map_index: Option<u32>,
410 #[serde(default)]
412 pub style: String,
413 #[serde(default)]
415 pub out: Option<i64>,
416}
417
418pub 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 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 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 Err(ClientError::Server { status, message }) if status != 503 => (gave_up(&message), None),
465 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#[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('&', "&").replace('"', """)
515 )
516}