OXYGENHUB
# 794ff94f194a oxygenhub / crates / hub / src / web / flow.rs
42.9 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
    let note = format!("expedited by {}: {reason}", me.account.username);
289
    if fdb::expedite(&app.db, run.id, &note).await.map_err(|e| Error::from_db(shell.clone(), e))? {
290
        db::accounts::audit(&app.db, Some(&me.account), "flow.expedite", &format!("{owner}/{name}"), &format!("#{number}: {reason}"))
291
            .await
292
            .ok();
293
        // Every queued job's place changes now, not at the next pass
294
        // (#291): this run's page and the pages of the runs it moved down
295
        // hear of it.
296
        if let Err(e) = crate::flow::explain_waits(&app).await {
297
            tracing::warn!("flow: placing after an expedite: {e}");
298
        }
299
        app.bus.live(&crate::events::topic::run(run.id), "jobs");
300
    }
301
    Ok(Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response())
302
}
303
304
/// Percent-encode a message for a query string.
305
fn urlencoding(s: &str) -> String {
306
    s.bytes()
307
        .map(|b| match b {
308
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),
309
            _ => format!("%{b:02X}"),
310
        })
311
        .collect()
312
}
313
314
/// A job placed in the graph.
315
pub struct Node {
316
    pub j: fdb::Job,
317
    pub x: i64,
318
    pub y: i64,
319
    pub duration: String,
320
}
321
322
pub struct Edge {
323
    pub d: String,
324
    pub status: String,
325
}
326
327
pub struct Graph {
328
    pub nodes: Vec<Node>,
329
    pub edges: Vec<Edge>,
330
    pub width: i64,
331
    pub height: i64,
332
}
333
334
pub const NODE_W: i64 = 200;
335
pub const NODE_H: i64 = 48;
336
const COL_GAP: i64 = 72;
337
const ROW_GAP: i64 = 18;
338
const PAD: i64 = 12;
339
340
/// Columns by dependency depth, jobs in each column in name order.
341
pub fn layout(jobs: Vec<fdb::Job>) -> Graph {
342
    let mut by_depth: std::collections::BTreeMap<i64, Vec<fdb::Job>> = Default::default();
343
    for j in jobs {
344
        by_depth.entry(j.depth).or_default().push(j);
345
    }
346
    let rows = by_depth.values().map(Vec::len).max().unwrap_or(0) as i64;
347
    let height = PAD * 2 + rows * NODE_H + (rows - 1).max(0) * ROW_GAP;
348
    let mut nodes = Vec::new();
349
    for (col, (_, mut js)) in by_depth.into_iter().enumerate() {
350
        js.sort_by(|a, b| a.name.cmp(&b.name));
351
        let n = js.len() as i64;
352
        let column_h = n * NODE_H + (n - 1).max(0) * ROW_GAP;
353
        let top = (height - column_h) / 2;
354
        for (i, j) in js.into_iter().enumerate() {
355
            let duration = crate::flow::duration(&j);
356
            nodes.push(Node { x: PAD + col as i64 * (NODE_W + COL_GAP), y: top + i as i64 * (NODE_H + ROW_GAP), duration, j });
357
        }
358
    }
359
    let mut edges = Vec::new();
360
    for n in &nodes {
361
        for d in n.j.depends_on() {
362
            if let Some(from) = nodes.iter().find(|m| m.j.name == d) {
363
                let (x1, y1) = (from.x + NODE_W, from.y + NODE_H / 2);
364
                let (x2, y2) = (n.x, n.y + NODE_H / 2);
365
                let mid = (x1 + x2) / 2;
366
                edges.push(Edge { d: format!("M{x1},{y1} C{mid},{y1} {mid},{y2} {x2},{y2}"), status: from.j.status.clone() });
367
            }
368
        }
369
    }
370
    let cols = nodes.iter().map(|n| n.x).max().map(|x| x + NODE_W + PAD).unwrap_or(PAD * 2);
371
    Graph { nodes, edges, width: cols, height: height.max(NODE_H + PAD * 2) }
372
}
373
374
pub fn glyph(status: &str) -> &'static str {
375
    match status {
376
        "passed" => "✓",
377
        "failed" => "✕",
378
        "running" => "●",
379
        "skipped" => "⤼",
380
        "cancelled" => "⊘",
381
        "error" => "!",
382
        _ => "○",
383
    }
