OXYGENHUB

Coverage / crates/hub/src/web/flow.rs 80.1%

704 of 879 lines run, 96 of 304 functions · run #528 on main · run missed

1
//! The Flow tab (hub spec §13.2): runs of a repository, and a run's job
2
//! graph with live status and logs.
3
4
use super::settings::{csrf, require};
5
use super::{filters, lookup, lookup_role, Error, Page, RepoShell, Shell};
6
use crate::auth::{Access, Role, Viewer};
7
use crate::db::{self, flow as fdb};
8
use crate::Shared;
9
use askama::Template;
10
use axum::extract::{Form, Path, Query, State};
11
use axum::response::{IntoResponse, Redirect, Response};
12
use axum::Json;
13
use serde::Deserialize;
14
15
pub struct RunRow {
16
    pub r: fdb::Run,
17
    pub duration: String,
18
    pub jobs: Vec<(String, String)>,
19
    /// "3rd in line" for a run still waiting for a runner.
20
    pub place: Option<String>,
21
}
22
23
#[derive(Template)]
24
#[template(path = "flow_runs.html")]
25
pub struct RunsPage {
26
    shell: Shell,
27
    repo: RepoShell,
28
    runs: Vec<RunRow>,
29
    enabled: bool,
30
    older: Option<i64>,
31
    /// Writers may start runs: the bookmarks to offer, default first.
32
    can_run: bool,
33
    bookmarks: Vec<String>,
34
    error: Option<String>,
35
    /// Why this viewer is not offered "Run pipeline", when they are not.
36
    why_not: Option<String>,
37
}
38
39
#[derive(Deserialize)]
40
pub struct RunsQuery {
41
    before: Option<i64>,
42
    /// Why a "Run pipeline" or "Re-run" did not start.
43
    error: Option<String>,
44
}
45
46
/// Why `viewer` may not start runs here, or `None` when they may.
4737×
pub fn why_not_run(enabled: bool, signed_in: bool, role: Role) -> Option<String> {
4837×
    if !enabled {
4930×
        Some("Flow is off for this repository; a site administrator can turn it on in Settings › Pipelines.".into())
507×
    } else if !signed_in {
516×
        Some("Sign in with write access to run the pipeline.".into())
521×
    } else if role < Role::Write {
530×
        Some("Running the pipeline needs write access to this repository.".into())
54
    } else {
551×
        None
56
    }
5737×
}
58
59
const PER_PAGE: i64 = 30;
60
61
#[derive(Template)]
62
#[template(path = "deployments.html")]
63
pub struct DeploymentsPage {
64
    shell: Shell,
65
    repo: RepoShell,
66
    /// Each environment's newest deployment, by name.
67
    current: Vec<fdb::Deployment>,
68
    /// Every recent deployment, newest first.
69
    history: Vec<fdb::Deployment>,
70
}
71
72
/// `GET /{owner}/{name}/deployments`: what each environment runs
73
/// (oxygenflow#59).
741×
pub async fn deployments(
751×
    State(app): State<Shared>,
761×
    viewer: Viewer,
771×
    Path((owner, name)): Path<(String, String)>,
781×
) -> Result<Page<DeploymentsPage>, Error> {
791×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/deployments"), &viewer);
801×
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
811×
    let history = fdb::deployments(&app.db, row.id, 50).await.map_err(|e| Error::from_db(shell.clone(), e))?;
821×
    let mut current: Vec<fdb::Deployment> = Vec::new();
831×
    for d in &history {
841×
        if !current.iter().any(|c| c.environment == d.environment) {
851×
            current.push(d.clone());
861×
        }
87
    }
881×
    current.sort_by(|a, b| a.environment.cmp(&b.environment));
891×
    Ok(Page(DeploymentsPage { shell, repo: RepoShell::new(&app, &row, "flow").with_role(role), current, history }))
901×
}
91
928×
pub async fn runs(
938×
    State(app): State<Shared>,
948×
    viewer: Viewer,
958×
    Path((owner, name)): Path<(String, String)>,
968×
    Query(q): Query<RunsQuery>,
978×
) -> Result<Page<RunsPage>, Error> {
988×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
998×
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1008×
    let list = fdb::runs(&app.db, row.id, PER_PAGE + 1, q.before).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1018×
    let older = (list.len() as i64 > PER_PAGE).then(|| list[PER_PAGE as usize - 1].id);
1028×
    let queue = if list.iter().any(|r| r.live()) { fdb::queue(&app.db).await.unwrap_or_default() } else { vec![] };
1038×
    let mut runs = Vec::new();
10411×
    for r in list.into_iter().take(PER_PAGE as usize) {
10511×
        let place = if r.live() { crate::flow::queue_info(&queue, row.id, r.id).place() } else { None };
10611×
        let jobs = fdb::jobs(&app.db, r.id).await.unwrap_or_default();
10711×
        let duration = match r.finished_ms {
1083×
            Some(f) => crate::flow::human_ms(f - r.created_ms),
1098×
            None if r.live() => crate::flow::human_ms(db::now_ms() - r.created_ms),
1100×
            None => "–".into(),
111
        };
11230×
        runs.push(RunRow { jobs: jobs.into_iter().map(|j| (j.name, j.status)).collect(), duration, r, place });
113
    }
1148×
    let enabled = crate::flow::enabled(&app, &row);
1158×
    let why_not = why_not_run(enabled, viewer.account().is_some(), role);
1168×
    let can_run = why_not.is_none();
1178×
    let bookmarks = if can_run { bookmark_names(&app, &row).await } else { vec![] };
1188×
    Ok(Page(RunsPage {
1198×
        shell,
1208×
        repo: RepoShell::new(&app, &row, "flow").with_role(role),
1218×
        runs,
1228×
        enabled,
1238×
        older,
1248×
        can_run,
1258×
        bookmarks,
1268×
        error: q.error,
1278×
        why_not,
1288×
    }))
1298×
}
130
131
/// A WASM job as the tab runner runs it (oxygenflow#80).
132
#[derive(serde::Serialize)]
133
pub struct TabJob {
134
    name: String,
135
    exec: Vec<String>,
136
    env: std::collections::BTreeMap<String, String>,
137
    memory_mib: u32,
138
}
139
140
#[derive(Template)]
141
#[template(path = "flow_tab.html")]
142
pub struct TabPage {
143
    shell: Shell,
144
    repo: RepoShell,
145
    bookmark: String,
146
    bookmarks: Vec<String>,
147
    /// The pipeline's WASM jobs, as JSON for the page's script.
148
    jobs_json: String,
149
    jobs: usize,
150
    /// Why there is nothing to run: no pipeline, one that does not read,
151
    /// or no WASM job in it.
152
    problem: Option<String>,
153
    archive: String,
154
}
155
156
#[derive(Deserialize)]
157
pub struct TabQuery {
158
    bookmark: Option<String>,
159
}
160
161
/// The WASM jobs of a pipeline (`runtime "wasm"`), each with the
162
/// environment its sandbox and itself give it.
1632×
pub fn wasm_jobs(p: &flow_core::Pipeline) -> Vec<TabJob> {
1642×
    p.jobs
1652×
        .values()
1662×
        .filter_map(|j| {
1672×
            let sb = p.sandboxes.get(&j.sandbox)?;
1682×
            (sb.runtime == flow_core::Runtime::Wasm && !j.exec.is_empty()).then(|| {
1692×
                let mut env = sb.env.clone();
1702×
                env.extend(j.env.clone());
1712×
                TabJob { name: j.name.clone(), exec: j.exec.clone(), env, memory_mib: sb.memory_mib }
1722×
            })
1732×
        })
1742×
        .collect()
1752×
}
176
177
/// `GET /{owner}/{name}/flow/tab`: run the pipeline's WASM jobs in this
178
/// browser tab (oxygenflow#80, first part): a worker unpacks the
179
/// bookmark's files and runs each job's modules with a WASI shim, as a
180
/// runner's WASM tier does. Nothing is claimed or reported: it shows the
181
/// tier works in a tab, before the tab becomes a runner.
1822×
pub async fn tab(
1832×
    State(app): State<Shared>,
1842×
    viewer: Viewer,
1852×
    Path((owner, name)): Path<(String, String)>,
1862×
    Query(q): Query<TabQuery>,
1872×
) -> Result<Page<TabPage>, Error> {
1882×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/tab"), &viewer);
1892×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1902×
    let bookmarks = bookmark_names(&app, &row).await;
1912×
    let bookmark = q.bookmark.filter(|b| bookmarks.contains(b)).unwrap_or_else(|| row.default_bookmark.clone());
1922×
    let b = bookmark.clone();
1932×
    let text = app
1942×
        .repos
1952×
        .read(&repo, move |r, cache| {
1962×
            let Some(st) = r.view()?.bookmarks.get(&b).copied() else { return Ok(None) };
1972×
            let heads = r.store().get_state(&st)?.heads;
1982×
            let loaded = cache.load(r, &heads)?;
1992×
            Ok(match loaded.snapshot.files.get(flow_core::PIPELINE_PATH).map(|f| &f.content) {
2002×
                Some(oxy_core::state::FileContent::Text { bytes, .. }) => Some(String::from_utf8_lossy(bytes).into_owned()),
2010×
                _ => None,
202
            })
2032×
        })
2042×
        .await
2052×
        .unwrap_or(None);
2062×
    let (jobs, problem) = match text.map(|t| flow_core::Pipeline::parse(&t)) {
2070×
        None => (vec![], Some(format!("{bookmark} has no {}.", flow_core::PIPELINE_PATH))),
2080×
        Some(Err(e)) => (vec![], Some(format!("The pipeline on {bookmark} does not read: {e}"))),
2092×
        Some(Ok(p)) => {
2102×
            let jobs = wasm_jobs(&p);
2112×
            let problem =
2122×
                jobs.is_empty().then(|| format!("The pipeline on {bookmark} has no WASM jobs (a sandbox with runtime \"wasm\")."));
2132×
            (jobs, problem)
214
        }
215
    };
216
    Ok(Page(TabPage {
2172×
        shell,
2182×
        repo: RepoShell::new(&app, &row, "flow").with_role(role),
2192×
        archive: format!("/{owner}/{name}/archive?ref={}&format=zip", urlencoding(&bookmark)),
2202×
        bookmark,
2212×
        bookmarks,
2222×
        jobs: jobs.len(),
2232×
        jobs_json: serde_json::to_string(&jobs).unwrap_or_else(|_| "[]".into()),
2242×
        problem,
225
    }))
2262×
}
227
228
/// The repository's bookmarks, its default first.
2293×
async fn bookmark_names(app: &Shared, row: &db::repos::RepoRow) -> Vec<String> {
2303×
    let Some(repo) = crate::repos::RepoName::new(&row.owner, &row.name) else { return vec![] };
2313×
    let mut names: Vec<String> = app.repos.read(&repo, |r, _| Ok(r.view()?.bookmarks.keys().cloned().collect())).await.unwrap_or_default();
2323×
    names.sort_by_key(|n| (n != &row.default_bookmark, n.clone()));
2333×
    names
2343×
}
235
236
#[derive(Deserialize)]
237
pub struct StartForm {
238
    #[serde(rename = "_csrf")]
239
    csrf_token: String,
240
    #[serde(default)]
241
    bookmark: String,
242
    /// A change's full hash: run the state whose only head it is.
243
    #[serde(default)]
244
    change: String,
245
}
246
247
/// `POST /{owner}/{name}/flow/start`: "Run pipeline" on a bookmark's
248
/// current state, or on one committed change.
2490×
pub async fn start(
2500×
    State(app): State<Shared>,
2510×
    viewer: Viewer,
2520×
    Path((owner, name)): Path<(String, String)>,
2530×
    Form(f): Form<StartForm>,
2540×
) -> Result<Response, Error> {
2550×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
2560×
    let me = require(&viewer, &shell)?;
2570×
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
2580×
    csrf(&viewer, &f.csrf_token, &shell)?;
2590×
    let (started, what) = if f.change.trim().is_empty() {
2600×
        (crate::flow::run_bookmark(&app, &row, f.bookmark.trim(), &me.account.username, &[]).await, f.bookmark.trim().to_string())
261
    } else {
2620×
        (crate::flow::run_change(&app, &row, &f.change, &me.account.username, &[]).await, format!("change {}", f.change.trim()))
263
    };
2640×
    Ok(match started {
2650×
        Ok(n) => {
2660×
            db::accounts::audit(&app.db, Some(&me.account), "flow.run", &format!("{owner}/{name}"), &format!("#{n} {what}")).await.ok();
2670×
            Redirect::to(&format!("/{owner}/{name}/flow/{n}")).into_response()
268
        }
2690×
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
270
    })
2710×
}
272
273
#[derive(Deserialize)]
274
pub struct RerunForm {
275
    #[serde(rename = "_csrf")]
276
    csrf_token: String,
277
}
278
279
/// `POST /{owner}/{name}/flow/{number}/rerun`.
2800×
pub async fn rerun(
2810×
    State(app): State<Shared>,
2820×
    viewer: Viewer,
2830×
    Path((owner, name, number)): Path<(String, String, i64)>,
2840×
    Form(f): Form<RerunForm>,
2850×
) -> Result<Response, Error> {
2860×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
2870×
    let me = require(&viewer, &shell)?;
2880×
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
2890×
    csrf(&viewer, &f.csrf_token, &shell)?;
2900×
    let run = fdb::run(&app.db, row.id, number)
2910×
        .await
2920×
        .map_err(|e| Error::from_db(shell.clone(), e))?
2930×
        .ok_or_else(|| Error::not_found(shell.clone()))?;
2940×
    Ok(match crate::flow::rerun(&app, &row, &run, &me.account.username).await {
2950×
        Ok(n) => {
2960×
            db::accounts::audit(&app.db, Some(&me.account), "flow.rerun", &format!("{owner}/{name}"), &format!("#{n} of #{number}"))
2970×
                .await
2980×
                .ok();
2990×
            Redirect::to(&format!("/{owner}/{name}/flow/{n}")).into_response()
300
        }
3010×
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
302
    })
3030×
}
304
305
/// `POST /{owner}/{name}/flow/{number}/jobs/{job}/rerun` (oxygenflow#31).
3060×
pub async fn rerun_job(
3070×
    State(app): State<Shared>,
3080×
    viewer: Viewer,
3090×
    Path((owner, name, number, job)): Path<(String, String, i64, String)>,
3100×
    Form(f): Form<RerunForm>,
3110×
) -> Result<Response, Error> {
3120×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
3130×
    let me = require(&viewer, &shell)?;
3140×
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
3150×
    csrf(&viewer, &f.csrf_token, &shell)?;
3160×
    let run = fdb::run(&app.db, row.id, number)
3170×
        .await
3180×
        .map_err(|e| Error::from_db(shell.clone(), e))?
3190×
        .ok_or_else(|| Error::not_found(shell.clone()))?;
3200×
    Ok(match crate::flow::rerun_job(&app, &row, &run, &job, &me.account.username).await {
321
        Ok(_) => {
3220×
            db::accounts::audit(&app.db, Some(&me.account), "flow.rerun", &format!("{owner}/{name}"), &format!("{job} of #{number}"))
3230×
                .await
3240×
                .ok();
3250×
            Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response()
326
        }
3270×
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
328
    })
3290×
}
330
331
/// `POST /{owner}/{name}/flow/{number}/cancel` (oxygenflow#32).
3320×
pub async fn cancel(
3330×
    State(app): State<Shared>,
3340×
    viewer: Viewer,
3350×
    Path((owner, name, number)): Path<(String, String, i64)>,
3360×
    Form(f): Form<RerunForm>,
3370×
) -> Result<Response, Error> {
3380×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
3390×
    let me = require(&viewer, &shell)?;
3400×
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
3410×
    csrf(&viewer, &f.csrf_token, &shell)?;
3420×
    let run = fdb::run(&app.db, row.id, number)
3430×
        .await
3440×
        .map_err(|e| Error::from_db(shell.clone(), e))?
3450×
        .ok_or_else(|| Error::not_found(shell.clone()))?;
3460×
    Ok(match crate::flow::cancel(&app, &row, &run, &me.account.username).await {
347
        Ok(()) => {
3480×
            db::accounts::audit(&app.db, Some(&me.account), "flow.cancel", &format!("{owner}/{name}"), &format!("#{number}")).await.ok();
3490×
            Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response()
350
        }
3510×
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
352
    })
3530×
}
354
355
#[derive(Deserialize)]
356
pub struct ExpediteForm {
357
    #[serde(rename = "_csrf")]
358
    csrf_token: String,
359
    #[serde(default)]
360
    reason: String,
361
}
362
363
/// `POST /{owner}/{repo}/flow/{n}/expedite` (oxygenhub#244): a maintainer
364
/// raises a running or queued run to urgent, saying why (an incident's
365
/// fix, say). Audited and shown on the run; it lapses when the run ends.
3661×
pub async fn expedite(
3671×
    State(app): State<Shared>,
3681×
    viewer: Viewer,
3691×
    Path((owner, name, number)): Path<(String, String, i64)>,
3701×
    Form(f): Form<ExpediteForm>,
3711×
) -> Result<Response, Error> {
3721×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
3731×
    let me = require(&viewer, &shell)?;
3741×
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Maintain).await?;
3751×
    csrf(&viewer, &f.csrf_token, &shell)?;
