diff --git a/docs/architecture.md b/docs/architecture.md index 472de83..5e1ca7c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -103,6 +103,13 @@ a time: the build, then a copy, comparison and activation for each node, or the answer. The broker's own copies read Nix's log with `exec::run_nix`. - `Reporter` sends a phase's progress to the requester when it starts, at most once a second while it runs, and when it ends. +- `runs::Runs` keeps the latest progress of each phase of requests that build, from the build on; + `exec::Output` records each `Progress` message it carries for a tracked request. The web app reads + it, and the request's `finished` or `failed` audit event keeps its phases. +- The web app shows a request's progress (`templates/progress.html`) in its page's region, and + the running requests (`templates/running.html`) in a region of the main page, both kept current + by the page's event stream (`web/events.rs`). The bars are `` elements, since the + content security policy allows no inline styles. - `slop` shows it with `terminal::Board`. On a terminal, `indicatif` draws a bar for each running phase below other output; the bars hide while other output is mid-line, which they would overwrite. Otherwise (for agents) a running phase gets a plain line every 30 seconds, and one @@ -159,6 +166,7 @@ What each request runs, and whose code, decides whether it needs an approval fir | `src/builder.rs` | Both sides of the builder: the worker (forced command) and the broker's client; also reads secrets and deploy nodes on the main branch | | `src/approve.rs` | Approver connections (many requests each), `slop-approve` client, `approve()` used by every approver | | `src/remote.rs` | SSH transport: the `slop-broker remote` forced command, the remote socket, `connect` for both clients, and `address` (environment, then `~/.config/slop/config.toml`, then the default) | +| `src/runs.rs` | Requests that build, copy or activate, with their phases' latest progress, while they run | | `src/audit.rs` | Typed audit events: a text line to the journal, a JSON line to the file; `tail` for `slop-approve log` | | `src/bin/slop-broker.rs` | Daemon (`serve`); `slop-approve` when run under that name | | `src/bin/slop.rs` | Agent client; `slop guide` prints `slop-tools.md` | diff --git a/docs/design.md b/docs/design.md index fcae7dc..236beb6 100644 --- a/docs/design.md +++ b/docs/design.md @@ -227,6 +227,15 @@ on a desktop shows what `slop-approve` can only print. leases, and updates itself. - A dismissed or missed notification costs nothing; a notification only points at its request. - Requests that need a passkey are marked, with a padlock on their approve buttons. +- **Progress.** Builds and deploys show how they're going while they run, to approvers as well + as in `slop`. + - A running request's page has a bar for the build (derivations built, paths fetched, what's + building now) and a row for each node: copying, comparing, ready, activating, done or + failed, with its copy's bar and how long it's taken. + - The main page lists running requests with one bar each. + - Without JavaScript, a reload shows the latest. + - Once a request finishes, its page and the audit log keep how each phase ended, such as + `built: 12 derivations in 4m 10s`. - **Audit log.** The log page groups the audit file by request: who asked, what, the outcome and who approved it. - Filters by requester, operation and outcome, and a search. @@ -237,8 +246,9 @@ on a desktop shows what `slop-approve` can only print. them. - **Live updates.** Each open page follows one stream of Server-Sent Events (`/events`). - Each event carries a region of the page as HTML: a whole element with its `id`, such as the - pending list or a request, rendered by the same templates as the page. Agent-supplied text - is only ever escaped by them, never in the browser. + pending list, the running requests or a request with its progress, rendered by the same + templates as the page. Agent-supplied text is only ever escaped by them, never in the + browser. - The script morphs each region into the page with [idiomorph](https://github.com/bigskysoftware/idiomorph) (vendored), so open details, the focus and what's being typed stay. diff --git a/src/audit.rs b/src/audit.rs index 7d37c4c..009372c 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -11,6 +11,7 @@ use anyhow::Result; use serde::{Deserialize, Serialize}; use crate::detail::{Detail, Section}; +use crate::progress::Progress; use crate::proto::ApprovedBy; /// One line of the audit file. @@ -87,10 +88,15 @@ pub enum Event { id: String, exit: i32, seconds: f64, + /// How each phase of a build or deploy ended. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + phases: Vec, }, Failed { id: String, error: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + phases: Vec, }, } @@ -185,14 +191,26 @@ impl fmt::Display for Event { Event::Detached { id } => { write!(f, "{} the requester disconnected; waiting for it to finish anyway", short(id)) } - Event::Finished { id, exit, seconds } => { - write!(f, "{} finished with exit status {exit} after {seconds:.1}s", short(id)) + Event::Finished { id, exit, seconds, phases } => { + write!(f, "{} finished with exit status {exit} after {seconds:.1}s", short(id))?; + phase_lines(f, phases) + } + Event::Failed { id, error, phases } => { + write!(f, "{} failed: {error}", short(id))?; + phase_lines(f, phases) } - Event::Failed { id, error } => write!(f, "{} failed: {error}", short(id)), } } } +/// Phases as `; built: 12 derivations in 4m 10s; …`. +fn phase_lines(f: &mut fmt::Formatter, phases: &[Progress]) -> fmt::Result { + for phase in phases { + write!(f, "; {}", phase.line())?; + } + Ok(()) +} + impl Record { /// For reviewing: the journal's line, with the time and the rest of a request's detail. pub fn describe(&self) -> String { @@ -265,11 +283,14 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let audit = Audit::new(Some(&directory.path().join("audit.jsonl"))).unwrap(); for exit in 0..5 { - audit.log(Event::Finished { id: "0123456789abcdef".into(), exit, seconds: 1.5 }); + audit.log(Event::Finished { id: "0123456789abcdef".into(), exit, seconds: 1.5, phases: vec![] }); } let records = audit.tail(2).unwrap(); assert_eq!(records.len(), 2); - assert_eq!(records[1].event, Event::Finished { id: "0123456789abcdef".into(), exit: 4, seconds: 1.5 }); + assert_eq!( + records[1].event, + Event::Finished { id: "0123456789abcdef".into(), exit: 4, seconds: 1.5, phases: vec![] } + ); assert!(records[1].describe().ends_with("012345 finished with exit status 4 after 1.5s\n")); } diff --git a/src/exec.rs b/src/exec.rs index 8be5582..c23ed5a 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -1,6 +1,7 @@ //! Runs processes for approved requests, wired to the requester's stdout and stderr (carried as //! messages). use std::process::{ExitStatus, Stdio}; +use std::sync::Arc; use std::time::Duration; use anyhow::{Context, Result, bail}; @@ -14,14 +15,31 @@ use tokio_util::sync::CancellationToken; use crate::progress::{NixLog, Reporter}; use crate::proto::ServerMessage; +use crate::runs::Runs; -/// Messages on their way back to the requester. +/// Messages on their way back to the requester. Progress also goes to the request's run, if +/// it's tracked. #[derive(Clone)] -pub struct Output(pub mpsc::Sender); +pub struct Output { + tx: mpsc::Sender, + run: Option<(Arc, String)>, +} impl Output { + pub fn new(tx: mpsc::Sender) -> Output { + Output { tx, run: None } + } + + /// The same output, with progress recorded in `runs` for request `id`. + pub fn tracking(&self, runs: Arc, id: &str) -> Output { + Output { tx: self.tx.clone(), run: Some((runs, id.to_owned())) } + } + pub async fn send(&self, message: ServerMessage) { - let _ = self.0.send(message).await; + if let (ServerMessage::Progress(progress), Some((runs, id))) = (&message, &self.run) { + runs.record(id, progress); + } + let _ = self.tx.send(message).await; } pub async fn info(&self, message: impl Into) { diff --git a/src/lib.rs b/src/lib.rs index ee6706f..34ea1a1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,7 @@ pub mod progress; pub mod proto; pub mod queue; pub mod remote; +pub mod runs; pub mod server; pub mod targets; pub mod terminal; diff --git a/src/progress.rs b/src/progress.rs index 0036f43..384eb07 100644 --- a/src/progress.rs +++ b/src/progress.rs @@ -123,8 +123,18 @@ impl Progress { } } - /// The counts in words, like `37/120 derivations, 10/40 paths (1.2/3.4 GiB)`. - fn counted(&self, finished: bool) -> String { + /// What it's doing or did, like `copying to river` or `building failed`. + pub fn title(&self) -> String { + match self.state { + State::Running => self.phase.doing(), + State::Done => self.phase.done(), + State::Failed => format!("{} failed", self.phase.doing()), + } + } + + /// The counts in words, like `37/120 derivations, 10/40 paths (1.2/3.4 GiB)`, or only what + /// was done once it's `finished`. + pub fn counted(&self, finished: bool) -> String { let counts = &self.counts; let count = |c: Count| if finished { c.done.to_string() } else { format!("{}/{}", c.done, c.total) }; let fetched = if self.phase == Phase::Build { "fetched" } else { "" }; @@ -166,11 +176,8 @@ impl Progress { format!("{line}, {}", elapsed(self.elapsed)) } State::Done | State::Failed => { - let counted = self.counted(true); - let mut line = match self.state { - State::Done => self.phase.done(), - _ => format!("{} failed", self.phase.doing()), - }; + let counted = self.counted(self.state == State::Done); + let mut line = self.title(); if !counted.is_empty() { line = format!("{line}: {counted}"); } diff --git a/src/runs.rs b/src/runs.rs new file mode 100644 index 0000000..830d09f --- /dev/null +++ b/src/runs.rs @@ -0,0 +1,229 @@ +//! Requests that build, copy or activate, with each phase's latest progress, while they run. +//! The web app shows them, and their final phases go in the audit log. +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +use tokio::sync::watch; + +use crate::progress::{Count, Phase, Progress, State}; + +pub struct Runs { + runs: Mutex>, + /// Bumped on every change, progress included. + changed: watch::Sender, + /// Bumped when a run starts or ends. + members: watch::Sender, +} + +#[derive(Debug, Clone)] +pub struct Run { + pub id: String, + pub requester: String, + pub op: String, + pub summary: String, + started: Instant, + /// The latest progress of each phase, in the order they started. + pub phases: Vec, +} + +/// How a node is getting on, from its phases. +#[derive(Debug, Clone, PartialEq)] +pub struct NodeRow { + pub node: String, + pub state: &'static str, + /// For styling: `active`, `good`, `bad` or `neutral`. + pub tone: &'static str, + /// Its copy, for a bar. + pub copy: Option, + /// Its phase now, or its last. + pub latest: Progress, +} + +impl Run { + pub fn elapsed(&self) -> u64 { + self.started.elapsed().as_secs() + } + + /// Phases that aren't about one node: the build and the push. + pub fn overall(&self) -> Vec<&Progress> { + self.phases.iter().filter(|p| p.phase.node().is_none()).collect() + } + + /// The nodes, in the order their first phase started. + pub fn nodes(&self) -> Vec { + let mut order: Vec<&str> = Vec::new(); + for node in self.phases.iter().filter_map(|p| p.phase.node()) { + if !order.contains(&node) { + order.push(node); + } + } + + order + .into_iter() + .map(|node| { + let phases: Vec<&Progress> = self.phases.iter().filter(|p| p.phase.node() == Some(node)).collect(); + let latest = (*phases.last().unwrap()).clone(); + let copy = phases.iter().find(|p| matches!(p.phase, Phase::Copy(_))).map(|p| (*p).clone()); + let (state, tone) = match (&latest.phase, latest.state) { + (_, State::Failed) => ("failed", "bad"), + (Phase::Copy(_), State::Running) => ("copying", "active"), + (Phase::Copy(_), State::Done) => ("copied", "neutral"), + (Phase::Compare(_), State::Running) => ("comparing", "active"), + (Phase::Compare(_), State::Done) => ("ready", "neutral"), + (Phase::Activate(_), State::Running) => ("activating", "active"), + (Phase::Activate(_), State::Done) => ("done", "good"), + _ => ("", "neutral"), + }; + NodeRow { node: node.to_owned(), state, tone, copy, latest } + }) + .collect() + } + + /// One bar for the whole request, for lists: the build, then the share of nodes past each + /// step. + pub fn bar(&self) -> Option { + let nodes = self.nodes(); + if nodes.is_empty() { + return self.overall().last().and_then(|p| p.bar()); + } + + let steps = |row: &NodeRow| match (&row.latest.phase, row.latest.state) { + (_, State::Failed) => 3, + (Phase::Copy(_), State::Running) => 0, + (Phase::Copy(_), _) | (Phase::Compare(_), State::Running) => 1, + (Phase::Compare(_), _) | (Phase::Activate(_), State::Running) => 2, + _ => 3, + }; + let total = nodes.len() as u64 * 3; + Some(Count { done: nodes.iter().map(steps).sum(), total }) + } + + /// What it's doing now, in a line. + pub fn status(&self) -> String { + match self.phases.iter().rev().find(|p| p.state == State::Running).or(self.phases.last()) { + Some(progress) => progress.line(), + None => "starting".into(), + } + } +} + +impl Default for Runs { + fn default() -> Runs { + Runs { runs: Mutex::default(), changed: watch::Sender::new(0), members: watch::Sender::new(0) } + } +} + +impl Runs { + /// Tracks a request until the guard is dropped. + pub fn start(self: &Arc, id: &str, requester: &str, op: &str, summary: &str) -> Tracked { + let run = Run { + id: id.into(), + requester: requester.into(), + op: op.into(), + summary: summary.into(), + started: Instant::now(), + phases: Vec::new(), + }; + self.runs.lock().unwrap().insert(id.into(), run); + self.bump(true); + Tracked { runs: self.clone(), id: id.into() } + } + + pub fn record(&self, id: &str, progress: &Progress) { + { + let mut runs = self.runs.lock().unwrap(); + let Some(run) = runs.get_mut(id) else { return }; + match run.phases.iter_mut().find(|p| p.phase == progress.phase) { + Some(phase) => *phase = progress.clone(), + None => run.phases.push(progress.clone()), + } + } + self.bump(false); + } + + /// A run's phases so far, for the audit log. + pub fn phases(&self, id: &str) -> Vec { + self.runs.lock().unwrap().get(id).map(|r| r.phases.clone()).unwrap_or_default() + } + + pub fn get(&self, id: &str) -> Option { + self.runs.lock().unwrap().get(id).cloned() + } + + /// Every run, the oldest first. + pub fn list(&self) -> Vec { + let mut runs: Vec = self.runs.lock().unwrap().values().cloned().collect(); + runs.sort_by_key(|r| r.started); + runs + } + + /// Changes on every update. + pub fn subscribe(&self) -> watch::Receiver { + self.changed.subscribe() + } + + /// Changes when a run starts or ends. + pub fn members(&self) -> u64 { + *self.members.borrow() + } + + fn bump(&self, members: bool) { + self.changed.send_modify(|v| *v += 1); + if members { + self.members.send_modify(|v| *v += 1); + } + } +} + +/// A run in [`Runs`], until it's dropped. +pub struct Tracked { + runs: Arc, + id: String, +} + +impl Drop for Tracked { + fn drop(&mut self) { + self.runs.runs.lock().unwrap().remove(&self.id); + self.runs.bump(true); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::progress::Counts; + + fn progress(phase: Phase, state: State) -> Progress { + Progress { phase, state, elapsed: 1, counts: Counts::default() } + } + + #[test] + fn follows_nodes_through_their_phases() { + let runs = Arc::new(Runs::default()); + let tracked = runs.start("a", "agent", "deploy", "deploy river, stream"); + let members = runs.members(); + + runs.record("a", &progress(Phase::Build, State::Done)); + runs.record("a", &progress(Phase::Copy("river".into()), State::Done)); + runs.record("a", &progress(Phase::Compare("river".into()), State::Running)); + runs.record("a", &progress(Phase::Copy("stream".into()), State::Running)); + runs.record("nope", &progress(Phase::Build, State::Running)); + assert_eq!(runs.members(), members); + + let run = runs.get("a").unwrap(); + assert_eq!(run.overall().len(), 1); + let nodes = run.nodes(); + assert_eq!( + nodes.iter().map(|n| (n.node.as_str(), n.state)).collect::>(), + [("river", "comparing"), ("stream", "copying")] + ); + assert!(nodes[0].copy.is_some()); + assert_eq!(run.bar(), Some(Count { done: 1, total: 6 })); + assert_eq!(run.status(), "copying to stream, 1s"); + + drop(tracked); + assert!(runs.get("a").is_none() && runs.phases("a").is_empty()); + assert_ne!(runs.members(), members); + } +} diff --git a/src/server.rs b/src/server.rs index b05c04d..c0ec48c 100644 --- a/src/server.rs +++ b/src/server.rs @@ -21,6 +21,7 @@ use crate::ops; use crate::policy::{self, Action}; use crate::proto::{ApprovedBy, ClientMessage, PROTOCOL_VERSION, Request, ServerMessage, decode, encode, transport}; use crate::queue::{NewRequest, Outcome, Queue, new_id}; +use crate::runs::Runs; use crate::targets::Targets; /// The most stdin a requester may send. Operations that read it have their own, smaller limits; @@ -32,6 +33,7 @@ pub struct Broker { pub queue: Queue, pub audit: Audit, pub targets: Targets, + pub runs: Arc, } impl Broker { @@ -40,7 +42,7 @@ impl Broker { let queue = Queue::new(Duration::from_secs(config.timeout), config.max_pending); let audit = Audit::new(config.audit_log.as_deref())?; let targets = Targets::new(&config); - Ok(Broker { config, queue, audit, targets }) + Ok(Broker { config, queue, audit, targets, runs: Arc::default() }) } } @@ -113,7 +115,7 @@ pub async fn handle(broker: Arc { - log(Event::Finished { id, exit: outcome.exit, seconds: start.elapsed().as_secs_f64() }); + let (seconds, phases) = (start.elapsed().as_secs_f64(), broker.runs.phases(&id)); + log(Event::Finished { id, exit: outcome.exit, seconds, phases }); Some(ServerMessage::Finished { exit: outcome.exit, result: outcome.result }) } Err(error) => { let error = format!("{error:#}"); - log(Event::Failed { id, error: error.clone() }); + let phases = broker.runs.phases(&id); + log(Event::Failed { id, error: error.clone(), phases }); Some(ServerMessage::Error(error)) } } diff --git a/src/targets.rs b/src/targets.rs index 43289cf..211b631 100644 --- a/src/targets.rs +++ b/src/targets.rs @@ -63,7 +63,7 @@ impl Targets { } // Nobody sees the builder's progress: this is the broker's own business. - let out = Output(mpsc::channel(1).0); + let out = Output::new(mpsc::channel(1).0); let result = crate::builder::nodes(ssh, deploy, &out, &CancellationToken::new()).await; *looked = Some((Instant::now(), result.is_ok())); match result { diff --git a/src/web/assets/style.css b/src/web/assets/style.css index 946f19a..305e1b0 100644 --- a/src/web/assets/style.css +++ b/src/web/assets/style.css @@ -474,3 +474,120 @@ table.log .label { color: var(--muted); font-size: 0.85rem; } + +/* Progress of running requests: native bars, coloured by state. */ +progress { + appearance: none; + width: 100%; + max-width: 24rem; + height: 10px; + border: none; + border-radius: 5px; + background: var(--code-bg); + vertical-align: middle; + overflow: hidden; +} + +progress::-webkit-progress-bar { + background: var(--code-bg); + border-radius: 5px; +} + +progress::-webkit-progress-value { + background: var(--active); + border-radius: 5px; +} + +progress::-moz-progress-bar { + background: var(--active); + border-radius: 5px; +} + +progress.good::-webkit-progress-value { + background: var(--good); +} + +progress.good::-moz-progress-bar { + background: var(--good); +} + +progress.bad::-webkit-progress-value { + background: var(--bad); +} + +progress.bad::-moz-progress-bar { + background: var(--bad); +} + +section.progress { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 8px; + padding: 12px 14px; + margin-bottom: 14px; +} + +.phase { + margin: 10px 0; +} + +.phase-title { + margin: 0 0 4px; +} + +/* A phase's bar spans its section, like a running request's in the list. */ +.phase progress { + display: block; + max-width: none; +} + +.phase .current code { + overflow-wrap: anywhere; +} + +table.nodes { + width: 100%; + margin-top: 8px; +} + +table.nodes td { + vertical-align: middle; +} + +/* The copy column takes the table's spare width, its counts under the bar. */ +table.nodes progress { + display: block; + min-width: 8rem; + max-width: none; +} + +table.nodes td.copy { + width: 100%; +} + +#running h2 { + margin-top: 20px; +} + +ul.runs { + list-style: none; + padding: 0; +} + +ul.runs li { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 8px; + padding: 8px 12px; + margin-bottom: 8px; +} + +ul.runs progress { + display: block; + max-width: none; + margin: 6px 0 2px; +} + +ul.phases li.bad { + color: var(--bad); +} diff --git a/src/web/events.rs b/src/web/events.rs index 3c27590..ff2ff17 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -2,10 +2,12 @@ //! //! - Each `morph` event carries a region of the page: a whole element with its `id`, which the //! page script morphs into the one it has, so open details and the focus stay. The main page's -//! region is the pending list (`#pending`), and a request's page's is the request (`#request`). +//! regions are the pending list (`#pending`) and the running requests (`#running`), and a +//! request's page's is the request (`#request`), with its progress while it runs. //! - A region comes when the stream starts, so a page catches up after reconnecting, and then //! whenever it changes. //! - `signed-out` ends the stream, when the approver signs out or the session expires. +use std::collections::HashMap; use std::convert::Infallible; use std::future::Future; use std::pin::Pin; @@ -14,9 +16,11 @@ use std::time::{Duration, Instant}; use axum::response::sse::{Event, KeepAlive, Sse}; use axum::response::{IntoResponse, Response}; +use futures_util::StreamExt; use tokio::sync::watch; use tower_sessions::Session; +use super::history::History; use super::{User, page}; use crate::server::Broker; @@ -34,9 +38,11 @@ pub fn stream(broker: Arc, session: Session, request: Option) -> let updates = Updates::new(broker, signed_in, request); let events = futures_util::stream::unfold(updates, |mut updates| async move { - let (name, data) = updates.next().await?; - Some((Ok::<_, Infallible>(Event::default().event(name).data(data)), updates)) - }); + let events = updates.next().await?; + Some((futures_util::stream::iter(events), updates)) + }) + .flatten() + .map(|(name, data)| Ok::<_, Infallible>(Event::default().event(name).data(data))); let mut response = Sse::new(events).keep_alive(KeepAlive::default()).into_response(); // Proxies such as nginx would otherwise hold events back. @@ -50,57 +56,96 @@ struct Updates { /// The request whose page it is, or none for the main page. request: Option, queue: watch::Receiver, - /// The region last sent. - sent: Option, + runs: watch::Receiver, + /// What the audit log has of the request, read again when the queue changes or a run starts + /// or ends, rather than with every bit of progress. + past: Option, + members: Option, + /// Each region last sent, by `id`. + sent: HashMap<&'static str, String>, last: Option, ended: bool, } impl Updates { fn new(broker: Arc, signed_in: SignedIn, request: Option) -> Updates { - let queue = broker.queue.subscribe(); - Updates { broker, signed_in, request, queue, sent: None, last: None, ended: false } + let (queue, runs) = (broker.queue.subscribe(), broker.runs.subscribe()); + Updates { + broker, + signed_in, + request, + queue, + runs, + past: None, + members: None, + sent: HashMap::new(), + last: None, + ended: false, + } } - /// The next event, as a name and data, once something changes; `None` ends the stream. - async fn next(&mut self) -> Option<(&'static str, String)> { + /// The next events, as names and data, once something changes; `None` ends the stream. + async fn next(&mut self) -> Option> { if self.ended { return None; } loop { - // The region at first, then when it changes, at most once an interval + // The regions at first, then the ones that change, at most once an interval + let mut queue_changed = self.last.is_none(); if let Some(last) = self.last { - self.queue.changed().await.ok()?; + queue_changed = tokio::select! { + changed = self.queue.changed() => changed.map(|()| true).ok()?, + changed = self.runs.changed() => changed.map(|()| false).ok()?, + }; tokio::time::sleep(INTERVAL.saturating_sub(last.elapsed())).await; } self.last = Some(Instant::now()); + queue_changed |= self.queue.has_changed().unwrap_or(false); self.queue.borrow_and_update(); + self.runs.borrow_and_update(); // Signing out, or the session expiring, ends it. let Some(csrf) = (self.signed_in)().await else { self.ended = true; - return Some(("signed-out", "signed out".into())); + return Some(vec![("signed-out", "signed out".into())]); }; - let region = self.region(&csrf); - if self.sent.as_ref() != Some(®ion) { - self.sent = Some(region.clone()); - return Some(("morph", region)); + let events: Vec<_> = self + .regions(&csrf, queue_changed) + .into_iter() + .filter(|(id, region)| self.sent.get(id) != Some(region)) + .collect(); + for (id, region) in &events { + self.sent.insert(id, region.clone()); + } + if !events.is_empty() { + return Some(events.into_iter().map(|(_, region)| ("morph", region)).collect()); } } } - fn region(&self, csrf: &str) -> String { - match &self.request { - None => page::pending(csrf, &self.broker.queue.list(), &self.broker.queue.all_leases()), - Some(id) => { - let entry = self.broker.queue.list().into_iter().find(|e| &e.id == id); - let past = super::past(&self.broker, id); - let view = page::RequestView { id, entry: entry.as_ref(), past: past.as_ref() }; - page::request_region(csrf, &view) + /// The page's regions now, by `id`. + fn regions(&mut self, csrf: &str, queue_changed: bool) -> Vec<(&'static str, String)> { + let queue = &self.broker.queue; + let Some(id) = self.request.clone() else { + let mut regions = Vec::new(); + if queue_changed { + regions.push(("pending", page::pending(csrf, &queue.list(), &queue.all_leases()))); } + regions.push(("running", page::running_list(&self.broker.runs.list()))); + return regions; + }; + + let members = self.broker.runs.members(); + if queue_changed || self.members != Some(members) { + self.members = Some(members); + self.past = super::past(&self.broker, &id); } + let entry = queue.list().into_iter().find(|e| e.id == id); + let run = self.broker.runs.get(&id); + let view = page::RequestView { id: &id, entry: entry.as_ref(), run: run.as_ref(), past: self.past.as_ref() }; + vec![("request", page::request_region(csrf, &view))] } } @@ -110,6 +155,7 @@ mod tests { use super::*; use crate::detail::Detail; + use crate::progress::{Counts, Phase, Progress, State}; use crate::queue::NewRequest; fn broker() -> Arc { @@ -138,8 +184,12 @@ mod tests { broker.queue.submit(id, request, 4).unwrap() } + fn names(events: &[(&'static str, String)]) -> Vec<&'static str> { + events.iter().map(|(name, _)| *name).collect() + } + #[tokio::test] - async fn the_main_page_gets_its_list_as_it_changes() { + async fn the_main_page_gets_its_regions_as_they_change() { let broker = broker(); let signed_out = Arc::new(AtomicBool::new(false)); let check = signed_out.clone(); @@ -149,39 +199,59 @@ mod tests { }); let mut updates = Updates::new(broker.clone(), signed_in, None); - // The list to start with, as a whole element - let (name, data) = updates.next().await.unwrap(); - assert_eq!(name, "morph"); - assert!(data.starts_with(r#"
"#) && data.contains("Nothing is waiting"), "{data}"); + // Both regions to start with, as whole elements + let events = updates.next().await.unwrap(); + assert_eq!(names(&events), ["morph", "morph"]); + assert!(events[0].1.starts_with(r#"
"#) && events[0].1.contains("Nothing is waiting")); + assert!(events[1].1.starts_with(r#"
"#), "{events:?}"); - // A new request, then its leaving + // A new request changes only the pending list, and its leaving too let _reply = submit(&broker, "abc"); - let (_, data) = updates.next().await.unwrap(); - assert!(data.contains("ssh river"), "{data}"); + let events = updates.next().await.unwrap(); + assert!(events.len() == 1 && events[0].1.contains("ssh river"), "{events:?}"); broker.queue.cancel("abc"); - let (_, data) = updates.next().await.unwrap(); - assert!(data.contains("Nothing is waiting"), "{data}"); + let events = updates.next().await.unwrap(); + assert!(events.len() == 1 && events[0].1.contains("Nothing is waiting"), "{events:?}"); + + // A run starting, its progress and its end change only the running list + let tracked = broker.runs.start("def", "agent", "deploy", "deploy river"); + let events = updates.next().await.unwrap(); + assert!(events.len() == 1 && events[0].1.contains("deploy river"), "{events:?}"); + let progress = Progress { phase: Phase::Build, state: State::Running, elapsed: 1, counts: Counts::default() }; + broker.runs.record("def", &progress); + let events = updates.next().await.unwrap(); + assert!(events.len() == 1 && events[0].1.contains("building"), "{events:?}"); + drop(tracked); + let events = updates.next().await.unwrap(); + assert!(events.len() == 1 && !events[0].1.contains("deploy river"), "{events:?}"); signed_out.store(true, Ordering::SeqCst); - let _reply = submit(&broker, "def"); - assert_eq!(updates.next().await.unwrap().0, "signed-out"); + let _reply = submit(&broker, "ghi"); + assert_eq!(names(&updates.next().await.unwrap()), ["signed-out"]); assert!(updates.next().await.is_none()); } #[tokio::test] - async fn a_request_page_gets_its_request() { + async fn a_request_page_gets_its_request_and_progress() { let broker = broker(); let signed_in: SignedIn = Box::new(|| Box::pin(async { Some("token".to_owned()) })); let mut updates = Updates::new(broker.clone(), signed_in, Some("abc".into())); - let (_, data) = updates.next().await.unwrap(); - assert!(data.starts_with(r#"
"#), "{data}"); - assert!(data.contains("The audit log has nothing"), "{data}"); + let events = updates.next().await.unwrap(); + assert!(events[0].1.starts_with(r#"
"#), "{events:?}"); + assert!(events[0].1.contains("The audit log has nothing"), "{events:?}"); // Other requests change nothing here, so nothing comes until this one does let _other = submit(&broker, "xyz"); let _reply = submit(&broker, "abc"); - let (_, data) = updates.next().await.unwrap(); - assert!(data.contains("

ssh river

"), "{data}"); + let events = updates.next().await.unwrap(); + assert!(events[0].1.contains("

ssh river

"), "{events:?}"); + + // Its run shows while it's waiting too, as for a deploy that's built + let _tracked = broker.runs.start("abc", "agent", "deploy", "deploy river"); + let progress = Progress { phase: Phase::Build, state: State::Done, elapsed: 1, counts: Counts::default() }; + broker.runs.record("abc", &progress); + let events = updates.next().await.unwrap(); + assert!(events[0].1.contains("ssh river") && events[0].1.contains("built"), "{events:?}"); } } diff --git a/src/web/history.rs b/src/web/history.rs index 83a5428..4583b33 100644 --- a/src/web/history.rs +++ b/src/web/history.rs @@ -2,7 +2,8 @@ use std::collections::HashMap; use crate::audit::{Event, Record, Shown}; -use crate::detail::Detail; +use crate::detail::{Detail, Section}; +use crate::progress::Progress; use crate::proto::ApprovedBy; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -70,6 +71,8 @@ pub struct History { pub outcome: Outcome, /// Who approved it (the request itself, not a step before it), with the answer they gave. pub approved_by: Option, + /// How each phase of a build or deploy ended. + pub phases: Vec, pub records: Vec, } @@ -124,6 +127,7 @@ fn summarize(id: String, records: Vec) -> History { label: None, outcome: Outcome::Waiting, approved_by: None, + phases: vec![], records: vec![], }; let mut answer = None; @@ -155,9 +159,14 @@ fn summarize(id: String, records: Vec) -> History { Event::Denied { .. } => history.outcome = Outcome::Denied, Event::Expired { .. } => history.outcome = Outcome::Expired, Event::Disconnected { .. } => history.outcome = Outcome::Cancelled, - Event::Finished { exit: 0, .. } => history.outcome = Outcome::Succeeded, - Event::Finished { exit, .. } => history.outcome = Outcome::ExitedWith(*exit), - Event::Failed { .. } => history.outcome = Outcome::Failed, + Event::Finished { exit, phases, .. } => { + history.outcome = if *exit == 0 { Outcome::Succeeded } else { Outcome::ExitedWith(*exit) }; + history.phases = phases.clone(); + } + Event::Failed { phases, .. } => { + history.outcome = Outcome::Failed; + history.phases = phases.clone(); + } Event::Unknown { .. } | Event::Prepared { .. } | Event::Approved { .. } | Event::Detached { .. } => {} } } @@ -196,13 +205,22 @@ pub fn describe(event: &Event) -> (String, Option) { Event::Expired { .. } => ("Expired without an answer".into(), None), Event::Disconnected { .. } => ("Cancelled: the requester disconnected".into(), None), Event::Detached { .. } => ("The requester disconnected; carried on to the end".into(), None), - Event::Finished { exit, seconds, .. } => { - (format!("Finished with exit status {exit} after {seconds:.1}s"), None) + Event::Finished { exit, seconds, phases, .. } => { + (format!("Finished with exit status {exit} after {seconds:.1}s"), phase_list(phases)) } - Event::Failed { error, .. } => (format!("Failed: {error}"), None), + Event::Failed { error, phases, .. } => (format!("Failed: {error}"), phase_list(phases)), } } +fn phase_list(phases: &[Progress]) -> Option { + if phases.is_empty() { + return None; + } + let mut detail = Detail::new(); + detail.section(Section::list("Phases", phases.iter().map(Progress::line))); + Some(detail) +} + fn shown(detail: &Shown) -> Option { Some(detail.to_detail()).filter(|d| !d.fields.is_empty() || !d.sections.is_empty()) } @@ -251,7 +269,7 @@ mod tests { step: None, }, ), - record("6", Event::Finished { id: "a".into(), exit: 1, seconds: 0.5 }), + record("6", Event::Finished { id: "a".into(), exit: 1, seconds: 0.5, phases: vec![] }), record("7", Event::Expired { id: "b".into() }), record("8", request("c")), record("9", Event::Approved { id: "c".into(), by: ApprovedBy::Lease, approver: None, step: None }), @@ -293,7 +311,7 @@ mod tests { let (histories, _) = gather(records.clone()); assert_eq!(histories[0].outcome, Outcome::Running); - records.push(record("4", Event::Finished { id: "a".into(), exit: 0, seconds: 30.0 })); + records.push(record("4", Event::Finished { id: "a".into(), exit: 0, seconds: 30.0, phases: vec![] })); let (histories, _) = gather(records); assert_eq!(histories[0].outcome, Outcome::Succeeded); } diff --git a/src/web/mod.rs b/src/web/mod.rs index c580c28..1229fe4 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -205,7 +205,7 @@ async fn index(State(web): State>, session: Session) -> Result user, Err(redirect) => return Ok(redirect), }; - let (entry, past) = (pending(&web, &id), past(&web.broker, &id)); - let view = page::RequestView { id: &id, entry: entry.as_ref(), past: past.as_ref() }; + let (entry, run, past) = (pending(&web, &id), web.broker.runs.get(&id), past(&web.broker, &id)); + let view = page::RequestView { id: &id, entry: entry.as_ref(), run: run.as_ref(), past: past.as_ref() }; Ok(page::request(&user.name, &user.csrf, &view).into_response()) } diff --git a/src/web/page.rs b/src/web/page.rs index f0ee27c..8f057c6 100644 --- a/src/web/page.rs +++ b/src/web/page.rs @@ -11,7 +11,9 @@ use super::history::{self, History}; use crate::audit::{Record, short}; use crate::detail::{Column, Detail, Section}; use crate::ops::printable; +use crate::progress::{Progress, State}; use crate::queue::{Decision, PendingInfo}; +use crate::runs::Run; /// The broker's version, which signed-in pages show. pub use crate::VERSION; @@ -70,6 +72,23 @@ fn section_titles(detail: &Detail) -> String { detail.sections.iter().map(Section::title).collect::>().join(", ") } +fn elapsed(seconds: impl std::borrow::Borrow) -> String { + crate::progress::elapsed(*seconds.borrow()) +} + +/// For styling a phase: `active`, `good` or `bad`. +fn state_class(progress: &Progress) -> &'static str { + match progress.state { + State::Running => "active", + State::Done => "good", + State::Failed => "bad", + } +} + +fn running(progress: &Progress) -> bool { + progress.state == State::Running +} + fn describe(record: &Record) -> (String, Option) { history::describe(&record.event) } @@ -105,24 +124,46 @@ struct Index<'a> { csrf: &'a str, entries: &'a [PendingInfo], leases: &'a [(String, String, u64)], + runs: &'a [Run], } -pub fn index(name: &str, csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html { - render(Index { name, csrf, entries, leases }) +pub fn index( + name: &str, + csrf: &str, + entries: &[PendingInfo], + leases: &[(String, String, u64)], + runs: &[Run], +) -> Html { + render(Index { name, csrf, entries, leases, runs }) } -/// What a request's page shows: the request while it waits, and what the audit log has of it. +/// The requests that are running: the main page's other region that the page script keeps +/// current. +#[derive(Template)] +#[template(path = "running.html")] +struct Running<'a> { + runs: &'a [Run], +} + +pub fn running_list(runs: &[Run]) -> String { + render(Running { runs }).0 +} + +/// What a request's page shows: the request while it waits, its progress while it runs, and what +/// the audit log has of it. pub struct RequestView<'a> { pub id: &'a str, pub entry: Option<&'a PendingInfo>, + pub run: Option<&'a Run>, pub past: Option<&'a History>, } impl RequestView<'_> { fn heading(&self) -> String { - match (self.entry, self.past) { - (Some(entry), _) => entry.summary.clone(), - (None, Some(past)) if !past.summary.is_empty() => past.summary.clone(), + match (self.entry, self.run, self.past) { + (Some(entry), _, _) => entry.summary.clone(), + (None, Some(run), _) => run.summary.clone(), + (None, None, Some(past)) if !past.summary.is_empty() => past.summary.clone(), _ => format!("Request {}", short(self.id)), } } @@ -307,7 +348,7 @@ mod tests { ]; let (histories, _) = super::history::gather(records); - let view = RequestView { id: "abc", entry: None, past: Some(&histories[0]) }; + let view = RequestView { id: "abc", entry: None, run: None, past: Some(&histories[0]) }; let html = request("broker", "token", &view).0; assert!(html.contains(r#"
"#), "{html}"); assert!(html.contains(request_region("token", &view).trim()), "{html}"); @@ -316,4 +357,39 @@ mod tests { assert!(html.contains("Details (Text)") && html.contains("
Old: text
"), "{html}"); assert!(html.contains(&format!("slop-broker {VERSION}")), "{html}"); } + + #[test] + fn shows_progress_of_running_requests() { + use crate::progress::{Count, Counts, Phase}; + use crate::runs::Runs; + + let runs = std::sync::Arc::new(Runs::default()); + let _tracked = runs.start("abc", "slop-cannon", "deploy", "deploy "); + let progress = |phase, state, counts| Progress { phase, state, elapsed: 70, counts }; + let building = Counts { + builds: Some(Count { done: 3, total: 8 }), + current: vec!["hello-2.12".into()], + ..Counts::default() + }; + runs.record("abc", &progress(Phase::Build, State::Running, building)); + let copied = Counts { paths: Some(Count { done: 2, total: 2 }), ..Counts::default() }; + runs.record("abc", &progress(Phase::Copy("river".into()), State::Done, copied)); + let run = runs.get("abc").unwrap(); + + // The request's page, with its heading from the run + let view = RequestView { id: "abc", entry: None, run: Some(&run), past: None }; + let html = request_region("token", &view); + assert!(html.contains("

deploy <river>

"), "{html}"); + assert!(html.contains(r#""#), "{html}"); + assert!(html.contains("building 1m 10s"), "{html}"); + assert!(html.contains("Now: hello-2.12"), "{html}"); + assert!(html.contains(r#"copied"#), "{html}"); + assert!(html.contains(r#""#), "{html}"); + + // The main page's list, which is there even when nothing runs + let list = running_list(&runs.list()); + assert!(list.contains("deploy <river>") && list.contains(""#) && !empty.contains("Running"), "{empty}"); + } } diff --git a/templates/index.html b/templates/index.html index 2758630..d2d543f 100644 --- a/templates/index.html +++ b/templates/index.html @@ -6,4 +6,5 @@

{% include "pending.html" %} +{% include "running.html" %} {% endblock %} diff --git a/templates/macros.html b/templates/macros.html index 382ad97..92f2936 100644 --- a/templates/macros.html +++ b/templates/macros.html @@ -90,3 +90,23 @@ {%- for (value, text) in options %}{% endfor -%} {%- endmacro %} + +{# A bar for a phase: its count if it has one, otherwise just whether it's going. #} +{% macro meter(progress) -%} +{% if let Some(count) = progress.bar() -%} + +{%- else if self::running(progress) -%} + +{%- else -%} + +{%- endif %} +{%- endmacro %} + +{# A request's whole progress in one bar, for lists. #} +{% macro run_meter(run) -%} +{% if let Some(count) = run.bar() -%} + +{%- else -%} + +{%- endif %} +{%- endmacro %} diff --git a/templates/progress.html b/templates/progress.html new file mode 100644 index 0000000..28d3bba --- /dev/null +++ b/templates/progress.html @@ -0,0 +1,24 @@ +{%- import "macros.html" as m -%} +

Progress

+

Running for {{ self::elapsed(run.elapsed()) }}

+{% for phase in run.overall() %} +
+

{{ phase.title() }} {{ self::elapsed(phase.elapsed) }}

+{% call m::meter(phase) %}{% endcall %} +{% let counted = phase.counted(false) %} +{% if !counted.is_empty() %}

{{ counted }}

{% endif %} +{% if !phase.counts.current.is_empty() %}

Now: {% for name in phase.counts.current %}{{ name }}{% if !loop.last %}, {% endif %}{% endfor %}

{% endif %} +
+{% endfor %} +{% let nodes = run.nodes() %} +{% if !nodes.is_empty() %} +
+ + +{% for row in nodes %} + + + +{% endfor %} +
NodeStateCopyTime
{{ row.node }}{{ row.state }}{% if let Some(copy) = row.copy %}{% call m::meter(copy) %}{% endcall %}{% let counted = copy.counted(false) %}{% if !counted.is_empty() %}{{ counted }}{% endif %}{% endif %}{{ self::elapsed(row.latest.elapsed) }}
+{% endif %} diff --git a/templates/request_region.html b/templates/request_region.html index 5c07b48..3de7053 100644 --- a/templates/request_region.html +++ b/templates/request_region.html @@ -4,6 +4,20 @@ {% if let Some(entry) = view.entry %} {% call m::card(entry, csrf, true) %}{% endcall %} {% endif %} +{% if let Some(run) = view.run %} +
+{% include "progress.html" %} +
+{% else if let Some(past) = view.past %} +{% if !past.phases.is_empty() %} +

Progress

+
    +{% for phase in past.phases %} +
  • {{ phase.line() }}
  • +{% endfor %} +
+{% endif %} +{% endif %} {% if let Some(past) = view.past %} {% if view.entry.is_none() %}

{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}

diff --git a/templates/running.html b/templates/running.html new file mode 100644 index 0000000..7c77428 --- /dev/null +++ b/templates/running.html @@ -0,0 +1,13 @@ +{%- import "macros.html" as m -%} +
+{% if !runs.is_empty() %} +

Running

+
    +{% for run in runs %} +
  • {{ run.summary }} {{ run.requester }} +{% call m::run_meter(run) %}{% endcall %} +{{ run.status() }}
  • +{% endfor %} +
+{% endif %} +