web: Show the progress of running requests
The broker keeps the latest progress of each phase of requests that build (`runs::Runs`), from the build on. A request's page shows a full-width bar for the build and a row for each node in its region, and the main page gets a region of its own listing running requests with a bar each, both kept current by the page's event stream. A request's page reads the audit log again only when the queue changes or a run starts or ends, not with every bit of progress. 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:
1 parent
0f9f56f7b0
commit
45075229de
19 files changed
+742
-85
No files matched your search
@@ -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 `<progress>` 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` |
|
||||
|
||||
+12
-2
@@ -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.
|
||||
|
||||
+26
-5
@@ -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
@@ -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>) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
+14
-7
@@ -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}");
|
||||
}
|
||||
|
||||
+229
@@ -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
@@ -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 {
|
||||
@@ -215,6 +217,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
|
||||
@@ -242,7 +247,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))
|
||||
};
|
||||
|
||||
@@ -273,6 +278,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 {
|
||||
@@ -316,12 +324,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
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+113
-43
@@ -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<Broker>, session: Session, request: Option<String>) ->
|
||||
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<String>,
|
||||
queue: watch::Receiver<u64>,
|
||||
/// The region last sent.
|
||||
sent: Option<String>,
|
||||
runs: watch::Receiver<u64>,
|
||||
/// 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<History>,
|
||||
members: Option<u64>,
|
||||
/// Each region last sent, by `id`.
|
||||
sent: HashMap<&'static str, String>,
|
||||
last: Option<Instant>,
|
||||
ended: bool,
|
||||
}
|
||||
|
||||
impl Updates {
|
||||
fn new(broker: Arc<Broker>, signed_in: SignedIn, request: Option<String>) -> 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<Vec<(&'static str, String)>> {
|
||||
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<Broker> {
|
||||
@@ -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#"<div id="pending">"#) && 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#"<div id="pending">"#) && events[0].1.contains("Nothing is waiting"));
|
||||
assert!(events[1].1.starts_with(r#"<section id="running">"#), "{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#"<div id="request" data-id="abc">"#), "{data}");
|
||||
assert!(data.contains("The audit log has nothing"), "{data}");
|
||||
let events = updates.next().await.unwrap();
|
||||
assert!(events[0].1.starts_with(r#"<div id="request" data-id="abc">"#), "{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("<h1>ssh river</h1>"), "{data}");
|
||||
let events = updates.next().await.unwrap();
|
||||
assert!(events[0].1.contains("<h1>ssh river</h1>"), "{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:?}");
|
||||
}
|
||||
}
|
||||
+27
-9
@@ -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);
|
||||
}
|
||||
|
||||
+3
-3
@@ -205,7 +205,7 @@ 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).into_response())
|
||||
Ok(page::index(&user.name, &user.csrf, &entries, &leases, &web.broker.runs.list()).into_response())
|
||||
}
|
||||
|
||||
async fn request_page(
|
||||
@@ -217,8 +217,8 @@ async fn request_page(
|
||||
Ok(user) => 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())
|
||||
}
|
||||
|
||||
|
||||
+83
-7
@@ -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::<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)
|
||||
}
|
||||
@@ -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<String> {
|
||||
render(Index { name, csrf, entries, leases })
|
||||
pub fn index(
|
||||
name: &str,
|
||||
csrf: &str,
|
||||
entries: &[PendingInfo],
|
||||
leases: &[(String, String, u64)],
|
||||
runs: &[Run],
|
||||
) -> Html<String> {
|
||||
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#"<div id="request" data-id="abc">"#), "{html}");
|
||||
assert!(html.contains(request_region("token", &view).trim()), "{html}");
|
||||
@@ -316,4 +357,39 @@ mod tests {
|
||||
assert!(html.contains("Details (Text)") && html.contains("<pre>Old: text</pre>"), "{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 <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();
|
||||
|
||||
// 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("<h1>deploy <river></h1>"), "{html}");
|
||||
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}");
|
||||
|
||||
// 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("<progress"), "{list}");
|
||||
let empty = running_list(&[]);
|
||||
assert!(empty.starts_with(r#"<section id="running">"#) && !empty.contains("Running"), "{empty}");
|
||||
}
|
||||
}
|
||||
@@ -6,4 +6,5 @@
|
||||
<p><span id="push-state"></span> <button type="button" id="push-toggle" class="quiet"></button></p>
|
||||
</section>
|
||||
{% include "pending.html" %}
|
||||
{% include "running.html" %}
|
||||
{% endblock %}
|
||||
@@ -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 %}
|
||||
@@ -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 class="copy">{% 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 %}
|
||||
@@ -4,6 +4,20 @@
|
||||
{% if let Some(entry) = view.entry %}
|
||||
{% call m::card(entry, csrf, true) %}{% endcall %}
|
||||
{% endif %}
|
||||
{% if let Some(run) = view.run %}
|
||||
<section class="progress">
|
||||
{% include "progress.html" %}
|
||||
</section>
|
||||
{% else if let Some(past) = view.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) = view.past %}
|
||||
{% if view.entry.is_none() %}
|
||||
<p class="meta">{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}</p>
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{%- import "macros.html" as m -%}
|
||||
<section id="running">
|
||||
{% 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 %}
|
||||
</section>
|
||||
Reference in new issue
Block a user