OXYGENHUB
◆ proposal-list-fast oxygenhub / crates / hub / src / web / flow.rs
46.8 KiB · Rust · last changed Expediting a run moves the queue at once (closes #291) 11 days ago source blame history raw
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.
47
pub fn why_not_run(enabled: bool, signed_in: bool, role: Role) -> Option<String> {
48
    if !enabled {
49
        Some("Flow is off for this repository; a site administrator can turn it on in Settings › Pipelines.".into())
50
    } else if !signed_in {
51
        Some("Sign in with write access to run the pipeline.".into())
52
    } else if role < Role::Write {
53
        Some("Running the pipeline needs write access to this repository.".into())
54
    } else {
55
        None
56
    }
57
}
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).
74
pub async fn deployments(
75
    State(app): State<Shared>,
76
    viewer: Viewer,
77
    Path((owner, name)): Path<(String, String)>,
78
) -> Result<Page<DeploymentsPage>, Error> {
79
    let shell = Shell::new(&app, &format!("/{owner}/{name}/deployments"), &viewer);
80
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
81
    let history = fdb::deployments(&app.db, row.id, 50).await.map_err(|e| Error::from_db(shell.clone(), e))?;
82
    let mut current: Vec<fdb::Deployment> = Vec::new();
83
    for d in &history {
84
        if !current.iter().any(|c| c.environment == d.environment) {
85
            current.push(d.clone());
86
        }
87
    }
88
    current.sort_by(|a, b| a.environment.cmp(&b.environment));
89
    Ok(Page(DeploymentsPage { shell, repo: RepoShell::new(&app, &row, "flow").with_role(role), current, history }))
90
}
91
92
pub async fn runs(
93
    State(app): State<Shared>,
94
    viewer: Viewer,
95
    Path((owner, name)): Path<(String, String)>,
96
    Query(q): Query<RunsQuery>,
97
) -> Result<Page<RunsPage>, Error> {
98
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
99
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
100
    let list = fdb::runs(&app.db, row.id, PER_PAGE + 1, q.before).await.map_err(|e| Error::from_db(shell.clone(), e))?;
101
    let older = (list.len() as i64 > PER_PAGE).then(|| list[PER_PAGE as usize - 1].id);
102
    let queue = if list.iter().any(|r| r.live()) { fdb::queue(&app.db).await.unwrap_or_default() } else { vec![] };
103
    let mut runs = Vec::new();
104
    for r in list.into_iter().take(PER_PAGE as usize) {
105
        let place = if r.live() { crate::flow::queue_info(&queue, row.id, r.id).place() } else { None };
106
        let jobs = fdb::jobs(&app.db, r.id).await.unwrap_or_default();
107
        let duration = match r.finished_ms {
108
            Some(f) => crate::flow::human_ms(f - r.created_ms),
109
            None if r.live() => crate::flow::human_ms(db::now_ms() - r.created_ms),
110
            None => "–".into(),
111
        };
112
        runs.push(RunRow { jobs: jobs.into_iter().map(|j| (j.name, j.status)).collect(), duration, r, place });
113
    }
114
    let enabled = crate::flow::enabled(&app, &row);
115
    let why_not = why_not_run(enabled, viewer.account().is_some(), role);
116
    let can_run = why_not.is_none();
117
    let bookmarks = if can_run { bookmark_names(&app, &row).await } else { vec![] };
118
    Ok(Page(RunsPage {
119
        shell,
120
        repo: RepoShell::new(&app, &row, "flow").with_role(role),
121
        runs,
122
        enabled,
123
        older,
124
        can_run,
125
        bookmarks,
126
        error: q.error,
127
        why_not,
128
    }))
129
}
130
131
/// The repository's bookmarks, its default first.
132
async fn bookmark_names(app: &Shared, row: &db::repos::RepoRow) -> Vec<String> {
133
    let Some(repo) = crate::repos::RepoName::new(&row.owner, &row.name) else { return vec![] };
134
    let mut names: Vec<String> = app.repos.read(&repo, |r, _| Ok(r.view()?.bookmarks.keys().cloned().collect())).await.unwrap_or_default();
135
    names.sort_by_key(|n| (n != &row.default_bookmark, n.clone()));
136
    names
137
}
138
139
#[derive(Deserialize)]
140
pub struct StartForm {
141
    #[serde(rename = "_csrf")]
142
    csrf_token: String,
143
    #[serde(default)]
144
    bookmark: String,
145
    /// A change's full hash: run the state whose only head it is.
146
    #[serde(default)]
147
    change: String,
148
}
149
150
/// `POST /{owner}/{name}/flow/start`: "Run pipeline" on a bookmark's
151
/// current state, or on one committed change.
152
pub async fn start(
153
    State(app): State<Shared>,
154
    viewer: Viewer,
155
    Path((owner, name)): Path<(String, String)>,
156
    Form(f): Form<StartForm>,
157
) -> Result<Response, Error> {
158
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
159
    let me = require(&viewer, &shell)?;
160
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
161
    csrf(&viewer, &f.csrf_token, &shell)?;
162
    let (started, what) = if f.change.trim().is_empty() {
163
        (crate::flow::run_bookmark(&app, &row, f.bookmark.trim(), &me.account.username, &[]).await, f.bookmark.trim().to_string())
164
    } else {
165
        (crate::flow::run_change(&app, &row, &f.change, &me.account.username, &[]).await, format!("change {}", f.change.trim()))
166
    };
167
    Ok(match started {
168
        Ok(n) => {
169
            db::accounts::audit(&app.db, Some(&me.account), "flow.run", &format!("{owner}/{name}"), &format!("#{n} {what}")).await.ok();
170
            Redirect::to(&format!("/{owner}/{name}/flow/{n}")).into_response()
171
        }
172
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
173
    })
174
}
175
176
#[derive(Deserialize)]
177
pub struct RerunForm {
178
    #[serde(rename = "_csrf")]
179
    csrf_token: String,
180
}
181
182
/// `POST /{owner}/{name}/flow/{number}/rerun`.
183
pub async fn rerun(
184
    State(app): State<Shared>,
185
    viewer: Viewer,
186
    Path((owner, name, number)): Path<(String, String, i64)>,
187
    Form(f): Form<RerunForm>,
188
) -> Result<Response, Error> {
189
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
190
    let me = require(&viewer, &shell)?;
191
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
192
    csrf(&viewer, &f.csrf_token, &shell)?;
193
    let run = fdb::run(&app.db, row.id, number)
194
        .await
195
        .map_err(|e| Error::from_db(shell.clone(), e))?
196
        .ok_or_else(|| Error::not_found(shell.clone()))?;
197
    Ok(match crate::flow::rerun(&app, &row, &run, &me.account.username).await {
198
        Ok(n) => {
199
            db::accounts::audit(&app.db, Some(&me.account), "flow.rerun", &format!("{owner}/{name}"), &format!("#{n} of #{number}"))
200
                .await
201
                .ok();
202
            Redirect::to(&format!("/{owner}/{name}/flow/{n}")).into_response()
203
        }
204
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
205
    })
206
}
207
208
/// `POST /{owner}/{name}/flow/{number}/jobs/{job}/rerun` (oxygenflow#31).
209
pub async fn rerun_job(
210
    State(app): State<Shared>,
211
    viewer: Viewer,
212
    Path((owner, name, number, job)): Path<(String, String, i64, String)>,
213
    Form(f): Form<RerunForm>,
214
) -> Result<Response, Error> {
215
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
216
    let me = require(&viewer, &shell)?;
217
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
218
    csrf(&viewer, &f.csrf_token, &shell)?;
219
    let run = fdb::run(&app.db, row.id, number)
220
        .await
221
        .map_err(|e| Error::from_db(shell.clone(), e))?
222
        .ok_or_else(|| Error::not_found(shell.clone()))?;
223
    Ok(match crate::flow::rerun_job(&app, &row, &run, &job, &me.account.username).await {
224
        Ok(_) => {
225
            db::accounts::audit(&app.db, Some(&me.account), "flow.rerun", &format!("{owner}/{name}"), &format!("{job} of #{number}"))
226
                .await
227
                .ok();
228
            Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response()
229
        }
230
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
231
    })
232
}
233
234
/// `POST /{owner}/{name}/flow/{number}/cancel` (oxygenflow#32).
235
pub async fn cancel(
236
    State(app): State<Shared>,
237
    viewer: Viewer,
238
    Path((owner, name, number)): Path<(String, String, i64)>,
239
    Form(f): Form<RerunForm>,
240
) -> Result<Response, Error> {
241
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
242
    let me = require(&viewer, &shell)?;
243
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
244
    csrf(&viewer, &f.csrf_token, &shell)?;
245
    let run = fdb::run(&app.db, row.id, number)
246
        .await
247
        .map_err(|e| Error::from_db(shell.clone(), e))?
248
        .ok_or_else(|| Error::not_found(shell.clone()))?;
249
    Ok(match crate::flow::cancel(&app, &row, &run, &me.account.username).await {
250
        Ok(()) => {
251
            db::accounts::audit(&app.db, Some(&me.account), "flow.cancel", &format!("{owner}/{name}"), &format!("#{number}")).await.ok();
252
            Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response()
253
        }
254
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
255
    })
256
}
257
258
#[derive(Deserialize)]
259
pub struct ExpediteForm {
260
    #[serde(rename = "_csrf")]
261
    csrf_token: String,
262
    #[serde(default)]
263
    reason: String,
264
}
265
266
/// `POST /{owner}/{repo}/flow/{n}/expedite` (oxygenhub#244): a maintainer
267
/// raises a running or queued run to urgent, saying why (an incident's
268
/// fix, say). Audited and shown on the run; it lapses when the run ends.
269
pub async fn expedite(
270
    State(app): State<Shared>,
271
    viewer: Viewer,
272
    Path((owner, name, number)): Path<(String, String, i64)>,
273
    Form(f): Form<ExpediteForm>,
274
) -> Result<Response, Error> {
275
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
276
    let me = require(&viewer, &shell)?;
277
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Maintain).await?;
278
    csrf(&viewer, &f.csrf_token, &shell)?;