3761×
    let run = fdb::run(&app.db, row.id, number)
3771×
        .await
3781×
        .map_err(|e| Error::from_db(shell.clone(), e))?
3791×
        .ok_or_else(|| Error::not_found(shell.clone()))?;
3801×
    if let Err(msg) = crate::flow::expedite(&app, &row, &run, &me.account, &f.reason).await {
3810×
        return Ok(Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response());
3821×
    }
3831×
    Ok(Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response())
3841×
}
385
386
/// Percent-encode a message for a query string.
3872×
fn urlencoding(s: &str) -> String {
3882×
    s.bytes()
3898×
        .map(|b| match b {
3908×
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),
3910×
            _ => format!("%{b:02X}"),
3928×
        })
3932×
        .collect()
3942×
}
395
396
/// A job placed in the graph.
397
pub struct Node {
398
    pub j: fdb::Job,
399
    pub x: i64,
400
    pub y: i64,
401
    pub duration: String,
402
}
403
404
pub struct Edge {
405
    pub d: String,
406
    pub status: String,
407
}
408
409
pub struct Graph {
410
    pub nodes: Vec<Node>,
411
    pub edges: Vec<Edge>,
412
    pub width: i64,
413
    pub height: i64,
414
}
415
416
pub const NODE_W: i64 = 200;
417
pub const NODE_H: i64 = 48;
418
const COL_GAP: i64 = 72;
419
const ROW_GAP: i64 = 18;
420
const PAD: i64 = 12;
421
422
/// Columns by dependency depth, jobs in each column in name order.
42323×
pub fn layout(jobs: Vec<fdb::Job>) -> Graph {
42423×
    let mut by_depth: std::collections::BTreeMap<i64, Vec<fdb::Job>> = Default::default();
42554×
    for j in jobs {
42654×
        by_depth.entry(j.depth).or_default().push(j);
42754×
    }
42823×
    let rows = by_depth.values().map(Vec::len).max().unwrap_or(0) as i64;
42923×
    let height = PAD * 2 + rows * NODE_H + (rows - 1).max(0) * ROW_GAP;
43023×
    let mut nodes = Vec::new();
43139×
    for (col, (_, mut js)) in by_depth.into_iter().enumerate() {
43239×
        js.sort_by(|a, b| a.name.cmp(&b.name));
43339×
        let n = js.len() as i64;
43439×
        let column_h = n * NODE_H + (n - 1).max(0) * ROW_GAP;
43539×
        let top = (height - column_h) / 2;
43654×
        for (i, j) in js.into_iter().enumerate() {
43754×
            let duration = crate::flow::duration(&j);
43854×
            nodes.push(Node { x: PAD + col as i64 * (NODE_W + COL_GAP), y: top + i as i64 * (NODE_H + ROW_GAP), duration, j });
43954×
        }
440
    }
44123×
    let mut edges = Vec::new();
44254×
    for n in &nodes {
44354×
        for d in n.j.depends_on() {
44420×
            if let Some(from) = nodes.iter().find(|m| m.j.name == d) {
44518×
                let (x1, y1) = (from.x + NODE_W, from.y + NODE_H / 2);
44618×
                let (x2, y2) = (n.x, n.y + NODE_H / 2);
44718×
                let mid = (x1 + x2) / 2;
44818×
                edges.push(Edge { d: format!("M{x1},{y1} C{mid},{y1} {mid},{y2} {x2},{y2}"), status: from.j.status.clone() });
44918×
            }
450
        }
451
    }
45223×
    let cols = nodes.iter().map(|n| n.x).max().map(|x| x + NODE_W + PAD).unwrap_or(PAD * 2);
45323×
    Graph { nodes, edges, width: cols, height: height.max(NODE_H + PAD * 2) }
45423×
}
455
456181×
pub fn glyph(status: &str) -> &'static str {
457181×
    match status {
458181×
        "passed" => "✓",
459124×
        "failed" => "✕",
460111×
        "running" => "●",
46196×
        "skipped" => "⤼",
46295×
        "cancelled" => "⊘",
46386×
        "error" => "!",
46485×
        _ => "○",
465
    }