384
}
385
386
/// Failed tests a run page lists per job; the rest are counted.
387
const SHOWN_FAILURES: i64 = 50;
388
389
pub struct JobLog {
390
    pub j: fdb::Job,
391
    pub artifacts: Vec<fdb::Artifact>,
392
    pub lines: Vec<fdb::LogLine>,
393
    pub duration: String,
394
    /// The last line shown; the live view asks for what follows.
395
    pub last_seq: i64,
396
    /// The job's coverage report, when it uploaded one (#113): its id and percentage.
397
    pub coverage: Option<(i64, String)>,
398
    /// The job's test report, when it uploaded one (#114), and its first
399
    /// failures.
400
    pub tests: Option<crate::junit::Report>,
401
    pub failures: Vec<crate::junit::Case>,
402
}
403
404
#[derive(Template)]
405
#[template(path = "flow_run.html")]
406
pub struct RunPage {
407
    shell: Shell,
408
    repo: RepoShell,
409
    run: fdb::Run,
410
    graph: Graph,
411
    logs: Vec<JobLog>,
412
    duration: String,
413
    /// Whether the viewer may re-run it.
414
    can_rerun: bool,
415
    /// Whether the viewer may cancel it.
416
    can_cancel: bool,
417
    /// May raise the run to urgent (oxygenhub#244): maintainers, while it runs.
418
    can_expedite: bool,
419
    /// Where a live run stands among the runners' work.
420
    queue: Option<crate::flow::QueueInfo>,
421
    /// Releases a writer may attach this run's artifacts to.
422
    releases: Vec<db::releases::Release>,
423
    /// Jobs that wait, or waited, for a person (oxygenflow#57).
424
    approvals: Vec<ApprovalView>,
425
}
426
427
/// A job's approval as the run page shows it.
428
pub struct ApprovalView {
429
    pub job: String,
430
    pub by: String,
431
    pub others_only: bool,
432
    /// `waiting`, `approved`, `rejected` or `expired`.
433
    pub state: &'static str,
434
    pub who: String,
435
    pub when_ms: i64,
436
    /// Whether the viewer may approve or reject it now, else why not.
437
    pub may: Result<(), String>,
438
    /// It takes an approval signed with the approver's key (#235): the
439
    /// command that signs it, and the approval's hash once sealed.
440
    pub sealed: bool,
441
    pub command: String,
442
    pub seal: String,
443
}
444
445
impl ApprovalView {
446
    pub fn may_decide(&self) -> bool {
447
        self.may.is_ok()
448
    }
449
450
    pub fn why_not(&self) -> String {
451
        self.may.clone().err().unwrap_or_default()
452
    }
453
}
454
455
/// Lines of a job's log a page shows before "the rest is loaded as it comes".
456
const PAGE_LINES: i64 = 5000;
457
458
pub async fn run(
459
    State(app): State<Shared>,
460
    viewer: Viewer,
461
    Path((owner, name, id)): Path<(String, String, i64)>,
462
) -> Result<Page<RunPage>, Error> {
463
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer);
464
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
465
    let run = fdb::run(&app.db, row.id, id)
466
        .await
467
        .map_err(|e| Error::from_db(shell.clone(), e))?
468
        .ok_or_else(|| Error::not_found(shell.clone()))?;
469
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
470
    let reports = crate::coverage::for_run(&app.db, run.id).await.unwrap_or_default();
471
    let test_reports = crate::junit::for_run(&app.db, run.id).await.unwrap_or_default();
472
    let mut logs = Vec::new();