279
    let run = fdb::run(&app.db, row.id, number)
280
        .await
281
        .map_err(|e| Error::from_db(shell.clone(), e))?
282
        .ok_or_else(|| Error::not_found(shell.clone()))?;
283
    let reason: String = f.reason.chars().filter(|c| !c.is_control()).take(200).collect();
284
    let reason = reason.trim();
285
    if reason.is_empty() {
286
        return Ok(Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding("Say why the run is urgent."))).into_response());
287
    }
288
    // A cap on one owner's urgent runs at once (Admin > Runners >
289
    // Settings), so urgent can't starve everyone else.
290
    let cap: i64 = db::accounts::setting(&app.db, "flow_expedite_cap").await.ok().flatten().and_then(|v| v.parse().ok()).unwrap_or(2);
291
    let live = fdb::expedited_live(&app.db, &owner).await.map_err(|e| Error::from_db(shell.clone(), e))?;
292
    if live >= cap {
293
        let msg = format!("{owner} already has {live} expedited run(s) going, the most at once ({cap}); wait for one to end.");
294
        return Ok(Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response());
295
    }
296
    let note = format!("expedited by {}: {reason}", me.account.username);
297
    if fdb::expedite(&app.db, run.id, &note).await.map_err(|e| Error::from_db(shell.clone(), e))? {
298
        db::accounts::audit(&app.db, Some(&me.account), "flow.expedite", &format!("{owner}/{name}"), &format!("#{number}: {reason}"))
299
            .await
300
            .ok();
301
        // Every queued job's place changes now, not at the next pass
302
        // (#291): this run's page and the pages of the runs it moved down
303
        // hear of it.
304
        if let Err(e) = crate::flow::explain_waits(&app).await {
305
            tracing::warn!("flow: placing after an expedite: {e}");
306
        }
307
        app.bus.live(&crate::events::topic::run(run.id), "jobs");
308
    }