466181×
}
467
468
/// Failed tests a run page lists per job; the rest are counted.
469
const SHOWN_FAILURES: i64 = 50;
470
471
/// A stretch of a job's log as the run page shows it: a line, or a
472
/// section the job marked with `::group::TITLE` … `::endgroup::`
473
/// (oxygenflow#31), shown folded with how long it took.
474
pub enum Segment {
475
    Line(fdb::LogLine),
476
    Group(Section),
477
}
478
479
pub struct Section {
480
    pub title: String,
481
    /// When it began, and ended (`None` while it is still going).
482
    pub from_t: i64,
483
    pub to_t: Option<i64>,
484
    pub lines: Vec<fdb::LogLine>,
485
}
486
487
/// A log's lines in sections. A section left open is still going; a new
488
/// `::group::` ends the one before (sections do not nest).
48955×
pub fn sections(lines: &[fdb::LogLine]) -> Vec<Segment> {
49055×
    let mut out: Vec<Segment> = Vec::new();
49155×
    let mut open: Option<Section> = None;
49255×
    for l in lines {
49333×
        if let Some(title) = l.text.strip_prefix("::group::") {
4946×
            if let Some(g) = open.take() {
4951×
                out.push(Segment::Group(Section { to_t: Some(l.t), ..g }));
4965×
            }
4976×
            open = Some(Section { title: title.trim().to_string(), from_t: l.t, to_t: None, lines: Vec::new() });
49827×
        } else if l.text.trim() == "::endgroup::" {
4994×
            if let Some(g) = open.take() {
5004×
                out.push(Segment::Group(Section { to_t: Some(l.t), ..g }));
5014×
            }
502
        } else {
50323×
            match open.as_mut() {
5047×
                Some(g) => g.lines.push(l.clone()),
50516×
                None => out.push(Segment::Line(l.clone())),
506
            }
507
        }
508
    }
50955×
    if let Some(g) = open {
5101×
        out.push(Segment::Group(g));
51154×
    }
51255×
    out
51355×
}
514
515
/// Milliseconds as the log shows them: `12.3s`.
51629×
pub fn secs(ms: impl std::borrow::Borrow<i64>) -> String {
51729×
    let ms = *ms.borrow();
51829×
    format!("{}.{}s", ms / 1000, ms % 1000 / 100)
51929×
}
520
521
pub struct JobLog {
522
    pub j: fdb::Job,
523
    pub artifacts: Vec<fdb::Artifact>,
524
    pub lines: Vec<fdb::LogLine>,
525
    /// The lines in sections (oxygenflow#31).
526
    pub segments: Vec<Segment>,
527
    pub duration: String,
528
    /// The last line shown; the live view asks for what follows.
529
    pub last_seq: i64,
530
    /// The job's coverage report, when it uploaded one (#113): its id and percentage.
531
    pub coverage: Option<(i64, String)>,
532
    /// The job's test report, when it uploaded one (#114), and its first
533
    /// failures.
534
    pub tests: Option<crate::junit::Report>,
535
    pub failures: Vec<crate::junit::Case>,
536
}
537
538
#[derive(Template)]
539
#[template(path = "flow_run.html")]
540
pub struct RunPage {
541
    shell: Shell,
542
    repo: RepoShell,
543
    run: fdb::Run,
544
    graph: Graph,
545
    logs: Vec<JobLog>,
546
    duration: String,
547
    /// Whether the viewer may re-run it.
548
    can_rerun: bool,
549
    /// Whether the viewer may cancel it.
550
    can_cancel: bool,
551
    /// May raise the run to urgent (oxygenhub#244): maintainers, while it runs.
552
    can_expedite: bool,
553
    /// Where a live run stands among the runners' work.
554
    queue: Option<crate::flow::QueueInfo>,
555
    /// Releases a writer may attach this run's artifacts to.
556
    releases: Vec<db::releases::Release>,
557
    /// Jobs that wait, or waited, for a person (oxygenflow#57).
558
    approvals: Vec<ApprovalView>,
559
}
560
561
/// A job's approval as the run page shows it.
562
pub struct ApprovalView {
563
    pub job: String,
564
    pub by: String,
565
    pub others_only: bool,
566
    /// `waiting`, `approved`, `rejected` or `expired`.
567
    pub state: &'static str,
568
    pub who: String,
569
    pub when_ms: i64,
570
    /// Whether the viewer may approve or reject it now, else why not.
571
    pub may: Result<(), String>,
572
    /// It takes an approval signed with the approver's key (#235): the
573
    /// command that signs it, and the approval's hash once sealed.
574
    pub sealed: bool,
575
    pub command: String,
576
    pub seal: String,
577
}
578
579
impl ApprovalView {
5802×
    pub fn may_decide(&self) -> bool {
5812×
        self.may.is_ok()
5822×
    }
583
5842×
    pub fn why_not(&self) -> String {
5852×
        self.may.clone().err().unwrap_or_default()
5862×
    }
587
}
588
589
/// Lines of a job's log a page shows before "the rest is loaded as it comes".
590
const PAGE_LINES: i64 = 5000;
591
59224×
pub async fn run(
59324×
    State(app): State<Shared>,
59424×
    viewer: Viewer,
59524×
    Path((owner, name, id)): Path<(String, String, i64)>,
59624×
) -> Result<Page<RunPage>, Error> {
59724×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer);
59824×
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
59924×
    let run = fdb::run(&app.db, row.id, id)