473
    for j in &jobs {
474
        let lines = fdb::log(&app.db, j.id, 0, PAGE_LINES).await.unwrap_or_default();
475
        let last_seq = lines.last().map(|l| l.seq).unwrap_or(0);
476
        let artifacts = fdb::artifacts(&app.db, j.id).await.unwrap_or_default();
477
        let coverage = reports
478
            .iter()
479
            .find(|r| r.job_id == Some(j.id))
480
            .map(|r| (r.id, r.percent().map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into())));
481
        let tests = test_reports.iter().find(|r| r.job_id == j.id).cloned();
482
        let failures = match &tests {
483
            Some(r) if r.broken() > 0 => crate::junit::failures(&app.db, r.id, SHOWN_FAILURES).await.unwrap_or_default(),
484
            _ => vec![],
485
        };
486
        logs.push(JobLog { duration: crate::flow::duration(j), j: j.clone(), artifacts, lines, last_seq, coverage, tests, failures });
487
    }
488
    let duration = match run.finished_ms {
489
        Some(f) => crate::flow::human_ms(f - run.created_ms),
490
        None => crate::flow::human_ms(db::now_ms() - run.created_ms),
491
    };
492
    let mut approvals = Vec::new();
493
    for j in jobs.iter().filter(|j| !j.approval.is_empty()) {
494
        let Some(a) = serde_json::from_str::<flow_core::Job>(&j.spec).ok().and_then(|s| s.approval) else { continue };
495
        let state = match (j.approval.as_str(), j.status.as_str()) {
496
            ("waiting", "queued") => "waiting",
497
            ("approved", _) => "approved",
498
            (_, "cancelled") if !j.approved_by.is_empty() => "rejected",
499
            (_, "cancelled") if j.error.starts_with("no approval within") => "expired",
500
            _ => continue,
501
        };
502
        let may = match (state, viewer.account()) {
503
            ("waiting", Some(me)) => crate::flow::may_decide(&app, &row, &run, j, me).await.map(|_| ()),
504
            ("waiting", None) => Err("sign in to approve".into()),
505
            _ => Err(String::new()),
506
        };
507
        approvals.push(ApprovalView {
508
            sealed: a.sealed,
509
            command: format!("oxy seal --flow {}/{owner}/{name}/flow/{} --job {}", app.config.base_url(), run.number, j.name),
510
            seal: j.approval_seal.clone(),
511
            job: j.name.clone(),
512
            by: a.by,
513
            others_only: a.others_only,
514
            state,
515
            who: if j.approved_via.is_empty() { j.approved_by.clone() } else { format!("{} via {}", j.approved_by, j.approved_via) },
516
            when_ms: j.approved_ms.unwrap_or(0),
517
            may,
518
        });
519
    }
520
    let graph = layout(jobs);
521
    let can_write = viewer.account().is_some() && role >= Role::Write;
522
    let can_rerun = !run.live() && can_write && crate::flow::enabled(&app, &row);
523
    let can_cancel = run.live() && can_write;
524
    let can_expedite = run.live() && run.priority.is_empty() && viewer.account().is_some() && role >= Role::Maintain;
525
    let queue = if run.live() {
526
        let q = fdb::queue(&app.db).await.unwrap_or_default();
527
        Some(crate::flow::queue_info(&q, row.id, run.id)).filter(|i| i.position.is_some())
528
    } else {
529
        None
530
    };
531
    let releases = if viewer.account().is_some() && role >= Role::Write && logs.iter().any(|l| !l.artifacts.is_empty()) {
532
        db::releases::list(&app.db, row.id).await.unwrap_or_default()
533
    } else {
534
        vec![]
535
    };
536
    Ok(Page(RunPage {
537
        shell,
538
        repo: RepoShell::new(&app, &row, "flow").with_role(role),
539
        run,
540
        graph,
541
        logs,
542
        duration,
543
        can_rerun,
544
        can_cancel,
545
        can_expedite,
546
        queue,
547
        releases,
548
        approvals,
549
    }))