309
    Ok(Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response())
310
}
311
312
/// Percent-encode a message for a query string.
313
fn urlencoding(s: &str) -> String {
314
    s.bytes()
315
        .map(|b| match b {
316
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),
317
            _ => format!("%{b:02X}"),
318
        })
319
        .collect()
320
}
321
322
/// A job placed in the graph.
323
pub struct Node {
324
    pub j: fdb::Job,
325
    pub x: i64,
326
    pub y: i64,
327
    pub duration: String,
328
}
329
330
pub struct Edge {
331
    pub d: String,
332
    pub status: String,
333
}
334
335
pub struct Graph {
336
    pub nodes: Vec<Node>,
337
    pub edges: Vec<Edge>,
338
    pub width: i64,
339
    pub height: i64,
340
}
341
342
pub const NODE_W: i64 = 200;
343
pub const NODE_H: i64 = 48;
344
const COL_GAP: i64 = 72;
345
const ROW_GAP: i64 = 18;
346
const PAD: i64 = 12;
347
348
/// Columns by dependency depth, jobs in each column in name order.
349
pub fn layout(jobs: Vec<fdb::Job>) -> Graph {
350
    let mut by_depth: std::collections::BTreeMap<i64, Vec<fdb::Job>> = Default::default();
351
    for j in jobs {
352
        by_depth.entry(j.depth).or_default().push(j);
353
    }
354
    let rows = by_depth.values().map(Vec::len).max().unwrap_or(0) as i64;
355
    let height = PAD * 2 + rows * NODE_H + (rows - 1).max(0) * ROW_GAP;
356
    let mut nodes = Vec::new();
357
    for (col, (_, mut js)) in by_depth.into_iter().enumerate() {
358
        js.sort_by(|a, b| a.name.cmp(&b.name));
359
        let n = js.len() as i64;
360
        let column_h = n * NODE_H + (n - 1).max(0) * ROW_GAP;
361
        let top = (height - column_h) / 2;
362
        for (i, j) in js.into_iter().enumerate() {
363
            let duration = crate::flow::duration(&j);
364
            nodes.push(Node { x: PAD + col as i64 * (NODE_W + COL_GAP), y: top + i as i64 * (NODE_H + ROW_GAP), duration, j });
365
        }
366
    }
367
    let mut edges = Vec::new();
368
    for n in &nodes {
369
        for d in n.j.depends_on() {
370
            if let Some(from) = nodes.iter().find(|m| m.j.name == d) {
371
                let (x1, y1) = (from.x + NODE_W, from.y + NODE_H / 2);
372
                let (x2, y2) = (n.x, n.y + NODE_H / 2);
373
                let mid = (x1 + x2) / 2;
374
                edges.push(Edge { d: format!("M{x1},{y1} C{mid},{y1} {mid},{y2} {x2},{y2}"), status: from.j.status.clone() });
375
            }
376
        }
377
    }
378
    let cols = nodes.iter().map(|n| n.x).max().map(|x| x + NODE_W + PAD).unwrap_or(PAD * 2);
379
    Graph { nodes, edges, width: cols, height: height.max(NODE_H + PAD * 2) }
380
}
381
382
pub fn glyph(status: &str) -> &'static str {
383
    match status {
384
        "passed" => "✓",
385
        "failed" => "✕",
386
        "running" => "●",
387
        "skipped" => "⤼",
388
        "cancelled" => "⊘",
389
        "error" => "!",
390
        _ => "○",
391
    }