60024×
        .await
60124×
        .map_err(|e| Error::from_db(shell.clone(), e))?
60224×
        .ok_or_else(|| Error::not_found(shell.clone()))?;
60323×
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
60423×
    let reports = crate::coverage::for_run(&app.db, run.id).await.unwrap_or_default();
60523×
    let test_reports = crate::junit::for_run(&app.db, run.id).await.unwrap_or_default();
60623×
    let mut logs = Vec::new();
60754×
    for j in &jobs {
60854×
        let lines = fdb::log(&app.db, j.id, 0, PAGE_LINES).await.unwrap_or_default();
60954×
        let last_seq = lines.last().map(|l| l.seq).unwrap_or(0);
61054×
        let artifacts = fdb::artifacts(&app.db, j.id).await.unwrap_or_default();
61154×
        let coverage = reports
61254×
            .iter()
61354×
            .find(|r| r.job_id == Some(j.id))
61454×
            .map(|r| (r.id, r.percent().map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into())));
61554×
        let tests = test_reports.iter().find(|r| r.job_id == j.id).cloned();
61654×
        let failures = match &tests {
6171×
            Some(r) if r.broken() > 0 => crate::junit::failures(&app.db, r.id, SHOWN_FAILURES).await.unwrap_or_default(),
61853×
            _ => vec![],
619
        };
62054×
        let segments = sections(&lines);