550
}
551
552
#[derive(Deserialize)]
553
pub struct DecideForm {
554
    #[serde(rename = "_csrf")]
555
    csrf_token: String,
556
    /// `approve` or `reject`.
557
    action: String,
558
}
559
560
/// `POST /{owner}/{name}/flow/{id}/jobs/{job}/decide`: approve or reject
561
/// a job that waits for a person (oxygenflow#57).
562
pub async fn decide(
563
    State(app): State<Shared>,
564
    viewer: Viewer,
565
    Path((owner, name, number, job)): Path<(String, String, i64, String)>,
566
    Form(f): Form<DecideForm>,
567
) -> Result<Response, Error> {
568
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
569
    let me = require(&viewer, &shell)?;
570
    let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?;
571
    csrf(&viewer, &f.csrf_token, &shell)?;
572
    let run = fdb::run(&app.db, row.id, number)
573
        .await
574
        .map_err(|e| Error::from_db(shell.clone(), e))?
575
        .ok_or_else(|| Error::not_found(shell.clone()))?;
576
    let approve = match f.action.as_str() {
577
        "approve" => true,
578
        "reject" => false,
579
        _ => return Err(Error::bad(shell, "approve or reject")),
580
    };
581
    match crate::flow::decide(&app, &row, &run, &job, &me.account, approve, None).await {
582
        Ok(_) => Ok(Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response()),
583
        Err(why) => Err(Error::bad(shell, why)),
584
    }
585
}
586
587
#[derive(Deserialize)]
588
pub struct LiveQuery {
589
    /// `job:seq,job:seq`: the last log line each open job already shows.
590
    after: Option<String>,
591
}
592
593
/// `GET /{owner}/{name}/flow/{id}/live`: statuses and new log lines, for the
594
/// run page while it is live.
595
pub async fn live(
596
    State(app): State<Shared>,
597
    viewer: Viewer,
598
    Path((owner, name, id)): Path<(String, String, i64)>,
599
    Query(q): Query<LiveQuery>,
600
) -> Result<Response, Error> {
601
    let shell = Shell::new(&app, "", &viewer);
602
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
603
    let run = fdb::run(&app.db, row.id, id)
604
        .await
605
        .map_err(|e| Error::from_db(shell.clone(), e))?
606
        .ok_or_else(|| Error::not_found(shell.clone()))?;
607
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
608
    let after: std::collections::HashMap<i64, i64> = q
609
        .after
610
        .unwrap_or_default()
611
        .split(',')
612
        .filter_map(|p| p.split_once(':'))
613
        .filter_map(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))
614
        .collect();
615
    let mut out = Vec::new();
616
    for j in &jobs {
617
        let lines = match after.get(&j.id) {
618
            Some(seq) => fdb::log(&app.db, j.id, *seq, 1000).await.unwrap_or_default(),
619
            None => vec![],
620
        };
621
        out.push(serde_json::json!({
622
            "id": j.id,
623
            "name": j.name,
624
            "status": j.status,
625
            "glyph": glyph(&j.status),
626
            "duration": crate::flow::duration(j),
627
            "exit_code": j.exit_code,
628
            "lines": lines.iter().map(|l| serde_json::json!({ "seq": l.seq, "t": l.t, "stream": l.stream, "text": l.text })).collect::<Vec<_>>(),
629
        }));
630
    }
631
    Ok(Json(serde_json::json!({ "status": run.status, "live": run.live(), "jobs": out })).into_response())