392
}
393
394
/// Failed tests a run page lists per job; the rest are counted.
395
const SHOWN_FAILURES: i64 = 50;
396
397
/// A stretch of a job's log as the run page shows it: a line, or a
398
/// section the job marked with `::group::TITLE` … `::endgroup::`
399
/// (oxygenflow#31), shown folded with how long it took.
400
pub enum Segment {
401
    Line(fdb::LogLine),
402
    Group(Section),
403
}
404
405
pub struct Section {
406
    pub title: String,
407
    /// When it began, and ended (`None` while it is still going).
408
    pub from_t: i64,
409
    pub to_t: Option<i64>,
410
    pub lines: Vec<fdb::LogLine>,
411
}
412
413
/// A log's lines in sections. A section left open is still going; a new
414
/// `::group::` ends the one before (sections do not nest).
415
pub fn sections(lines: &[fdb::LogLine]) -> Vec<Segment> {
416
    let mut out: Vec<Segment> = Vec::new();
417
    let mut open: Option<Section> = None;
418
    for l in lines {
419
        if let Some(title) = l.text.strip_prefix("::group::") {
420
            if let Some(g) = open.take() {
421
                out.push(Segment::Group(Section { to_t: Some(l.t), ..g }));
422
            }
423
            open = Some(Section { title: title.trim().to_string(), from_t: l.t, to_t: None, lines: Vec::new() });
424
        } else if l.text.trim() == "::endgroup::" {
425
            if let Some(g) = open.take() {
426
                out.push(Segment::Group(Section { to_t: Some(l.t), ..g }));
427
            }
428
        } else {
429
            match open.as_mut() {
430
                Some(g) => g.lines.push(l.clone()),
431
                None => out.push(Segment::Line(l.clone())),
432
            }
433
        }
434
    }
435
    if let Some(g) = open {
436
        out.push(Segment::Group(g));
437
    }
438
    out
439
}
440
441
/// Milliseconds as the log shows them: `12.3s`.
442
pub fn secs(ms: impl std::borrow::Borrow<i64>) -> String {
443
    let ms = *ms.borrow();
444
    format!("{}.{}s", ms / 1000, ms % 1000 / 100)
445
}
446
447
pub struct JobLog {
448
    pub j: fdb::Job,
449
    pub artifacts: Vec<fdb::Artifact>,
450
    pub lines: Vec<fdb::LogLine>,
451
    /// The lines in sections (oxygenflow#31).
452
    pub segments: Vec<Segment>,
453
    pub duration: String,
454
    /// The last line shown; the live view asks for what follows.
455
    pub last_seq: i64,
456
    /// The job's coverage report, when it uploaded one (#113): its id and percentage.
457
    pub coverage: Option<(i64, String)>,
458
    /// The job's test report, when it uploaded one (#114), and its first
459
    /// failures.
460
    pub tests: Option<crate::junit::Report>,
461
    pub failures: Vec<crate::junit::Case>,
462
}
463
464
#[derive(Template)]
465
#[template(path = "flow_run.html")]
466
pub struct RunPage {
467
    shell: Shell,
468
    repo: RepoShell,
469
    run: fdb::Run,
470
    graph: Graph,
471
    logs: Vec<JobLog>,
472
    duration: String,
473
    /// Whether the viewer may re-run it.
474
    can_rerun: bool,
475
    /// Whether the viewer may cancel it.
476
    can_cancel: bool,
477
    /// May raise the run to urgent (oxygenhub#244): maintainers, while it runs.
478
    can_expedite: bool,
479
    /// Where a live run stands among the runners' work.
480
    queue: Option<crate::flow::QueueInfo>,
481
    /// Releases a writer may attach this run's artifacts to.
482
    releases: Vec<db::releases::Release>,
483
    /// Jobs that wait, or waited, for a person (oxygenflow#57).
484
    approvals: Vec<ApprovalView>,
485
}
486
487
/// A job's approval as the run page shows it.
488
pub struct ApprovalView {
489
    pub job: String,
490
    pub by: String,
491
    pub others_only: bool,
492
    /// `waiting`, `approved`, `rejected` or `expired`.
493
    pub state: &'static str,
494
    pub who: String,
495
    pub when_ms: i64,
496
    /// Whether the viewer may approve or reject it now, else why not.
497
    pub may: Result<(), String>,
498
    /// It takes an approval signed with the approver's key (#235): the
499
    /// command that signs it, and the approval's hash once sealed.
500
    pub sealed: bool,
501
    pub command: String,
502
    pub seal: String,
503
}
504
505
impl ApprovalView {
506
    pub fn may_decide(&self) -> bool {
507
        self.may.is_ok()
508
    }
509
510
    pub fn why_not(&self) -> String {
511
        self.may.clone().err().unwrap_or_default()
512
    }
513
}
514
515
/// Lines of a job's log a page shows before "the rest is loaded as it comes".
516
const PAGE_LINES: i64 = 5000;
517
518
pub async fn run(
519
    State(app): State<Shared>,
520
    viewer: Viewer,
521
    Path((owner, name, id)): Path<(String, String, i64)>,
522
) -> Result<Page<RunPage>, Error> {
523
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer);
524
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
525
    let run = fdb::run(&app.db, row.id, id)
526
        .await
527
        .map_err(|e| Error::from_db(shell.clone(), e))?
528
        .ok_or_else(|| Error::not_found(shell.clone()))?;
529
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
530
    let reports = crate::coverage::for_run(&app.db, run.id).await.unwrap_or_default();
531
    let test_reports = crate::junit::for_run(&app.db, run.id).await.unwrap_or_default();
532
    let mut logs = Vec::new();
533
    for j in &jobs {
534
        let lines = fdb::log(&app.db, j.id, 0, PAGE_LINES).await.unwrap_or_default();
535
        let last_seq = lines.last().map(|l| l.seq).unwrap_or(0);
536
        let artifacts = fdb::artifacts(&app.db, j.id).await.unwrap_or_default();
537
        let coverage = reports
538
            .iter()
539
            .find(|r| r.job_id == Some(j.id))
540
            .map(|r| (r.id, r.percent().map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into())));
541
        let tests = test_reports.iter().find(|r| r.job_id == j.id).cloned();
542
        let failures = match &tests {
543
            Some(r) if r.broken() > 0 => crate::junit::failures(&app.db, r.id, SHOWN_FAILURES).await.unwrap_or_default(),
544
            _ => vec![],
545
        };
546
        let segments = sections(&lines);
547
        logs.push(JobLog {
548
            duration: crate::flow::duration(j),
549
            j: j.clone(),
550
            artifacts,
551
            lines,
552
            segments,
553
            last_seq,
554
            coverage,
555
            tests,
556
            failures,
557
        });
558
    }
559
    let duration = match run.finished_ms {
560
        Some(f) => crate::flow::human_ms(f - run.created_ms),
561
        None => crate::flow::human_ms(db::now_ms() - run.created_ms),
562
    };
563
    let mut approvals = Vec::new();
564
    for j in jobs.iter().filter(|j| !j.approval.is_empty()) {
565
        let Some(a) = serde_json::from_str::<flow_core::Job>(&j.spec).ok().and_then(|s| s.approval) else { continue };
566
        let state = match (j.approval.as_str(), j.status.as_str()) {
567
            ("waiting", "queued") => "waiting",
568
            ("approved", _) => "approved",
569
            (_, "cancelled") if !j.approved_by.is_empty() => "rejected",
570
            (_, "cancelled") if j.error.starts_with("no approval within") => "expired",
571
            _ => continue,
572
        };
573
        let may = match (state, viewer.account()) {
574
            ("waiting", Some(me)) => crate::flow::may_decide(&app, &row, &run, j, me).await.map(|_| ()),
575
            ("waiting", None) => Err("sign in to approve".into()),
576
            _ => Err(String::new()),
577
        };
578
        approvals.push(ApprovalView {
579
            sealed: a.sealed,
580
            command: format!("oxy seal --flow {}/{owner}/{name}/flow/{} --job {}", app.config.base_url(), run.number, j.name),
581
            seal: j.approval_seal.clone(),
582
            job: j.name.clone(),
583
            by: a.by,
584
            others_only: a.others_only,
585
            state,
586
            who: if j.approved_via.is_empty() { j.approved_by.clone() } else { format!("{} via {}", j.approved_by, j.approved_via) },
587
            when_ms: j.approved_ms.unwrap_or(0),
588
            may,
589
        });
590
    }