62154×
        logs.push(JobLog {
62254×
            duration: crate::flow::duration(j),
62354×
            j: j.clone(),
62454×
            artifacts,
62554×
            lines,
62654×
            segments,
62754×
            last_seq,
62854×
            coverage,
62954×
            tests,
63054×
            failures,
63154×
        });
632
    }
63323×
    let duration = match run.finished_ms {
63411×
        Some(f) => crate::flow::human_ms(f - run.created_ms),
63512×
        None => crate::flow::human_ms(db::now_ms() - run.created_ms),
636
    };
63723×
    let mut approvals = Vec::new();
63854×
    for j in jobs.iter().filter(|j| !j.approval.is_empty()) {
6394×
        let Some(a) = serde_json::from_str::<flow_core::Job>(&j.spec).ok().and_then(|s| s.approval) else { continue };
6404×
        let state = match (j.approval.as_str(), j.status.as_str()) {
6414×
            ("waiting", "queued") => "waiting",
6422×
            ("approved", _) => "approved",
6430×
            (_, "cancelled") if !j.approved_by.is_empty() => "rejected",
6440×
            (_, "cancelled") if j.error.starts_with("no approval within") => "expired",
6450×
            _ => continue,
646
        };
6474×
        let may = match (state, viewer.account()) {
6484×
            ("waiting", Some(me)) => crate::flow::may_decide(&app, &row, &run, j, me).await.map(|_| ()),
6492×
            ("waiting", None) => Err("sign in to approve".into()),
6502×
            _ => Err(String::new()),
651
        };
6524×
        approvals.push(ApprovalView {
6534×
            sealed: a.sealed,
6544×
            command: format!("oxy seal --flow {}/{owner}/{name}/flow/{} --job {}", app.config.base_url(), run.number, j.name),
6554×
            seal: j.approval_seal.clone(),
6564×
            job: j.name.clone(),
6574×
            by: a.by,
6584×
            others_only: a.others_only,
6594×
            state,
6604×
            who: if j.approved_via.is_empty() { j.approved_by.clone() } else { format!("{} via {}", j.approved_by, j.approved_via) },
6614×
            when_ms: j.approved_ms.unwrap_or(0),
6624×
            may,
663
        });
664
    }
66523×
    let graph = layout(jobs);
66623×
    let can_write = viewer.account().is_some() && role >= Role::Write;
66723×
    let can_rerun = !run.live() && can_write && crate::flow::enabled(&app, &row);
66823×
    let can_cancel = run.live() && can_write;
66923×
    let can_expedite = run.live() && run.priority.is_empty() && viewer.account().is_some() && role >= Role::Maintain;
67023×
    let queue = if run.live() {
67112×
        let q = fdb::queue(&app.db).await.unwrap_or_default();
67212×
        Some(crate::flow::queue_info(&q, row.id, run.id)).filter(|i| i.position.is_some())
673
    } else {
67411×
        None
675
    };
67623×
    let releases = if viewer.account().is_some() && role >= Role::Write && logs.iter().any(|l| !l.artifacts.is_empty()) {
6771×
        db::releases::list(&app.db, row.id).await.unwrap_or_default()
678
    } else {
67922×
        vec![]
680
    };
68123×
    Ok(Page(RunPage {
68223×
        shell,
68323×
        repo: RepoShell::new(&app, &row, "flow").with_role(role),
68423×
        run,
68523×
        graph,
68623×
        logs,
68723×
        duration,
68823×
        can_rerun,
68923×
        can_cancel,
69023×
        can_expedite,
69123×
        queue,
69223×
        releases,
69323×
        approvals,
69423×
    }))
69524×
}
696
697
#[derive(Deserialize)]
698
pub struct DecideForm {
699
    #[serde(rename = "_csrf")]
700
    csrf_token: String,
701
    /// `approve` or `reject`.
702
    action: String,
703
}
704
705
/// `POST /{owner}/{name}/flow/{id}/jobs/{job}/decide`: approve or reject
706
/// a job that waits for a person (oxygenflow#57).
7070×
pub async fn decide(
7080×
    State(app): State<Shared>,
7090×
    viewer: Viewer,
7100×
    Path((owner, name, number, job)): Path<(String, String, i64, String)>,
7110×
    Form(f): Form<DecideForm>,
7120×
) -> Result<Response, Error> {
7130×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
7140×
    let me = require(&viewer, &shell)?;
7150×
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
7160×
    csrf(&viewer, &f.csrf_token, &shell)?;
7170×
    let run = fdb::run(&app.db, row.id, number)
7180×
        .await
7190×
        .map_err(|e| Error::from_db(shell.clone(), e))?
7200×
        .ok_or_else(|| Error::not_found(shell.clone()))?;
7210×
    let approve = match f.action.as_str() {
7220×
        "approve" => true,
7230×
        "reject" => false,
7240×
        _ => return Err(Error::bad(shell, "approve or reject")),
725
    };
7260×
    match crate::flow::decide(&app, &row, &run, &job, &me.account, approve, None).await {
7270×
        Ok(_) => Ok(Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response()),
7280×
        Err(why) => Err(Error::bad(shell, why)),
729
    }
7300×
}
731
732
#[derive(Deserialize)]
733
pub struct LiveQuery {
734
    /// `job:seq,job:seq`: the last log line each open job already shows.
735
    after: Option<String>,
736
}
737
738
/// `GET /{owner}/{name}/flow/{id}/live`: statuses and new log lines, for the
739
/// run page while it is live.
7401×
pub async fn live(
7411×
    State(app): State<Shared>,
7421×
    viewer: Viewer,
7431×
    Path((owner, name, id)): Path<(String, String, i64)>,
7441×
    Query(q): Query<LiveQuery>,
7451×
) -> Result<Response, Error> {
7461×
    let shell = Shell::new(&app, "", &viewer);
7471×
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
7481×
    let run = fdb::run(&app.db, row.id, id)
7491×
        .await
7501×
        .map_err(|e| Error::from_db(shell.clone(), e))?
7511×
        .ok_or_else(|| Error::not_found(shell.clone()))?;
7521×
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
7531×
    let after: std::collections::HashMap<i64, i64> = q
7541×
        .after
7551×
        .unwrap_or_default()
7561×
        .split(',')
7571×
        .filter_map(|p| p.split_once(':'))
7581×
        .filter_map(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))
7591×
        .collect();
7601×
    let mut out = Vec::new();
7613×
    for j in &jobs {
7623×
        let lines = match after.get(&j.id) {
7631×
            Some(seq) => fdb::log(&app.db, j.id, *seq, 1000).await.unwrap_or_default(),
7642×
            None => vec![],
765
        };
7663×
        out.push(serde_json::json!({
7673×
            "id": j.id,
7683×
            "name": j.name,
7693×
            "status": j.status,
7703×
            "glyph": glyph(&j.status),
7713×
            "duration": crate::flow::duration(j),
7723×
            "exit_code": j.exit_code,
7733×
            "lines": lines.iter().map(|l| serde_json::json!({ "seq": l.seq, "t": l.t, "stream": l.stream, "text": l.text })).collect::<Vec<_>>(),
774
        }));
775
    }