632
}
633
634
// ------------------------------------------------------------ state stamps
635
636
/// In rendered Markdown, the image path that is the viewed state's stamp.
637
pub const STAMP_IMAGE: &str = ".flow/stamp";
638
/// In rendered Markdown, the link path to the viewed state's run.
639
pub const RUN_LINK: &str = ".flow/run";
640
641
/// Resolve a ref to its state address, and whether the ref can move.
642
async fn state_of(app: &Shared, owner: &str, name: &str, r: &str) -> Result<(String, bool), crate::repos::RepoError> {
643
    let repo = crate::repos::RepoName::new(owner, name).ok_or(crate::repos::RepoError::NotFound)?;
644
    let spec = r.to_string();
645
    app.repos
646
        .read(&repo, move |repo, cache| {
647
            let t = crate::repos::view::resolve(repo, cache, &spec)?;
648
            let moves = matches!(t.kind, crate::repos::view::RefKind::Bookmark | crate::repos::view::RefKind::Tag);
649
            Ok((t.permalink().unwrap_or_default(), moves))
650
        })
651
        .await
652
}
653
654
/// `GET /{owner}/{name}/flow/stamp/{ref}` (hub spec §13.2).
655
pub async fn stamp(
656
    State(app): State<Shared>,
657
    viewer: Viewer,
658
    Path((owner, name, r)): Path<(String, String, String)>,
659
) -> Result<Response, Error> {
660
    let shell = Shell::new(&app, "", &viewer);
661
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
662
    let (heads, moves) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
663
    if moves && !heads.is_empty() {
664
        let mut res = axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{heads}")).into_response();
665
        res.headers_mut().insert(axum::http::header::CACHE_CONTROL, axum::http::HeaderValue::from_static("no-cache"));
666
        return Ok(res);
667
    }
668
    let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?;
669
    let jobs = match &run {
670
        Some(r) => fdb::jobs(&app.db, r.id).await.map_err(|e| Error::from_db(shell.clone(), e))?,
671
        None => vec![],
672
    };
673
    let svg = stamp_svg(&heads, run.as_ref(), &jobs);
674
    let cache = if run.as_ref().is_some_and(|r| !r.live()) { "public, max-age=3600" } else { "public, max-age=60" };
675
    Ok((
676
        [
677
            (axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"),
678
            (axum::http::header::CACHE_CONTROL, cache),
679
            (axum::http::header::CONTENT_SECURITY_POLICY, "default-src 'none'; style-src 'unsafe-inline'"),
680
        ],
681
        svg,
682
    )
683
        .into_response())
684
}
685
686
/// `GET /{owner}/{name}/flow/at/{ref}`: the run of the ref's state, or the Flow tab.
687
pub async fn at(
688
    State(app): State<Shared>,
689
    viewer: Viewer,
690
    Path((owner, name, r)): Path<(String, String, String)>,
691
) -> Result<Response, Error> {
692
    let shell = Shell::new(&app, "", &viewer);
693
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
694
    let (heads, _) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
695
    let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?;
696
    let to = match run {
697
        Some(r) => format!("/{owner}/{name}/flow/{}", r.number),
698
        None => format!("/{owner}/{name}/flow"),
699
    };
700
    Ok(axum::response::Redirect::to(&to).into_response())
701
}
702
703
fn xml(s: &str) -> String {
704
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
705
}
706
707
/// The stamp: the mark, one glyph per job, the status, the state and the
708
/// date; the same facts machine-readable in `<metadata>`. Fixed colours,
709
/// because an image does not follow the page's theme.
710
pub fn stamp_svg(heads: &str, run: Option<&fdb::Run>, jobs: &[fdb::Job]) -> String {
711
    const CH: f64 = 6.6; // IBM Plex Mono at 11px
712
    let colour = |s: &str| match s {
713
        "passed" => "#5fe3a1",
714
        "failed" | "error" => "#ff5e7a",
715
        "running" => "#00e0f0",
716
        _ => "#8592ad",
717
    };
718
    let short: String = heads.chars().take(12).collect();
719
    let (status, date) = match run {
720
        Some(r) => (r.status.as_str(), crate::render::time::absolute(r.created_ms as u64).chars().take(10).collect::<String>()),
721
        None => ("no run", String::new()),
722
    };
723
    let mut ordered: Vec<&fdb::Job> = jobs.iter().collect();
724
    ordered.sort_by(|a, b| (a.depth, &a.name).cmp(&(b.depth, &b.name)));
725
    let label = "OXYGENFLOW";
726
    let label_w = 14.0 + label.len() as f64 * 6.2 + 8.0;
727
    let glyphs_w = if ordered.is_empty() { 0.0 } else { ordered.len() as f64 * 10.0 + 6.0 };
728
    let tail = if date.is_empty() { format!("{status} · {short}") } else { format!("{status} · {short} · {date}") };
729
    let right_w = 8.0 + glyphs_w + tail.chars().count() as f64 * CH + 8.0;
730
    let w = (label_w + right_w).ceil();
731
    let mut glyphs = String::new();
732
    for (i, j) in ordered.iter().enumerate() {
733
        let x = label_w + 8.0 + i as f64 * 10.0 + 4.0;
734
        glyphs.push_str(&format!(
735
            r#"<text x="{x:.1}" y="15" fill="{}" text-anchor="middle">{}</text>"#,
736
            colour(&j.status),
737
            glyph(&j.status)
738
        ));
739
    }
740
    let meta = serde_json::json!({
741
        "heads": heads.split('+').filter(|h| !h.is_empty()).collect::<Vec<_>>(),
742
        "run": run.map(|r| r.number),
743
        "status": status,
744
        "jobs": ordered.iter().map(|j| serde_json::json!({ "name": j.name, "status": j.status, "receipt": j.receipt_hash })).collect::<Vec<_>>(),
745
    });
746
    let title = match run {
747
        Some(r) => format!("OxygenFlow run #{} {status} on state {short}", r.number),
748
        None => format!("OxygenFlow: no run for state {short}"),
749
    };
750
    format!(
751
        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>"##,
752
        t = xml(&title),
753
        m = xml(&meta.to_string()),
754
        lw = label_w,
755
        lx = label_w - 4.0,
756
        tx = label_w + 8.0 + glyphs_w,
757
        sc = colour(status),
758
        tail = xml(&tail),
759
        wi = w - 1.0,
760
    )
761
}
762
763
/// A receipt kept in a repository (Oxygen spec §14.6), as pages show it.
764
#[derive(Clone, Debug)]
765
pub struct ReceiptRow {
766
    pub attest: String,
767
    pub job: String,
768
    pub exit_code: u32,
769
    pub duration: String,
770
    pub runner: String,
771
    pub run: String,
772
    /// Why it does not verify, or that its runner's key was revoked.
773
    pub problem: String,
774
    pub made_ms: i64,
775
}
776
777
impl ReceiptRow {
778
    pub fn passed(&self) -> bool {
779
        self.exit_code == 0
780
    }
781
}
782
783
/// The receipts kept for the state of `heads`.
784
pub async fn receipts_of(app: &Shared, name: &crate::repos::RepoName, heads: Vec<oxy_core::hash::ChangeHash>) -> Vec<ReceiptRow> {
785
    let base = app.config.base_url();
786
    let found = app.repos.read(name, move |repo, _| Ok(repo.receipts(&heads)?)).await.unwrap_or_default();
787
    found
788
        .into_iter()
789
        .map(|i| {
790
            let r = &i.signed.receipt;
791
            let run = i.signed.run().to_string();
792
            ReceiptRow {
793
                attest: i.attest.to_hex(),
794
                job: r.job_name.clone(),
795
                exit_code: r.exit_code,
796
                duration: crate::flow::human_ms(r.duration_ms as i64),
797
                runner: i.signed.runner.name.clone(),
798
                // Only links to this hub are followed from the page.
799
                run: if run.starts_with(base) { run } else { String::new() },
800
                problem: match (i.problem, i.revoked) {
801
                    (Some(p), _) => p,
802
                    (None, true) => "the runner's key was revoked".into(),
803
                    (None, false) => String::new(),
804
                },
805
                made_ms: i.signed.attest.hlc.wall_ms as i64,
806
            }
807
        })
808
        .collect()
809
}
810
811
/// `GET /{owner}/{name}/receipts/{attest}`: a signed receipt, for
812
/// `oxy receipt verify` or `oxy receipt import`.
813
pub async fn receipt_file(
814
    State(app): State<Shared>,
815
    viewer: Viewer,
816
    Path((owner, name, attest)): Path<(String, String, String)>,
817
) -> Result<Response, Error> {
818
    let shell = Shell::new(&app, &format!("/{owner}/{name}/receipts/{attest}"), &viewer);
819
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
820
    let Some(r) = oxy_core::hash::ObjectRef::from_hex(attest.trim_end_matches(".receipt")) else {
821
        return Err(Error::not_found(shell));
822
    };
823
    let (job, bytes) = app
824
        .repos
825
        .read(&repo, move |repo, _| {
826
            let i = repo.receipt(&r)?;
827
            Ok((i.signed.receipt.job_name.clone(), i.signed.encode()))
828
        })
829
        .await
830
        .map_err(|_| Error::not_found(shell.clone()))?;
831
    let file: String = job.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')).collect();
832
    Ok((
833
        [
834
            (axum::http::header::CONTENT_TYPE, "application/oxy-receipt".to_string()),
835
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{file}-{}.receipt\"", r.short(12))),
836
        ],
837
        bytes,
838
    )
839
        .into_response())