591
    let graph = layout(jobs);
592
    let can_write = viewer.account().is_some() && role >= Role::Write;
593
    let can_rerun = !run.live() && can_write && crate::flow::enabled(&app, &row);
594
    let can_cancel = run.live() && can_write;
595
    let can_expedite = run.live() && run.priority.is_empty() && viewer.account().is_some() && role >= Role::Maintain;
596
    let queue = if run.live() {
597
        let q = fdb::queue(&app.db).await.unwrap_or_default();
598
        Some(crate::flow::queue_info(&q, row.id, run.id)).filter(|i| i.position.is_some())
599
    } else {
600
        None
601
    };
602
    let releases = if viewer.account().is_some() && role >= Role::Write && logs.iter().any(|l| !l.artifacts.is_empty()) {
603
        db::releases::list(&app.db, row.id).await.unwrap_or_default()
604
    } else {
605
        vec![]
606
    };
607
    Ok(Page(RunPage {
608
        shell,
609
        repo: RepoShell::new(&app, &row, "flow").with_role(role),
610
        run,
611
        graph,
612
        logs,
613
        duration,
614
        can_rerun,
615
        can_cancel,
616
        can_expedite,
617
        queue,
618
        releases,
619
        approvals,
620
    }))
621
}
622
623
#[derive(Deserialize)]
624
pub struct DecideForm {
625
    #[serde(rename = "_csrf")]
626
    csrf_token: String,
627
    /// `approve` or `reject`.
628
    action: String,
629
}
630
631
/// `POST /{owner}/{name}/flow/{id}/jobs/{job}/decide`: approve or reject
632
/// a job that waits for a person (oxygenflow#57).
633
pub async fn decide(
634
    State(app): State<Shared>,
635
    viewer: Viewer,
636
    Path((owner, name, number, job)): Path<(String, String, i64, String)>,
637
    Form(f): Form<DecideForm>,
638
) -> Result<Response, Error> {
639
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
640
    let me = require(&viewer, &shell)?;
641
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
642
    csrf(&viewer, &f.csrf_token, &shell)?;
643
    let run = fdb::run(&app.db, row.id, number)
644
        .await
645
        .map_err(|e| Error::from_db(shell.clone(), e))?
646
        .ok_or_else(|| Error::not_found(shell.clone()))?;
647
    let approve = match f.action.as_str() {
648
        "approve" => true,
649
        "reject" => false,
650
        _ => return Err(Error::bad(shell, "approve or reject")),
651
    };
652
    match crate::flow::decide(&app, &row, &run, &job, &me.account, approve, None).await {
653
        Ok(_) => Ok(Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response()),
654
        Err(why) => Err(Error::bad(shell, why)),
655
    }
656
}
657
658
#[derive(Deserialize)]
659
pub struct LiveQuery {
660
    /// `job:seq,job:seq`: the last log line each open job already shows.
661
    after: Option<String>,
662
}
663
664
/// `GET /{owner}/{name}/flow/{id}/live`: statuses and new log lines, for the
665
/// run page while it is live.
666
pub async fn live(
667
    State(app): State<Shared>,
668
    viewer: Viewer,
669
    Path((owner, name, id)): Path<(String, String, i64)>,
670
    Query(q): Query<LiveQuery>,
671
) -> Result<Response, Error> {
672
    let shell = Shell::new(&app, "", &viewer);
673
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
674
    let run = fdb::run(&app.db, row.id, id)
675
        .await
676
        .map_err(|e| Error::from_db(shell.clone(), e))?
677
        .ok_or_else(|| Error::not_found(shell.clone()))?;
678
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
679
    let after: std::collections::HashMap<i64, i64> = q
680
        .after
681
        .unwrap_or_default()
682
        .split(',')
683
        .filter_map(|p| p.split_once(':'))
684
        .filter_map(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))
685
        .collect();
686
    let mut out = Vec::new();
687
    for j in &jobs {
688
        let lines = match after.get(&j.id) {
689
            Some(seq) => fdb::log(&app.db, j.id, *seq, 1000).await.unwrap_or_default(),
690
            None => vec![],
691
        };
692
        out.push(serde_json::json!({
693
            "id": j.id,
694
            "name": j.name,
695
            "status": j.status,
696
            "glyph": glyph(&j.status),
697
            "duration": crate::flow::duration(j),
698
            "exit_code": j.exit_code,
699
            "lines": lines.iter().map(|l| serde_json::json!({ "seq": l.seq, "t": l.t, "stream": l.stream, "text": l.text })).collect::<Vec<_>>(),
700
        }));
701
    }
702
    Ok(Json(serde_json::json!({ "status": run.status, "live": run.live(), "jobs": out })).into_response())