7761×
    Ok(Json(serde_json::json!({ "status": run.status, "live": run.live(), "jobs": out })).into_response())
7771×
}
778
779
// ------------------------------------------------------------ state stamps
780
781
/// In rendered Markdown, the image path that is the viewed state's stamp.
782
pub const STAMP_IMAGE: &str = ".flow/stamp";
783
/// In rendered Markdown, the link path to the viewed state's run.
784
pub const RUN_LINK: &str = ".flow/run";
785
786
/// Resolve a ref to its state address, and whether the ref can move.
7878×
async fn state_of(app: &Shared, owner: &str, name: &str, r: &str) -> Result<(String, bool), crate::repos::RepoError> {
7888×
    let repo = crate::repos::RepoName::new(owner, name).ok_or(crate::repos::RepoError::NotFound)?;
7898×
    let spec = r.to_string();
7908×
    app.repos
7918×
        .read(&repo, move |repo, cache| {
7928×
            let t = crate::repos::view::resolve(repo, cache, &spec)?;
7938×
            let moves = matches!(t.kind, crate::repos::view::RefKind::Bookmark | crate::repos::view::RefKind::Tag);
7948×
            Ok((t.permalink().unwrap_or_default(), moves))
7958×
        })
7968×
        .await
7978×
}
798
799
/// `GET /{owner}/{name}/flow/stamp/{ref}` (hub spec §13.2).
8006×
pub async fn stamp(
8016×
    State(app): State<Shared>,
8026×
    viewer: Viewer,
8036×
    Path((owner, name, r)): Path<(String, String, String)>,
8046×
) -> Result<Response, Error> {
8056×
    let shell = Shell::new(&app, "", &viewer);
8066×
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
8076×
    let (heads, moves) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
8086×
    if moves && !heads.is_empty() {
8092×
        let mut res = axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{heads}")).into_response();
8102×
        res.headers_mut().insert(axum::http::header::CACHE_CONTROL, axum::http::HeaderValue::from_static("no-cache"));
8112×
        return Ok(res);
8124×
    }
8134×
    let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?;
8144×
    let jobs = match &run {
8153×
        Some(r) => fdb::jobs(&app.db, r.id).await.map_err(|e| Error::from_db(shell.clone(), e))?,
8161×
        None => vec![],
817
    };
8184×
    let svg = stamp_svg(&heads, run.as_ref(), &jobs);
8194×
    let cache = if run.as_ref().is_some_and(|r| !r.live()) { "public, max-age=3600" } else { "public, max-age=60" };
8204×
    Ok((
8214×
        [
8224×
            (axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"),
8234×
            (axum::http::header::CACHE_CONTROL, cache),
8244×
            (axum::http::header::CONTENT_SECURITY_POLICY, "default-src 'none'; style-src 'unsafe-inline'"),
8254×
        ],
8264×
        svg,
8274×
    )
8284×
        .into_response())
8296×
}
830
831
/// `GET /{owner}/{name}/flow/at/{ref}`: the run of the ref's state, or the Flow tab.
8322×
pub async fn at(
8332×
    State(app): State<Shared>,
8342×
    viewer: Viewer,
8352×
    Path((owner, name, r)): Path<(String, String, String)>,
8362×
) -> Result<Response, Error> {
8372×
    let shell = Shell::new(&app, "", &viewer);
8382×
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
8392×
    let (heads, _) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
8402×
    let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?;
8412×
    let to = match run {
8421×
        Some(r) => format!("/{owner}/{name}/flow/{}", r.number),
8431×
        None => format!("/{owner}/{name}/flow"),
844
    };
8452×
    Ok(axum::response::Redirect::to(&to).into_response())
8462×
}
847
84812×
fn xml(s: &str) -> String {
84912×
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
85012×
}
851
852
/// The stamp: the mark, one glyph per job, the status, the state and the
853
/// date; the same facts machine-readable in `<metadata>`. Fixed colours,
854
/// because an image does not follow the page's theme.
8554×
pub fn stamp_svg(heads: &str, run: Option<&fdb::Run>, jobs: &[fdb::Job]) -> String {
856
    const CH: f64 = 6.6; // IBM Plex Mono at 11px
8577×
    let colour = |s: &str| match s {
8587×
        "passed" => "#5fe3a1",
8595×
        "failed" | "error" => "#ff5e7a",
8601×
        "running" => "#00e0f0",
8611×
        _ => "#8592ad",
8627×
    };
8634×
    let short: String = heads.chars().take(12).collect();
8644×
    let (status, date) = match run {
8653×
        Some(r) => (r.status.as_str(), crate::render::time::absolute(r.created_ms as u64).chars().take(10).collect::<String>()),
8661×
        None => ("no run", String::new()),
867
    };
8684×
    let mut ordered: Vec<&fdb::Job> = jobs.iter().collect();
8694×
    ordered.sort_by(|a, b| (a.depth, &a.name).cmp(&(b.depth, &b.name)));
8704×
    let label = "OXYGENFLOW";
8714×
    let label_w = 18.0 + label.len() as f64 * 7.4 + 8.0; // Barlow bold 10.5px, spaced
8724×
    let glyphs_w = if ordered.is_empty() { 0.0 } else { ordered.len() as f64 * 10.0 + 6.0 };
8734×
    let tail = if date.is_empty() { format!("{status} · {short}") } else { format!("{status} · {short} · {date}") };
8744×
    let right_w = 8.0 + glyphs_w + tail.chars().count() as f64 * CH + 8.0;
8754×
    let w = (label_w + right_w).ceil();
8764×
    let mut glyphs = String::new();
8774×
    for (i, j) in ordered.iter().enumerate() {
8783×
        let x = label_w + 8.0 + i as f64 * 10.0 + 4.0;
8793×
        glyphs.push_str(&format!(
8803×
            r#"<text x="{x:.1}" y="15" fill="{}" text-anchor="middle">{}</text>"#,
8813×
            colour(&j.status),
8823×
            glyph(&j.status)
8833×
        ));
8843×
    }
8854×
    let meta = serde_json::json!({
88610×
        "heads": heads.split('+').filter(|h| !h.is_empty()).collect::<Vec<_>>(),
8874×
        "run": run.map(|r| r.number),
8884×
        "status": status,
8894×
        "jobs": ordered.iter().map(|j| serde_json::json!({ "name": j.name, "status": j.status, "receipt": j.receipt_hash })).collect::<Vec<_>>(),
890
    });
8914×
    let title = match run {
8923×
        Some(r) => format!("OxygenFlow run #{} {status} on state {short}", r.number),
8931×
        None => format!("OxygenFlow: no run for state {short}"),
894
    };
8954×
    format!(
896
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="22" viewBox="0 0 {w} 22" role="img" aria-label="{t}"><title>{t}</title><metadata>{m}</metadata><rect width="{w}" height="22" rx="4" fill="#0e1526"/><rect width="{lw:.1}" height="22" rx="4" fill="#0b3f9e"/><rect x="{lx:.1}" width="4" height="22" fill="#0b3f9e"/><circle cx="9" cy="11" r="3.2" fill="none" stroke="#00f0ff" stroke-width="1.6"/><text x="16" y="15" fill="#ffffff" font-family="Barlow, Verdana, sans-serif" font-size="10.5" font-weight="700" letter-spacing=".6">{label}</text><g font-family="IBM Plex Mono, ui-monospace, monospace" font-size="11">{glyphs}<text x="{tx:.1}" y="15" fill="{sc}">{tail}</text></g><rect x=".5" y=".5" width="{wi}" height="21" rx="3.5" fill="none" stroke="#1f2b47"/></svg>"##,
8974×
        t = xml(&title),
8984×
        m = xml(&meta.to_string()),
899
        lw = label_w,
9004×
        lx = label_w - 4.0,
9014×
        tx = label_w + 8.0 + glyphs_w,
9024×
        sc = colour(status),
9034×
        tail = xml(&tail),
9044×
        wi = w - 1.0,
905
    )
9064×
}
907
908
/// A receipt kept in a repository (Oxygen spec §14.6), as pages show it.
909
#[derive(Clone, Debug)]
910
pub struct ReceiptRow {
911
    pub attest: String,
912
    pub job: String,
913
    pub exit_code: u32,
914
    pub duration: String,
915
    pub runner: String,
916
    pub run: String,
917
    /// Why it does not verify, or that its runner's key was revoked.
918
    pub problem: String,
919
    pub made_ms: i64,
920
}
921
922
impl ReceiptRow {
9233×
    pub fn passed(&self) -> bool {
9243×
        self.exit_code == 0
9253×
    }
926
}
927
928
/// The receipts kept for the state of `heads`.
92913×
pub async fn receipts_of(app: &Shared, name: &crate::repos::RepoName, heads: Vec<oxy_core::hash::ChangeHash>) -> Vec<ReceiptRow> {
93013×
    let base = app.config.base_url();
93113×
    let found = app.repos.read(name, move |repo, _| Ok(repo.receipts(&heads)?)).await.unwrap_or_default();
93213×
    found
93313×
        .into_iter()
93413×
        .map(|i| {
9351×
            let r = &i.signed.receipt;
9361×
            let run = i.signed.run().to_string();
937
            ReceiptRow {
9381×
                attest: i.attest.to_hex(),
9391×
                job: r.job_name.clone(),
9401×
                exit_code: r.exit_code,
9411×
                duration: crate::flow::human_ms(r.duration_ms as i64),
9421×
                runner: i.signed.runner.name.clone(),
943
                // Only links to this hub are followed from the page.
9441×
                run: if run.starts_with(base) { run } else { String::new() },
9451×
                problem: match (i.problem, i.revoked) {
9460×
                    (Some(p), _) => p,
9470×
                    (None, true) => "the runner's key was revoked".into(),
9481×
                    (None, false) => String::new(),
949
                },
9501×
                made_ms: i.signed.attest.hlc.wall_ms as i64,
951
            }
9521×
        })
95313×
        .collect()
95413×
}
955
956
/// `GET /{owner}/{name}/receipts/{attest}`: a signed receipt, for
957
/// `oxy receipt verify` or `oxy receipt import`.
9582×
pub async fn receipt_file(
9592×
    State(app): State<Shared>,
9602×
    viewer: Viewer,
9612×
    Path((owner, name, attest)): Path<(String, String, String)>,
9622×
) -> Result<Response, Error> {
9632×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/receipts/{attest}"), &viewer);
9642×
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
9652×
    let Some(r) = oxy_core::hash::ObjectRef::from_hex(attest.trim_end_matches(".receipt")) else {
9660×
        return Err(Error::not_found(shell));
967
    };
9682×
    let (job, bytes) = app
9692×
        .repos
9702×
        .read(&repo, move |repo, _| {
9712×
            let i = repo.receipt(&r)?;
9721×
            Ok((i.signed.receipt.job_name.clone(), i.signed.encode()))
9732×
        })
9742×
        .await
9752×
        .map_err(|_| Error::not_found(shell.clone()))?;
9765×
    let file: String = job.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')).collect();
9771×
    Ok((
9781×
        [
9791×
            (axum::http::header::CONTENT_TYPE, "application/oxy-receipt".to_string()),
9801×
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{file}-{}.receipt\"", r.short(12))),
9811×
        ],
9821×
        bytes,
9831×
    )
9841×
        .into_response())