840
}
841
842
/// `GET /{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}`: an artifact
843
/// of a run's job, read from the repository.
844
pub async fn artifact_file(
845
    State(app): State<Shared>,
846
    viewer: Viewer,
847
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
848
) -> Result<Response, Error> {
849
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}"), &viewer);
850
    let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
851
    let run = fdb::run(&app.db, row.id, id)
852
        .await
853
        .map_err(|e| Error::from_db(shell.clone(), e))?
854
        .ok_or_else(|| Error::not_found(shell.clone()))?;
855
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
856
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
857
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
858
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
859
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
860
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|_| Error::not_found(shell.clone()))?;
861
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
862
    Ok((
863
        [
864
            (axum::http::header::CONTENT_TYPE, "application/octet-stream".to_string()),
865
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}\"", file.replace('"', ""))),
866
        ],
867
        bytes,
868
    )
869
        .into_response())
870
}
871
872
/// `GET …/artifacts/{job}/{artifact}/provenance` (oxygenhub#239): the
873
/// artifact's SLSA provenance in a DSSE envelope signed by the hub, for
874
/// `cosign verify-blob-attestation --key oxyhub-signing.pem --type
875
/// slsaprovenance1`. Only for a job whose signed receipt the hub kept.
876
pub async fn provenance(
877
    State(app): State<Shared>,
878
    viewer: Viewer,
879
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
880
) -> Result<Response, Error> {
881
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/provenance"), &viewer);
882
    let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
883
    let run = fdb::run(&app.db, row.id, id)
884
        .await
885
        .map_err(|e| Error::from_db(shell.clone(), e))?
886
        .ok_or_else(|| Error::not_found(shell.clone()))?;
887
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
888
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
889
    if j.receipt_attest.is_empty() {
890
        return Err(Error::bad(shell, "This job has no signed receipt the hub kept, so the hub states no provenance for it.".to_string()));
891
    }
892
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
893
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
894
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
895
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|_| Error::not_found(shell.clone()))?;
896
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
897
    let base = app.config.base_url();
