web: Show the progress of running requests
CI / Check (pull_request) Successful in 5m25s

The broker keeps the latest progress of each phase of requests that
build (`runs::Runs`), from the build on. A running request's page shows
a bar for the build and a row for each node, updated through
Server-Sent Events, and the pending page lists running requests with a
bar each. The `finished` and `failed` audit events keep how each phase
ended, which the request's page shows afterwards.

Refs #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-28 21:29:53 +00:00
1 parent 3d8d229a00
commit 95f93f02ac
19 files changed
+713 -48

No files matched your search

+8
View File
@@ -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 streams a request's panel (`templates/progress.html`) from `/requests/<id>/events`
and the running list (`templates/running.html`) from `/running/events`, as Server-Sent Events of
rendered HTML that `app.js` swaps in. The bars are `<progress>` elements, since the content
security policy allows no inline styles.
- `slop` shows it with `Board`: on a terminal, a bar for each running phase, redrawn in place
below other output; otherwise plain lines, every 30 seconds for a running phase and when one
ends, for agents. It holds nothing but a read-only Git key.
@@ -157,6 +164,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` |
+11 -1
View File
@@ -227,13 +227,23 @@ 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 pending page lists running requests with one bar each.
- Pages get updates as Server-Sent Events; 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.
- Each request's page shows its full timeline, including the detail approvers saw, so a
notification for a request that's since been answered still leads somewhere useful.
- **Front end.** Server-rendered HTML that works without JavaScript.
- A small script refreshes the list and manages notifications, and a service worker shows them.
- A small script refreshes the list, follows progress and manages notifications, and a service
worker shows them.
- Everything shown passes through the same filter as `slop-approve` for control and
bidirectional characters.
- A strict content security policy allows only the app's own scripts.
+26 -5
View File
@@ -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<Progress>,
},
Failed {
id: String,
error: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
phases: Vec<Progress>,
},
}
@@ -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"));
}
+21 -3
View File
@@ -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<ServerMessage>);
pub struct Output {
tx: mpsc::Sender<ServerMessage>,
run: Option<(Arc<Runs>, String)>,
}
impl Output {
pub fn new(tx: mpsc::Sender<ServerMessage>) -> Output {
Output { tx, run: None }
}
/// The same output, with progress recorded in `runs` for request `id`.
pub fn tracking(&self, runs: Arc<Runs>, 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<String>) {
+1
View File
@@ -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 types;
+13 -6
View File
@@ -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 { "" };
@@ -167,10 +177,7 @@ impl Progress {
}
State::Done | State::Failed => {
let counted = self.counted(self.state == State::Done);
let mut line = match self.state {
State::Done => self.phase.done(),
_ => format!("{} failed", self.phase.doing()),
};
let mut line = self.title();
if !counted.is_empty() {
line = format!("{line}: {counted}");
}
+229
View File
@@ -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<HashMap<String, Run>>,
/// Bumped on every change, progress included.
changed: watch::Sender<u64>,
/// Bumped when a run starts or ends.
members: watch::Sender<u64>,
}
#[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<Progress>,
}
/// 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<Progress>,
/// 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<NodeRow> {
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<Count> {
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<Runs>, 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<Progress> {
self.runs.lock().unwrap().get(id).map(|r| r.phases.clone()).unwrap_or_default()
}
pub fn get(&self, id: &str) -> Option<Run> {
self.runs.lock().unwrap().get(id).cloned()
}
/// Every run, the oldest first.
pub fn list(&self) -> Vec<Run> {
let mut runs: Vec<Run> = 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<u64> {
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<Runs>,
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::<Vec<_>>(),
[("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);
}
}
+15 -5
View File
@@ -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<Runs>,
}
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<S: AsyncRead + AsyncWrite + Send + 'static>(broker: Arc<Brok
let _ = sink.close().await;
});
let out = Output(tx);
let out = Output::new(tx);
let first = tokio::time::timeout(Duration::from_secs(10), source.next()).await;
let request = match first {
@@ -214,6 +216,9 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
label: label.clone(),
});
// Requests that build are tracked from the build on, for the web app and the audit log.
let mut _tracked = None;
// Operations that build run agent-written Nix in the builder, which needs its own approval;
// approvers first see the commits and their diff, which only takes Git. Then they build, so
// the request's own approval can show what it changes. Others look things up the same way
@@ -241,7 +246,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
return None;
}
let error = format!("{error:#}");
log(Event::Failed { id: id.clone(), error: error.clone() });
log(Event::Failed { id: id.clone(), error: error.clone(), phases: broker.runs.phases(&id) });
Some(ServerMessage::Error(error))
};
@@ -272,6 +277,9 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
.info(format!("use of the builder approved by {}", approver.as_deref().unwrap_or(approved_by_name(by))))
.await;
parsed.prepared.description = Some(description);
_tracked = Some(broker.runs.start(&id, requester, &parsed.op.to_string(), &parsed.summary));
io.out = io.out.tracking(broker.runs.clone(), &id);
}
if let Err(error) = ops::prepare(broker, &mut parsed, io).await {
@@ -315,12 +323,14 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
match result {
Ok(outcome) => {
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))
}
}
+1 -1
View File
@@ -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 {
+20
View File
@@ -128,6 +128,26 @@ function localTimes(root) {
}
}
// Progress of running requests, pushed by the broker as HTML to swap in.
function follow(path, element, ended) {
if (!element || !("EventSource" in window)) return;
const source = new EventSource(path, { withCredentials: true });
source.addEventListener("update", (event) => {
element.innerHTML = event.data;
});
source.addEventListener("end", () => {
source.close();
if (ended) ended();
});
}
const progress = document.getElementById("progress");
if (progress) {
// Once it's finished, the page shows how it ended.
follow(`/requests/${encodeURIComponent(progress.dataset.id)}/events`, progress, () => location.reload());
}
follow("/running/events", document.getElementById("running"));
localTimes(document);
startCountdowns(document);
setInterval(() => refresh().catch(() => {}), 3000);
+104
View File
@@ -470,3 +470,107 @@ 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;
}
.phase .current code {
overflow-wrap: anywhere;
}
table.nodes {
width: 100%;
margin-top: 8px;
}
table.nodes td {
vertical-align: middle;
}
table.nodes progress {
width: 8rem;
}
#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);
}
+27 -9
View File
@@ -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<String>,
/// How each phase of a build or deploy ended.
pub phases: Vec<Progress>,
pub records: Vec<Record>,
}
@@ -124,6 +127,7 @@ fn summarize(id: String, records: Vec<Record>) -> 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<Record>) -> 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<Detail>) {
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<Detail> {
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<Detail> {
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);
}
+68 -3
View File
@@ -24,6 +24,7 @@ use tower_sessions_rusqlite_store::{RusqliteStore, tokio_rusqlite};
use crate::approve;
use crate::config::WebConfig;
use crate::queue::{Decision, PendingInfo};
use crate::runs::Runs;
use crate::server::Broker;
use auth::{Flow, Oidc, Purpose};
use history::History;
@@ -83,6 +84,8 @@ pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: String) -> Resu
.route("/", get(index))
.route("/pending", get(pending_fragment))
.route("/requests/{id}", get(request_page).post(answer))
.route("/requests/{id}/events", get(request_events))
.route("/running/events", get(running_events))
.route("/log", get(log_page))
.route("/api/version", get(version))
.route("/api/csrf", get(csrf))
@@ -204,7 +207,8 @@ async fn index(State(web): State<Arc<Web>>, session: Session) -> Result<Response
let entries = web.broker.queue.list();
let leases = web.broker.queue.all_leases();
Ok(page::index(&user.name, &user.csrf, &entries, &leases, web.broker.queue.version()).into_response())
let runs = web.broker.runs.list();
Ok(page::index(&user.name, &user.csrf, &entries, &leases, &runs, web.broker.queue.version()).into_response())
}
async fn pending_fragment(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
@@ -229,8 +233,69 @@ async fn request_page(
histories.into_iter().find(|h| h.id == id)
});
let current = pending(&web, &id);
Ok(page::request(&user.name, &user.csrf, &id, current.as_ref(), past.as_ref(), web.broker.queue.version())
.into_response())
let run = web.broker.runs.get(&id);
let view = page::RequestView {
id: &id,
entry: current.as_ref(),
run: run.as_ref(),
past: past.as_ref(),
version: web.broker.queue.version(),
};
Ok(page::request(&user.name, &user.csrf, &view).into_response())
}
/// A running request's progress panel, as Server-Sent Events: the panel as HTML whenever it
/// changes, then `end` once the request finishes.
async fn request_events(
State(web): State<Arc<Web>>,
session: Session,
Path(id): Path<String>,
) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(events(&web, move |runs| runs.get(&id).map(|run| page::panel(&run))))
}
/// The running requests' list, as Server-Sent Events whenever it changes.
async fn running_events(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(events(&web, |runs| Some(page::running_list(&runs.list()))))
}
/// How often pages get progress at most.
const EVENT_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
/// Streams `render`'s HTML as `update` events whenever runs change; when it gives `None`, an
/// `end` event closes the stream.
fn events(web: &Web, render: impl Fn(&Runs) -> Option<String> + Send + Sync + 'static) -> Response {
use axum::response::sse::{Event, KeepAlive, Sse};
let runs = web.broker.runs.clone();
let changes = runs.subscribe();
let render = Arc::new(render);
let stream = futures_util::stream::unfold((changes, true, false), move |(mut changes, first, ended)| {
let (runs, render) = (runs.clone(), render.clone());
async move {
if ended {
return None;
}
if !first {
tokio::time::sleep(EVENT_INTERVAL).await;
changes.changed().await.ok()?;
}
changes.borrow_and_update();
let event = match render(&runs) {
Some(html) => (Event::default().event("update").data(html), false),
None => (Event::default().event("end").data(""), true),
};
Some((Ok::<_, std::convert::Infallible>(event.0), (changes, false, event.1)))
}
});
let mut response = Sse::new(stream).keep_alive(KeepAlive::default()).into_response();
// Proxies such as nginx would otherwise hold events back.
response.headers_mut().insert("x-accel-buffering", HeaderValue::from_static("no"));
response
}
#[derive(Deserialize)]
+97 -15
View File
@@ -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;
/// HTML escaping, after replacing what [`printable`] replaces.
#[derive(Debug, Clone, Copy)]
@@ -67,6 +69,23 @@ fn section_titles(detail: &Detail) -> String {
detail.sections.iter().map(Section::title).collect::<Vec<_>>().join(", ")
}
fn elapsed(seconds: impl std::borrow::Borrow<u64>) -> 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<Detail>) {
history::describe(&record.event)
}
@@ -102,6 +121,7 @@ struct Index<'a> {
csrf: &'a str,
entries: &'a [PendingInfo],
leases: &'a [(String, String, u64)],
runs: &'a [Run],
version: u64,
}
@@ -110,9 +130,32 @@ pub fn index(
csrf: &str,
entries: &[PendingInfo],
leases: &[(String, String, u64)],
runs: &[Run],
version: u64,
) -> Html<String> {
render(Index { name, csrf, entries, leases, version })
render(Index { name, csrf, entries, leases, runs, version })
}
/// Requests that are running, which the page script swaps in as they change.
#[derive(Template)]
#[template(path = "running.html")]
struct Running<'a> {
runs: &'a [Run],
}
pub fn running_list(runs: &[Run]) -> String {
render(Running { runs }).0
}
/// A running request's progress panel, which the page script swaps in as it changes.
#[derive(Template)]
#[template(path = "progress.html")]
struct Panel<'a> {
run: &'a Run,
}
pub fn panel(run: &Run) -> String {
render(Panel { run }).0
}
#[derive(Template)]
@@ -122,24 +165,28 @@ struct Request<'a> {
csrf: &'a str,
heading: String,
entry: Option<&'a PendingInfo>,
run: Option<&'a Run>,
past: Option<&'a History>,
version: u64,
}
pub fn request(
name: &str,
csrf: &str,
id: &str,
entry: Option<&PendingInfo>,
past: Option<&History>,
version: u64,
) -> Html<String> {
let heading = match (entry, past) {
(Some(entry), _) => entry.summary.clone(),
(None, Some(past)) if !past.summary.is_empty() => past.summary.clone(),
_ => format!("Request {}", short(id)),
pub struct RequestView<'a> {
pub id: &'a str,
pub entry: Option<&'a PendingInfo>,
pub run: Option<&'a Run>,
pub past: Option<&'a History>,
pub version: u64,
}
pub fn request(name: &str, csrf: &str, view: &RequestView) -> Html<String> {
let heading = match (view.entry, view.run, view.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(view.id)),
};
render(Request { name, csrf, heading, entry, past, version })
let RequestView { entry, run, past, version, .. } = *view;
render(Request { name, csrf, heading, entry, run, past, version })
}
/// What the log page is filtered by.
@@ -296,9 +343,44 @@ mod tests {
];
let (histories, _) = super::history::gather(records);
let html = request("broker", "token", "abc", None, Some(&histories[0]), 0).0;
let view = RequestView { id: "abc", entry: None, run: None, past: Some(&histories[0]), version: 0 };
let html = request("broker", "token", &view).0;
assert!(html.contains("<dt>Command</dt><dd class=\"neutral\"><code>uptime</code></dd>"), "{html}");
assert!(html.contains("<span class=\"diff-add\">+a</span>"), "{html}");
assert!(html.contains("Details (Text)") && html.contains("<pre>Old: text</pre>"), "{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 <river>");
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();
let html = panel(&run);
assert!(html.contains(r#"<progress class="active" max="8" value="3"></progress>"#), "{html}");
assert!(html.contains("<strong>building</strong> <span class=\"meta\">1m 10s</span>"), "{html}");
assert!(html.contains("Now: <code>hello-2.12</code>"), "{html}");
assert!(html.contains(r#"<span class="outcome neutral">copied</span>"#), "{html}");
assert!(html.contains(r#"<progress class="good" max="2" value="2"></progress>"#), "{html}");
let list = running_list(&runs.list());
assert!(list.contains("deploy &#60;river&#62;") && list.contains("<progress"), "{list}");
assert!(!running_list(&[]).contains("Running"));
let view = RequestView { id: "abc", entry: None, run: Some(&run), past: None, version: 0 };
let page = request("broker", "token", &view).0;
assert!(page.contains(r#"id="progress" class="progress" data-id="abc""#), "{page}");
}
}
+3
View File
@@ -8,4 +8,7 @@
<div id="pending" data-version="{{ version }}">
{% include "pending.html" %}
</div>
<section id="running">
{% include "running.html" %}
</section>
{% endblock %}
+20
View File
@@ -90,3 +90,23 @@
{%- for (value, text) in options %}<option value="{{ value }}"{% if value.as_str() == chosen.as_str() %} selected{% endif %}>{{ text }}</option>{% endfor -%}
</select></label>
{%- 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() -%}
<progress class="{{ self::state_class(progress) }}" max="{{ count.total }}" value="{{ count.done }}"></progress>
{%- else if self::running(progress) -%}
<progress class="active"></progress>
{%- else -%}
<progress class="{{ self::state_class(progress) }}" max="1" value="1"></progress>
{%- endif %}
{%- endmacro %}
{# A request's whole progress in one bar, for lists. #}
{% macro run_meter(run) -%}
{% if let Some(count) = run.bar() -%}
<progress class="active" max="{{ count.total }}" value="{{ count.done }}"></progress>
{%- else -%}
<progress class="active"></progress>
{%- endif %}
{%- endmacro %}
+24
View File
@@ -0,0 +1,24 @@
{%- import "macros.html" as m -%}
<h2>Progress</h2>
<p class="meta">Running for {{ self::elapsed(run.elapsed()) }}</p>
{% for phase in run.overall() %}
<div class="phase {{ self::state_class(phase) }}">
<p class="phase-title"><strong>{{ phase.title() }}</strong> <span class="meta">{{ self::elapsed(phase.elapsed) }}</span></p>
{% call m::meter(phase) %}{% endcall %}
{% let counted = phase.counted(false) %}
{% if !counted.is_empty() %}<p class="meta">{{ counted }}</p>{% endif %}
{% if !phase.counts.current.is_empty() %}<p class="meta current">Now: {% for name in phase.counts.current %}<code>{{ name }}</code>{% if !loop.last %}, {% endif %}{% endfor %}</p>{% endif %}
</div>
{% endfor %}
{% let nodes = run.nodes() %}
{% if !nodes.is_empty() %}
<div class="scroll"><table class="nodes">
<thead><tr><th>Node</th><th>State</th><th>Copy</th><th>Time</th></tr></thead>
<tbody>
{% for row in nodes %}
<tr><td><code>{{ row.node }}</code></td><td><span class="outcome {{ row.tone }}">{{ row.state }}</span></td>
<td>{% if let Some(copy) = row.copy %}{% call m::meter(copy) %}{% endcall %}{% let counted = copy.counted(false) %}{% if !counted.is_empty() %} <span class="meta">{{ counted }}</span>{% endif %}{% endif %}</td>
<td>{{ self::elapsed(row.latest.elapsed) }}</td></tr>
{% endfor %}
</tbody></table></div>
{% endif %}
+14
View File
@@ -7,6 +7,20 @@
{% if let Some(entry) = entry %}
{% call m::card(entry, csrf, true) %}{% endcall %}
{% endif %}
{% if let Some(run) = run %}
<section id="progress" class="progress" data-id="{{ run.id }}">
{% include "progress.html" %}
</section>
{% else if let Some(past) = past %}
{% if !past.phases.is_empty() %}
<h2>Progress</h2>
<ul class="phases">
{% for phase in past.phases %}
<li class="{{ self::state_class(phase) }}">{{ phase.line() }}</li>
{% endfor %}
</ul>
{% endif %}
{% endif %}
{% if let Some(past) = past %}
{% if entry.is_none() %}
<p class="meta">{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}</p>
+11
View File
@@ -0,0 +1,11 @@
{%- import "macros.html" as m -%}
{% if !runs.is_empty() %}
<h2>Running</h2>
<ul class="runs">
{% for run in runs %}
<li><a href="/requests/{{ run.id }}">{{ run.summary }}</a> <span class="meta">{{ run.requester }}</span>
{% call m::run_meter(run) %}{% endcall %}
<span class="meta">{{ run.status() }}</span></li>
{% endfor %}
</ul>
{% endif %}