9852×
}
986
987
/// `GET /{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}`: an artifact
988
/// of a run's job, read from the repository.
9893×
pub async fn artifact_file(
9903×
    State(app): State<Shared>,
9913×
    viewer: Viewer,
9923×
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
9933×
) -> Result<Response, Error> {
9943×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}"), &viewer);
9953×
    let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
9963×
    let run = fdb::run(&app.db, row.id, id)
9973×
        .await
9983×
        .map_err(|e| Error::from_db(shell.clone(), e))?
9993×
        .ok_or_else(|| Error::not_found(shell.clone()))?;
10003×
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
10013×
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
10023×
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
10033×
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
10042×
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
10052×
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|_| Error::not_found(shell.clone()))?;
10062×
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
10072×
    Ok((
10082×
        [
10092×
            (axum::http::header::CONTENT_TYPE, "application/octet-stream".to_string()),
10102×
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}\"", file.replace('"', ""))),
10112×
        ],
10122×
        bytes,
10132×
    )
10142×
        .into_response())
10153×
}
1016
1017
/// `GET …/artifacts/{job}/{artifact}/provenance` (oxygenhub#239): the
1018
/// artifact's SLSA provenance in a DSSE envelope signed by the hub, for
1019
/// `cosign verify-blob-attestation --key oxyhub-signing.pem --type
1020
/// slsaprovenance1`. Only for a job whose signed receipt the hub kept.
10212×
pub async fn provenance(
10222×
    State(app): State<Shared>,
10232×
    viewer: Viewer,
10242×
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
10252×
) -> Result<Response, Error> {
10262×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/provenance"), &viewer);
10272×
    let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
10282×
    let run = fdb::run(&app.db, row.id, id)
10292×
        .await
10302×
        .map_err(|e| Error::from_db(shell.clone(), e))?
10312×
        .ok_or_else(|| Error::not_found(shell.clone()))?;
10322×
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
10332×
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
10342×
    if j.receipt_attest.is_empty() {
10351×
        return Err(Error::bad(shell, "This job has no signed receipt the hub kept, so the hub states no provenance for it.".to_string()));
10361×
    }
10371×
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
10381×
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
10391×
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
10401×
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|_| Error::not_found(shell.clone()))?;
10411×
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
10421×
    let base = app.config.base_url();
10431×
    let subject = crate::provenance::Subject {
10441×
        name: &file,
10451×
        bytes: &bytes,
10461×
        repo: &format!("{owner}/{name}"),
10471×
        run_url: &format!("{base}/{owner}/{name}/flow/{id}"),
10481×
        bookmark: &run.bookmark,
10491×
        state: &run.state,
10501×
        heads: &run.heads,
10511×
        pipeline_hash: &run.pipeline_hash,
10521×
        job: &j.name,
10531×
        runner: &j.runner,
10541×
        receipt_signer: &j.receipt_signer,
10551×
        receipt_attest: &j.receipt_attest,
10561×
        started_ms: j.started_ms,
10571×
        finished_ms: j.finished_ms,
10581×
    };