703
}
704
705
// ------------------------------------------------------------ state stamps
706
707
/// In rendered Markdown, the image path that is the viewed state's stamp.
708
pub const STAMP_IMAGE: &str = ".flow/stamp";
709
/// In rendered Markdown, the link path to the viewed state's run.
710
pub const RUN_LINK: &str = ".flow/run";
711
712
/// Resolve a ref to its state address, and whether the ref can move.
713
async fn state_of(app: &Shared, owner: &str, name: &str, r: &str) -> Result<(String, bool), crate::repos::RepoError> {
714
    let repo = crate::repos::RepoName::new(owner, name).ok_or(crate::repos::RepoError::NotFound)?;
715
    let spec = r.to_string();
716
    app.repos
717
        .read(&repo, move |repo, cache| {
718
            let t = crate::repos::view::resolve(repo, cache, &spec)?;
719
            let moves = matches!(t.kind, crate::repos::view::RefKind::Bookmark | crate::repos::view::RefKind::Tag);
720
            Ok((t.permalink().unwrap_or_default(), moves))
721
        })
722
        .await
723
}
724
725
/// `GET /{owner}/{name}/flow/stamp/{ref}` (hub spec §13.2).
726
pub async fn stamp(
727
    State(app): State<Shared>,
728
    viewer: Viewer,
729
    Path((owner, name, r)): Path<(String, String, String)>,
730
) -> Result<Response, Error> {
731
    let shell = Shell::new(&app, "", &viewer);
732
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
733
    let (heads, moves) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
734
    if moves && !heads.is_empty() {
735
        let mut res = axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{heads}")).into_response();
736
        res.headers_mut().insert(axum::http::header::CACHE_CONTROL, axum::http::HeaderValue::from_static("no-cache"));
737
        return Ok(res);
738
    }
739
    let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?;
740
    let jobs = match &run {
741
        Some(r) => fdb::jobs(&app.db, r.id).await.map_err(|e| Error::from_db(shell.clone(), e))?,
742
        None => vec![],
743
    };
744
    let svg = stamp_svg(&heads, run.as_ref(), &jobs);
745
    let cache = if run.as_ref().is_some_and(|r| !r.live()) { "public, max-age=3600" } else { "public, max-age=60" };
746
    Ok((
747
        [
748
            (axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"),
749
            (axum::http::header::CACHE_CONTROL, cache),
750
            (axum::http::header::CONTENT_SECURITY_POLICY, "default-src 'none'; style-src 'unsafe-inline'"),
751
        ],
752
        svg,
753
    )
754
        .into_response())
755
}
756
757
/// `GET /{owner}/{name}/flow/at/{ref}`: the run of the ref's state, or the Flow tab.
758
pub async fn at(
759
    State(app): State<Shared>,
760
    viewer: Viewer,
761
    Path((owner, name, r)): Path<(String, String, String)>,
762
) -> Result<Response, Error> {
763
    let shell = Shell::new(&app, "", &viewer);
764
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
765
    let (heads, _) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
766
    let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?;
767
    let to = match run {
768
        Some(r) => format!("/{owner}/{name}/flow/{}", r.number),
769
        None => format!("/{owner}/{name}/flow"),
770
    };
771
    Ok(axum::response::Redirect::to(&to).into_response())
772
}
773
774
fn xml(s: &str) -> String {
775
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
776
}
777
778
/// The stamp: the mark, one glyph per job, the status, the state and the
779
/// date; the same facts machine-readable in `<metadata>`. Fixed colours,
780
/// because an image does not follow the page's theme.
781
pub fn stamp_svg(heads: &str, run: Option<&fdb::Run>, jobs: &[fdb::Job]) -> String {
782
    const CH: f64 = 6.6; // IBM Plex Mono at 11px
783
    let colour = |s: &str| match s {
784
        "passed" => "#5fe3a1",
785
        "failed" | "error" => "#ff5e7a",
786
        "running" => "#00e0f0",
787
        _ => "#8592ad",
788
    };
789
    let short: String = heads.chars().take(12).collect();
790
    let (status, date) = match run {
791
        Some(r) => (r.status.as_str(), crate::render::time::absolute(r.created_ms as u64).chars().take(10).collect::<String>()),
792
        None => ("no run", String::new()),
793
    };
794
    let mut ordered: Vec<&fdb::Job> = jobs.iter().collect();
795
    ordered.sort_by(|a, b| (a.depth, &a.name).cmp(&(b.depth, &b.name)));
796
    let label = "OXYGENFLOW";
797
    let label_w = 18.0 + label.len() as f64 * 7.4 + 8.0; // Barlow bold 10.5px, spaced
798
    let glyphs_w = if ordered.is_empty() { 0.0 } else { ordered.len() as f64 * 10.0 + 6.0 };
799
    let tail = if date.is_empty() { format!("{status} · {short}") } else { format!("{status} · {short} · {date}") };
800
    let right_w = 8.0 + glyphs_w + tail.chars().count() as f64 * CH + 8.0;
801
    let w = (label_w + right_w).ceil();
802
    let mut glyphs = String::new();
803
    for (i, j) in ordered.iter().enumerate() {
804
        let x = label_w + 8.0 + i as f64 * 10.0 + 4.0;
805
        glyphs.push_str(&format!(
806
            r#"<text x="{x:.1}" y="15" fill="{}" text-anchor="middle">{}</text>"#,
807
            colour(&j.status),
808
            glyph(&j.status)
809
        ));
810
    }
811
    let meta = serde_json::json!({
812
        "heads": heads.split('+').filter(|h| !h.is_empty()).collect::<Vec<_>>(),
813
        "run": run.map(|r| r.number),
814
        "status": status,
815
        "jobs": ordered.iter().map(|j| serde_json::json!({ "name": j.name, "status": j.status, "receipt": j.receipt_hash })).collect::<Vec<_>>(),
816
    });
817
    let title = match run {
818
        Some(r) => format!("OxygenFlow run #{} {status} on state {short}", r.number),
819
        None => format!("OxygenFlow: no run for state {short}"),
820
    };
821
    format!(
822
        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>"##,
823
        t = xml(&title),
824
        m = xml(&meta.to_string()),
825
        lw = label_w,
826
        lx = label_w - 4.0,
827
        tx = label_w + 8.0 + glyphs_w,
828
        sc = colour(status),
829
        tail = xml(&tail),
830
        wi = w - 1.0,
831
    )
832
}
833
834
/// A receipt kept in a repository (Oxygen spec §14.6), as pages show it.
835
#[derive(Clone, Debug)]
836
pub struct ReceiptRow {
837
    pub attest: String,
838
    pub job: String,
839
    pub exit_code: u32,
840
    pub duration: String,
841
    pub runner: String,
842
    pub run: String,
843
    /// Why it does not verify, or that its runner's key was revoked.
844
    pub problem: String,
845
    pub made_ms: i64,
846
}
847
848
impl ReceiptRow {
849
    pub fn passed(&self) -> bool {
850
        self.exit_code == 0
851
    }
852
}
853
854
/// The receipts kept for the state of `heads`.
855
pub async fn receipts_of(app: &Shared, name: &crate::repos::RepoName, heads: Vec<oxy_core::hash::ChangeHash>) -> Vec<ReceiptRow> {
856
    let base = app.config.base_url();
857
    let found = app.repos.read(name, move |repo, _| Ok(repo.receipts(&heads)?)).await.unwrap_or_default();
858
    found
859
        .into_iter()
860
        .map(|i| {
861
            let r = &i.signed.receipt;
862
            let run = i.signed.run().to_string();
863
            ReceiptRow {
864
                attest: i.attest.to_hex(),
865
                job: r.job_name.clone(),
866
                exit_code: r.exit_code,
867
                duration: crate::flow::human_ms(r.duration_ms as i64),
868
                runner: i.signed.runner.name.clone(),
869
                // Only links to this hub are followed from the page.
870
                run: if run.starts_with(base) { run } else { String::new() },
871
                problem: match (i.problem, i.revoked) {
872
                    (Some(p), _) => p,
873
                    (None, true) => "the runner's key was revoked".into(),
874
                    (None, false) => String::new(),
875
                },
876
                made_ms: i.signed.attest.hlc.wall_ms as i64,
877
            }
878
        })
879
        .collect()
880
}
881
882
/// `GET /{owner}/{name}/receipts/{attest}`: a signed receipt, for
883
/// `oxy receipt verify` or `oxy receipt import`.
884
pub async fn receipt_file(
885
    State(app): State<Shared>,
886
    viewer: Viewer,
887
    Path((owner, name, attest)): Path<(String, String, String)>,
888
) -> Result<Response, Error> {
889
    let shell = Shell::new(&app, &format!("/{owner}/{name}/receipts/{attest}"), &viewer);
890
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
891
    let Some(r) = oxy_core::hash::ObjectRef::from_hex(attest.trim_end_matches(".receipt")) else {
892
        return Err(Error::not_found(shell));
893
    };
894
    let (job, bytes) = app
895
        .repos
896
        .read(&repo, move |repo, _| {
897
            let i = repo.receipt(&r)?;
898
            Ok((i.signed.receipt.job_name.clone(), i.signed.encode()))
899
        })
900
        .await
901
        .map_err(|_| Error::not_found(shell.clone()))?;
902
    let file: String = job.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')).collect();
903
    Ok((
904
        [
905
            (axum::http::header::CONTENT_TYPE, "application/oxy-receipt".to_string()),
906
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{file}-{}.receipt\"", r.short(12))),
907
        ],
908
        bytes,
909
    )
910
        .into_response())