898
    let subject = crate::provenance::Subject {
899
        name: &file,
900
        bytes: &bytes,
901
        repo: &format!("{owner}/{name}"),
902
        run_url: &format!("{base}/{owner}/{name}/flow/{id}"),
903
        bookmark: &run.bookmark,
904
        state: &run.state,
905
        heads: &run.heads,
906
        pipeline_hash: &run.pipeline_hash,
907
        job: &j.name,
908
        runner: &j.runner,
909
        receipt_signer: &j.receipt_signer,
910
        receipt_attest: &j.receipt_attest,
911
        started_ms: j.started_ms,
912
        finished_ms: j.finished_ms,
913
    };
914
    let statement = crate::provenance::statement(base, &subject);
915
    let envelope = crate::provenance::envelope(&app, &statement).map_err(|e| Error::bad(shell.clone(), e.to_string()))?;
916
    Ok((
917
        [
918
            (axum::http::header::CONTENT_TYPE, "application/json".to_string()),
919
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}.intoto.json\"", file.replace('"', ""))),
920
        ],
921
        serde_json::to_string(&envelope).unwrap_or_default(),
922
    )
923
        .into_response())
924
}
925
926
/// `GET /.well-known/oxyhub-signing.pem`: the hub's Ed25519 public key, as
927
/// cosign and other verifiers take it (oxygenhub#239).
928
pub async fn signing_key(State(app): State<Shared>) -> Response {
929
    ([(axum::http::header::CONTENT_TYPE, "application/x-pem-file")], crate::provenance::public_pem(&app)).into_response()
930
}
931
932
#[derive(Deserialize)]
933
pub struct AttachForm {
934
    _csrf: String,
935
    release: i64,
936
}
937
938
/// `POST /{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/attach`: add
939
/// an artifact to a release as an asset, named after its path; the release
940
/// page then shows the run and receipt that built it.
941
pub async fn attach(
942
    State(app): State<Shared>,
943
    viewer: Viewer,
944
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
945
    Form(f): Form<AttachForm>,
946
) -> Result<Response, Error> {
947
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer);
948
    require(&viewer, &shell)?;