10591×
    let statement = crate::provenance::statement(base, &subject);
10601×
    let envelope = crate::provenance::envelope(&app, &statement).map_err(|e| Error::bad(shell.clone(), e.to_string()))?;
10611×
    Ok((
10621×
        [
10631×
            (axum::http::header::CONTENT_TYPE, "application/json".to_string()),
10641×
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}.intoto.json\"", file.replace('"', ""))),
10651×
        ],
10661×
        serde_json::to_string(&envelope).unwrap_or_default(),
10671×
    )
10681×
        .into_response())
10692×
}
1070
1071
/// `GET /.well-known/oxyhub-signing.pem`: the hub's Ed25519 public key, as
1072
/// cosign and other verifiers take it (oxygenhub#239).
10731×
pub async fn signing_key(State(app): State<Shared>) -> Response {
10741×
    ([(axum::http::header::CONTENT_TYPE, "application/x-pem-file")], crate::provenance::public_pem(&app)).into_response()
10751×
}
1076
1077
#[derive(Deserialize)]
1078
pub struct AttachForm {
1079
    _csrf: String,
1080
    release: i64,
1081
}
1082
1083
/// `POST /{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/attach`: add
1084
/// an artifact to a release as an asset, named after its path; the release
1085
/// page then shows the run and receipt that built it.
10861×
pub async fn attach(
10871×
    State(app): State<Shared>,
10881×
    viewer: Viewer,
10891×
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
10901×
    Form(f): Form<AttachForm>,
10911×
) -> Result<Response, Error> {
10921×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer);
10931×
    require(&viewer, &shell)?;
10941×
    csrf(&viewer, &f._csrf, &shell)?;
10951×
    let (repo, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
10961×
    let run = fdb::run(&app.db, row.id, id)
10971×
        .await
10981×
        .map_err(|e| Error::from_db(shell.clone(), e))?
10991×
        .ok_or_else(|| Error::not_found(shell.clone()))?;
11001×
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
11011×
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
1102
    // A failing job's `when "always"` artifacts are not in its receipt, so
1103
    // they cannot stand for a release (oxygenflow#37).
11041×
    if j.status != "passed" {
11050×
        return Err(Error::bad(shell, "only a passing job's artifacts can be attached to a release"));
11061×
    }
11071×
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
11081×
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
11091×
    let releases = db::releases::list(&app.db, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
11101×
    let Some(rel) = releases.into_iter().find(|r| r.id == f.release) else { return Err(Error::not_found(shell)) };
11111×
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
11121×
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
11131×
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
11141×
    super::releases::store_asset(&app, rel.id, &file, "application/octet-stream", &bytes)
11151×
        .await
11161×
        .map_err(|m| Error::bad(shell.clone(), m))?;
11171×
    Ok(Redirect::to(&format!("/{owner}/{name}/releases/tag/{}", rel.tag)).into_response())
11181×
}
1119
1120
/// `/{owner}/{name}/flow/badge.svg`: the latest run on the default
1121
/// bookmark as a small SVG for a README, for whoever may read the
1122
/// repository. `passed` green, `failed` or `error` red, a run still going
1123
/// blue, none grey.
11241×
pub async fn badge(
11251×
    State(app): State<Shared>,
11261×
    viewer: Viewer,
11271×
    Path((owner, name)): Path<(String, String)>,
11281×
) -> Result<axum::response::Response, Error> {
1129
    use axum::response::IntoResponse;
11301×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
11311×
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
11321×
    let latest = fdb::latest_on(&app.db, row.id, &row.default_bookmark).await.map_err(|e| Error::from_db(shell.clone(), e))?;
11331×
    let (text, colour) = match latest.as_ref().map(|r| r.status.as_str()) {
11340×
        Some("passed") => ("passing", "#2da44e"),
11350×
        Some("failed") | Some("error") => ("failing", "#cf222e"),
11360×
        Some("cancelled") => ("cancelled", "#6e7781"),
11370×
        Some(_) => ("running", "#0969da"),
11381×
        None => ("no runs", "#6e7781"),
1139
    };
11401×
    let label = "OxygenFlow";
11411×
    let (lw, tw) = (label.len() as u32 * 7 + 10, text.len() as u32 * 7 + 10);
11421×
    let svg = format!(
1143
        r##"<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="20" role="img" aria-label="{label}: {text}"><title>{label}: {text}</title><rect width="{lw}" height="20" rx="3" fill="#555"/><rect x="{lw}" width="{tw}" height="20" rx="3" fill="{colour}"/><rect x="{lw}" width="4" height="20" fill="{colour}"/><g fill="#fff" font-family="Verdana,DejaVu Sans,sans-serif" font-size="11" text-anchor="middle"><text x="{lx}" y="14">{label}</text><text x="{tx}" y="14">{text}</text></g></svg>"##,
11441×
        w = lw + tw,
11451×
        lx = lw / 2,
11461×
        tx = lw + tw / 2,
1147
    );
11481×
    Ok((
11491×
        [(axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"), (axum::http::header::CACHE_CONTROL, "no-cache, max-age=60")],
11501×
        svg,
11511×
    )
11521×
        .into_response())
11531×
}
1154
1155
#[cfg(test)]
1156
mod section_tests {
1157
    use super::*;
1158
11599×
    fn line(seq: i64, t: i64, text: &str) -> fdb::LogLine {
11609×
        fdb::LogLine { seq, t, stream: "out".into(), text: text.into() }
11619×
    }
1162
1163
    #[test]
11641×
    fn marked_lines_fold_into_sections() {
11651×
        let lines = vec![
11661×
            line(1, 0, "booting"),
11671×
            line(2, 100, "::group::cargo build"),
11681×
            line(3, 200, "Compiling a"),
11691×
            line(4, 900, "Compiling b"),
11701×
            line(5, 4_300, "::endgroup::"),
11711×
            line(6, 4_400, "::group::cargo test"),
11721×
            line(7, 4_500, "test x ... ok"),
11731×
            line(8, 5_000, "::group::lint"),
11741×
            line(9, 5_100, "clean"),
1175
        ];
11761×
        let segs = sections(&lines);
11771×
        assert_eq!(segs.len(), 4);
11781×
        assert!(matches!(&segs[0], Segment::Line(l) if l.text == "booting"));
11791×
        let Segment::Group(build) = &segs[1] else { panic!("a section") };
11801×
        assert_eq!((build.title.as_str(), build.from_t, build.to_t, build.lines.len()), ("cargo build", 100, Some(4_300), 2));
11811×
        let Segment::Group(test) = &segs[2] else { panic!("a section") };
11821×
        assert_eq!(test.to_t, Some(5_000), "a new section ends the one before");
11831×
        let Segment::Group(lint) = &segs[3] else { panic!("a section") };
11841×
        assert_eq!((lint.to_t, lint.lines.len()), (None, 1), "still going");
11851×
        assert_eq!(secs(4_200), "4.2s");
11861×
    }
1187
}