911
}
912
913
/// `GET /{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}`: an artifact
914
/// of a run's job, read from the repository.
915
pub async fn artifact_file(
916
    State(app): State<Shared>,
917
    viewer: Viewer,
918
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
919
) -> Result<Response, Error> {
920
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}"), &viewer);
921
    let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
922
    let run = fdb::run(&app.db, row.id, id)
923
        .await
924
        .map_err(|e| Error::from_db(shell.clone(), e))?
925
        .ok_or_else(|| Error::not_found(shell.clone()))?;
926
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
927
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
928
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
929
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
930
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
931
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|_| Error::not_found(shell.clone()))?;
932
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
933
    Ok((
934
        [
935
            (axum::http::header::CONTENT_TYPE, "application/octet-stream".to_string()),
936
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}\"", file.replace('"', ""))),
937
        ],
938
        bytes,
939
    )
940
        .into_response())
941
}
942
943
/// `GET …/artifacts/{job}/{artifact}/provenance` (oxygenhub#239): the
944
/// artifact's SLSA provenance in a DSSE envelope signed by the hub, for
945
/// `cosign verify-blob-attestation --key oxyhub-signing.pem --type
946
/// slsaprovenance1`. Only for a job whose signed receipt the hub kept.
947
pub async fn provenance(
948
    State(app): State<Shared>,
949
    viewer: Viewer,
950
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
951
) -> Result<Response, Error> {
952
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/provenance"), &viewer);
953
    let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
954
    let run = fdb::run(&app.db, row.id, id)
955
        .await
956
        .map_err(|e| Error::from_db(shell.clone(), e))?
957
        .ok_or_else(|| Error::not_found(shell.clone()))?;
958
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
959
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
960
    if j.receipt_attest.is_empty() {
961
        return Err(Error::bad(shell, "This job has no signed receipt the hub kept, so the hub states no provenance for it.".to_string()));
962
    }
963
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
964
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
965
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
966
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|_| Error::not_found(shell.clone()))?;
967
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
968
    let base = app.config.base_url();
969
    let subject = crate::provenance::Subject {
970
        name: &file,
971
        bytes: &bytes,
972
        repo: &format!("{owner}/{name}"),
973
        run_url: &format!("{base}/{owner}/{name}/flow/{id}"),
974
        bookmark: &run.bookmark,
975
        state: &run.state,
976
        heads: &run.heads,
977
        pipeline_hash: &run.pipeline_hash,
978
        job: &j.name,
979
        runner: &j.runner,
980
        receipt_signer: &j.receipt_signer,
981
        receipt_attest: &j.receipt_attest,
982
        started_ms: j.started_ms,
983
        finished_ms: j.finished_ms,
984
    };
985
    let statement = crate::provenance::statement(base, &subject);
986
    let envelope = crate::provenance::envelope(&app, &statement).map_err(|e| Error::bad(shell.clone(), e.to_string()))?;