949
    csrf(&viewer, &f._csrf, &shell)?;
950
    let (repo, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
951
    let run = fdb::run(&app.db, row.id, id)
952
        .await
953
        .map_err(|e| Error::from_db(shell.clone(), e))?
954
        .ok_or_else(|| Error::not_found(shell.clone()))?;
955
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
956
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
957
    // A failing job's `when "always"` artifacts are not in its receipt, so
958
    // they cannot stand for a release (oxygenflow#37).
959
    if j.status != "passed" {
960
        return Err(Error::bad(shell, "only a passing job's artifacts can be attached to a release"));
961
    }
962
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
963
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
964
    let releases = db::releases::list(&app.db, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
965
    let Some(rel) = releases.into_iter().find(|r| r.id == f.release) else { return Err(Error::not_found(shell)) };
966
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
967
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
968
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
969
    super::releases::store_asset(&app, rel.id, &file, "application/octet-stream", &bytes)
970
        .await
971
        .map_err(|m| Error::bad(shell.clone(), m))?;
972
    Ok(Redirect::to(&format!("/{owner}/{name}/releases/tag/{}", rel.tag)).into_response())
973
}
974
975
/// `/{owner}/{name}/flow/badge.svg`: the latest run on the default
976
/// bookmark as a small SVG for a README, for whoever may read the
977
/// repository. `passed` green, `failed` or `error` red, a run still going
978
/// blue, none grey.
979
pub async fn badge(
980
    State(app): State<Shared>,
981
    viewer: Viewer,
982
    Path((owner, name)): Path<(String, String)>,
983
) -> Result<axum::response::Response, Error> {
984
    use axum::response::IntoResponse;
985
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
986
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
987
    let latest = fdb::latest_on(&app.db, row.id, &row.default_bookmark).await.map_err(|e| Error::from_db(shell.clone(), e))?;
988
    let (text, colour) = match latest.as_ref().map(|r| r.status.as_str()) {
989
        Some("passed") => ("passing", "#2da44e"),
990
        Some("failed") | Some("error") => ("failing", "#cf222e"),
991
        Some("cancelled") => ("cancelled", "#6e7781"),
992
        Some(_) => ("running", "#0969da"),
993
        None => ("no runs", "#6e7781"),
994
    };
995
    let label = "OxygenFlow";
996
    let (lw, tw) = (label.len() as u32 * 7 + 10, text.len() as u32 * 7 + 10);
997
    let svg = format!(
998
        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>"##,
999
        w = lw + tw,
1000
        lx = lw / 2,
1001
        tx = lw + tw / 2,
1002
    );
1003
    Ok((
1004
        [(axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"), (axum::http::header::CACHE_CONTROL, "no-cache, max-age=60")],
1005
        svg,
1006
    )
1007
        .into_response())
1008
}