987
    Ok((
988
        [
989
            (axum::http::header::CONTENT_TYPE, "application/json".to_string()),
990
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}.intoto.json\"", file.replace('"', ""))),
991
        ],
992
        serde_json::to_string(&envelope).unwrap_or_default(),
993
    )
994
        .into_response())
995
}
996
997
/// `GET /.well-known/oxyhub-signing.pem`: the hub's Ed25519 public key, as
998
/// cosign and other verifiers take it (oxygenhub#239).
999
pub async fn signing_key(State(app): State<Shared>) -> Response {
1000
    ([(axum::http::header::CONTENT_TYPE, "application/x-pem-file")], crate::provenance::public_pem(&app)).into_response()
1001
}
1002
1003
#[derive(Deserialize)]
1004
pub struct AttachForm {
1005
    _csrf: String,
1006
    release: i64,
1007
}
1008
1009
/// `POST /{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/attach`: add
1010
/// an artifact to a release as an asset, named after its path; the release
1011
/// page then shows the run and receipt that built it.
1012
pub async fn attach(
1013
    State(app): State<Shared>,
1014
    viewer: Viewer,
1015
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
1016
    Form(f): Form<AttachForm>,
1017
) -> Result<Response, Error> {
1018
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer);
1019
    require(&viewer, &shell)?;
1020
    csrf(&viewer, &f._csrf, &shell)?;
1021
    let (repo, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
1022
    let run = fdb::run(&app.db, row.id, id)
1023
        .await
1024
        .map_err(|e| Error::from_db(shell.clone(), e))?
1025
        .ok_or_else(|| Error::not_found(shell.clone()))?;
1026
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1027
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
1028
    // A failing job's `when "always"` artifacts are not in its receipt, so
1029
    // they cannot stand for a release (oxygenflow#37).
1030
    if j.status != "passed" {
1031
        return Err(Error::bad(shell, "only a passing job's artifacts can be attached to a release"));
1032
    }
1033
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1034
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
1035
    let releases = db::releases::list(&app.db, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1036
    let Some(rel) = releases.into_iter().find(|r| r.id == f.release) else { return Err(Error::not_found(shell)) };
1037
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
1038
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
1039
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
1040
    super::releases::store_asset(&app, rel.id, &file, "application/octet-stream", &bytes)
1041
        .await
1042
        .map_err(|m| Error::bad(shell.clone(), m))?;
1043
    Ok(Redirect::to(&format!("/{owner}/{name}/releases/tag/{}", rel.tag)).into_response())
1044
}
1045
1046
/// `/{owner}/{name}/flow/badge.svg`: the latest run on the default
1047
/// bookmark as a small SVG for a README, for whoever may read the
1048
/// repository. `passed` green, `failed` or `error` red, a run still going
1049
/// blue, none grey.
1050
pub async fn badge(
1051
    State(app): State<Shared>,
1052
    viewer: Viewer,
1053
    Path((owner, name)): Path<(String, String)>,
1054
) -> Result<axum::response::Response, Error> {
1055
    use axum::response::IntoResponse;
1056
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
1057
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
1058
    let latest = fdb::latest_on(&app.db, row.id, &row.default_bookmark).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1059
    let (text, colour) = match latest.as_ref().map(|r| r.status.as_str()) {
1060
        Some("passed") => ("passing", "#2da44e"),
1061
        Some("failed") | Some("error") => ("failing", "#cf222e"),
1062
        Some("cancelled") => ("cancelled", "#6e7781"),
1063
        Some(_) => ("running", "#0969da"),
1064
        None => ("no runs", "#6e7781"),
1065
    };
1066
    let label = "OxygenFlow";
1067
    let (lw, tw) = (label.len() as u32 * 7 + 10, text.len() as u32 * 7 + 10);
1068
    let svg = format!(
1069
        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>"##,
1070
        w = lw + tw,
1071
        lx = lw / 2,
1072
        tx = lw + tw / 2,
1073
    );
1074
    Ok((
1075
        [(axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"), (axum::http::header::CACHE_CONTROL, "no-cache, max-age=60")],
1076
        svg,
1077
    )
1078
        .into_response())
1079
}
1080
1081
#[cfg(test)]
1082
mod section_tests {
1083
    use super::*;
1084
1085
    fn line(seq: i64, t: i64, text: &str) -> fdb::LogLine {
1086
        fdb::LogLine { seq, t, stream: "out".into(), text: text.into() }
1087
    }
1088
1089
    #[test]
1090
    fn marked_lines_fold_into_sections() {
1091
        let lines = vec![
1092
            line(1, 0, "booting"),
1093
            line(2, 100, "::group::cargo build"),
1094
            line(3, 200, "Compiling a"),
1095
            line(4, 900, "Compiling b"),
1096
            line(5, 4_300, "::endgroup::"),
1097
            line(6, 4_400, "::group::cargo test"),
1098
            line(7, 4_500, "test x ... ok"),
1099
            line(8, 5_000, "::group::lint"),
1100
            line(9, 5_100, "clean"),
1101
        ];
1102
        let segs = sections(&lines);
1103
        assert_eq!(segs.len(), 4);
1104
        assert!(matches!(&segs[0], Segment::Line(l) if l.text == "booting"));
1105
        let Segment::Group(build) = &segs[1] else { panic!("a section") };
1106
        assert_eq!((build.title.as_str(), build.from_t, build.to_t, build.lines.len()), ("cargo build", 100, Some(4_300), 2));
1107
        let Segment::Group(test) = &segs[2] else { panic!("a section") };
1108
        assert_eq!(test.to_t, Some(5_000), "a new section ends the one before");
1109
        let Segment::Group(lint) = &segs[3] else { panic!("a section") };
1110
        assert_eq!((lint.to_t, lint.lines.len()), (None, 1), "still going");
1111
        assert_eq!(secs(4_200), "4.2s");
1112
    }
1113
}