OXYGENHUB
# 4fa0da126b70 oxygenhub / crates / hub / src / web / flow.rs
31.5 KiB · Rust · last changed Coverage from a workstation: oh coverage upload, shown as uploaded 24 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 → Flow.".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
pub async fn runs(
62
    State(app): State<Shared>,
63
    viewer: Viewer,
64
    Path((owner, name)): Path<(String, String)>,
65
    Query(q): Query<RunsQuery>,
66
) -> Result<Page<RunsPage>, Error> {
67
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
68
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
69
    let list = fdb::runs(&app.db, row.id, PER_PAGE + 1, q.before).await.map_err(|e| Error::from_db(shell.clone(), e))?;
70
    let older = (list.len() as i64 > PER_PAGE).then(|| list[PER_PAGE as usize - 1].id);
71
    let queue = if list.iter().any(|r| r.live()) { fdb::queue(&app.db).await.unwrap_or_default() } else { vec![] };
72
    let mut runs = Vec::new();
73
    for r in list.into_iter().take(PER_PAGE as usize) {
74
        let place = if r.live() { crate::flow::queue_info(&queue, row.id, r.id).place() } else { None };
75
        let jobs = fdb::jobs(&app.db, r.id).await.unwrap_or_default();
76
        let duration = match r.finished_ms {
77
            Some(f) => crate::flow::human_ms(f - r.created_ms),
78
            None if r.live() => crate::flow::human_ms(db::now_ms() - r.created_ms),
79
            None => "–".into(),
80
        };
81
        runs.push(RunRow { jobs: jobs.into_iter().map(|j| (j.name, j.status)).collect(), duration, r, place });
82
    }
83
    let enabled = crate::flow::enabled(&app, &row);
84
    let why_not = why_not_run(enabled, viewer.account().is_some(), role);
85
    let can_run = why_not.is_none();
86
    let bookmarks = if can_run { bookmark_names(&app, &row).await } else { vec![] };
87
    Ok(Page(RunsPage {
88
        shell,
89
        repo: RepoShell::new(&app, &row, "flow").with_role(role),
90
        runs,
91
        enabled,
92
        older,
93
        can_run,
94
        bookmarks,
95
        error: q.error,
96
        why_not,
97
    }))
98
}
99
100
/// The repository's bookmarks, its default first.
101
async fn bookmark_names(app: &Shared, row: &db::repos::RepoRow) -> Vec<String> {
102
    let Some(repo) = crate::repos::RepoName::new(&row.owner, &row.name) else { return vec![] };
103
    let mut names: Vec<String> = app.repos.read(&repo, |r, _| Ok(r.view()?.bookmarks.keys().cloned().collect())).await.unwrap_or_default();
104
    names.sort_by_key(|n| (n != &row.default_bookmark, n.clone()));
105
    names
106
}
107
108
#[derive(Deserialize)]
109
pub struct StartForm {
110
    #[serde(rename = "_csrf")]
111
    csrf_token: String,
112
    #[serde(default)]
113
    bookmark: String,
114
    /// A change's full hash: run the state whose only head it is.
115
    #[serde(default)]
116
    change: String,
117
}
118
119
/// `POST /{owner}/{name}/flow/start`: "Run pipeline" on a bookmark's
120
/// current state, or on one committed change.
121
pub async fn start(
122
    State(app): State<Shared>,
123
    viewer: Viewer,
124
    Path((owner, name)): Path<(String, String)>,
125
    Form(f): Form<StartForm>,
126
) -> Result<Response, Error> {
127
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
128
    let me = require(&viewer, &shell)?;
129
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
130
    csrf(&viewer, &f.csrf_token, &shell)?;
131
    let (started, what) = if f.change.trim().is_empty() {
132
        (crate::flow::run_bookmark(&app, &row, f.bookmark.trim(), &me.account.username, &[]).await, f.bookmark.trim().to_string())
133
    } else {
134
        (crate::flow::run_change(&app, &row, &f.change, &me.account.username, &[]).await, format!("change {}", f.change.trim()))
135
    };
136
    Ok(match started {
137
        Ok(n) => {
138
            db::accounts::audit(&app.db, Some(&me.account), "flow.run", &format!("{owner}/{name}"), &format!("#{n} {what}")).await.ok();
139
            Redirect::to(&format!("/{owner}/{name}/flow/{n}")).into_response()
140
        }
141
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
142
    })
143
}
144
145
#[derive(Deserialize)]
146
pub struct RerunForm {
147
    #[serde(rename = "_csrf")]
148
    csrf_token: String,
149
}
150
151
/// `POST /{owner}/{name}/flow/{number}/rerun`.
152
pub async fn rerun(
153
    State(app): State<Shared>,
154
    viewer: Viewer,
155
    Path((owner, name, number)): Path<(String, String, i64)>,
156
    Form(f): Form<RerunForm>,
157
) -> Result<Response, Error> {
158
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &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 run = fdb::run(&app.db, row.id, number)
163
        .await
164
        .map_err(|e| Error::from_db(shell.clone(), e))?
165
        .ok_or_else(|| Error::not_found(shell.clone()))?;
166
    Ok(match crate::flow::rerun(&app, &row, &run, &me.account.username).await {
167
        Ok(n) => {
168
            db::accounts::audit(&app.db, Some(&me.account), "flow.rerun", &format!("{owner}/{name}"), &format!("#{n} of #{number}"))
169
                .await
170
                .ok();
171
            Redirect::to(&format!("/{owner}/{name}/flow/{n}")).into_response()
172
        }
173
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
174
    })
175
}
176
177
/// `POST /{owner}/{name}/flow/{number}/cancel` (oxygenflow#32).
178
pub async fn cancel(
179
    State(app): State<Shared>,
180
    viewer: Viewer,
181
    Path((owner, name, number)): Path<(String, String, i64)>,
182
    Form(f): Form<RerunForm>,
183
) -> Result<Response, Error> {
184
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
185
    let me = require(&viewer, &shell)?;
186
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
187
    csrf(&viewer, &f.csrf_token, &shell)?;
188
    let run = fdb::run(&app.db, row.id, number)
189
        .await
190
        .map_err(|e| Error::from_db(shell.clone(), e))?
191
        .ok_or_else(|| Error::not_found(shell.clone()))?;
192
    Ok(match crate::flow::cancel(&app, &row, &run, &me.account.username).await {
193
        Ok(()) => {
194
            db::accounts::audit(&app.db, Some(&me.account), "flow.cancel", &format!("{owner}/{name}"), &format!("#{number}")).await.ok();
195
            Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response()
196
        }
197
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
198
    })
199
}
200
201
/// Percent-encode a message for a query string.
202
fn urlencoding(s: &str) -> String {
203
    s.bytes()
204
        .map(|b| match b {
205
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),
206
            _ => format!("%{b:02X}"),
207
        })
208
        .collect()
209
}
210
211
/// A job placed in the graph.
212
pub struct Node {
213
    pub j: fdb::Job,
214
    pub x: i64,
215
    pub y: i64,
216
    pub duration: String,
217
}
218
219
pub struct Edge {
220
    pub d: String,
221
    pub status: String,
222
}
223
224
pub struct Graph {
225
    pub nodes: Vec<Node>,
226
    pub edges: Vec<Edge>,
227
    pub width: i64,
228
    pub height: i64,
229
}
230
231
pub const NODE_W: i64 = 200;
232
pub const NODE_H: i64 = 48;
233
const COL_GAP: i64 = 72;
234
const ROW_GAP: i64 = 18;
235
const PAD: i64 = 12;
236
237
/// Columns by dependency depth, jobs in each column in name order.
238
pub fn layout(jobs: Vec<fdb::Job>) -> Graph {
239
    let mut by_depth: std::collections::BTreeMap<i64, Vec<fdb::Job>> = Default::default();
240
    for j in jobs {
241
        by_depth.entry(j.depth).or_default().push(j);
242
    }
243
    let rows = by_depth.values().map(Vec::len).max().unwrap_or(0) as i64;
244
    let height = PAD * 2 + rows * NODE_H + (rows - 1).max(0) * ROW_GAP;
245
    let mut nodes = Vec::new();
246
    for (col, (_, mut js)) in by_depth.into_iter().enumerate() {
247
        js.sort_by(|a, b| a.name.cmp(&b.name));
248
        let n = js.len() as i64;
249
        let column_h = n * NODE_H + (n - 1).max(0) * ROW_GAP;
250
        let top = (height - column_h) / 2;
251
        for (i, j) in js.into_iter().enumerate() {
252
            let duration = crate::flow::duration(&j);
253
            nodes.push(Node { x: PAD + col as i64 * (NODE_W + COL_GAP), y: top + i as i64 * (NODE_H + ROW_GAP), duration, j });
254
        }
255
    }
256
    let mut edges = Vec::new();
257
    for n in &nodes {
258
        for d in n.j.depends_on() {
259
            if let Some(from) = nodes.iter().find(|m| m.j.name == d) {
260
                let (x1, y1) = (from.x + NODE_W, from.y + NODE_H / 2);
261
                let (x2, y2) = (n.x, n.y + NODE_H / 2);
262
                let mid = (x1 + x2) / 2;
263
                edges.push(Edge { d: format!("M{x1},{y1} C{mid},{y1} {mid},{y2} {x2},{y2}"), status: from.j.status.clone() });
264
            }
265
        }
266
    }
267
    let cols = nodes.iter().map(|n| n.x).max().map(|x| x + NODE_W + PAD).unwrap_or(PAD * 2);
268
    Graph { nodes, edges, width: cols, height: height.max(NODE_H + PAD * 2) }
269
}
270
271
pub fn glyph(status: &str) -> &'static str {
272
    match status {
273
        "passed" => "✓",
274
        "failed" => "✕",
275
        "running" => "●",
276
        "skipped" => "⤼",
277
        "cancelled" => "⊘",
278
        "error" => "!",
279
        _ => "○",
280
    }
281
}
282
283
/// Failed tests a run page lists per job; the rest are counted.
284
const SHOWN_FAILURES: i64 = 50;
285
286
pub struct JobLog {
287
    pub j: fdb::Job,
288
    pub artifacts: Vec<fdb::Artifact>,
289
    pub lines: Vec<fdb::LogLine>,
290
    pub duration: String,
291
    /// The last line shown; the live view asks for what follows.
292
    pub last_seq: i64,
293
    /// The job's coverage report, when it uploaded one (#113): its id and percentage.
294
    pub coverage: Option<(i64, String)>,
295
    /// The job's test report, when it uploaded one (#114), and its first
296
    /// failures.
297
    pub tests: Option<crate::junit::Report>,
298
    pub failures: Vec<crate::junit::Case>,
299
}
300
301
#[derive(Template)]
302
#[template(path = "flow_run.html")]
303
pub struct RunPage {
304
    shell: Shell,
305
    repo: RepoShell,
306
    run: fdb::Run,
307
    graph: Graph,
308
    logs: Vec<JobLog>,
309
    duration: String,
310
    /// Whether the viewer may re-run it.
311
    can_rerun: bool,
312
    /// Whether the viewer may cancel it.
313
    can_cancel: bool,
314
    /// Where a live run stands among the runners' work.
315
    queue: Option<crate::flow::QueueInfo>,
316
    /// Releases a writer may attach this run's artifacts to.
317
    releases: Vec<db::releases::Release>,
318
}
319
320
/// Lines of a job's log a page shows before "the rest is loaded as it comes".
321
const PAGE_LINES: i64 = 5000;
322
323
pub async fn run(
324
    State(app): State<Shared>,
325
    viewer: Viewer,
326
    Path((owner, name, id)): Path<(String, String, i64)>,
327
) -> Result<Page<RunPage>, Error> {
328
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer);
329
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
330
    let run = fdb::run(&app.db, row.id, id)
331
        .await
332
        .map_err(|e| Error::from_db(shell.clone(), e))?
333
        .ok_or_else(|| Error::not_found(shell.clone()))?;
334
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
335
    let reports = crate::coverage::for_run(&app.db, run.id).await.unwrap_or_default();
336
    let test_reports = crate::junit::for_run(&app.db, run.id).await.unwrap_or_default();
337
    let mut logs = Vec::new();
338
    for j in &jobs {
339
        let lines = fdb::log(&app.db, j.id, 0, PAGE_LINES).await.unwrap_or_default();
340
        let last_seq = lines.last().map(|l| l.seq).unwrap_or(0);
341
        let artifacts = fdb::artifacts(&app.db, j.id).await.unwrap_or_default();
342
        let coverage = reports
343
            .iter()
344
            .find(|r| r.job_id == Some(j.id))
345
            .map(|r| (r.id, r.percent().map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into())));
346
        let tests = test_reports.iter().find(|r| r.job_id == j.id).cloned();
347
        let failures = match &tests {
348
            Some(r) if r.broken() > 0 => crate::junit::failures(&app.db, r.id, SHOWN_FAILURES).await.unwrap_or_default(),
349
            _ => vec![],
350
        };
351
        logs.push(JobLog { duration: crate::flow::duration(j), j: j.clone(), artifacts, lines, last_seq, coverage, tests, failures });
352
    }
353
    let duration = match run.finished_ms {
354
        Some(f) => crate::flow::human_ms(f - run.created_ms),
355
        None => crate::flow::human_ms(db::now_ms() - run.created_ms),
356
    };
357
    let graph = layout(jobs);
358
    let can_write = viewer.account().is_some() && role >= Role::Write;
359
    let can_rerun = !run.live() && can_write && crate::flow::enabled(&app, &row);
360
    let can_cancel = run.live() && can_write;
361
    let queue = if run.live() {
362
        let q = fdb::queue(&app.db).await.unwrap_or_default();
363
        Some(crate::flow::queue_info(&q, row.id, run.id)).filter(|i| i.position.is_some())
364
    } else {
365
        None
366
    };
367
    let releases = if viewer.account().is_some() && role >= Role::Write && logs.iter().any(|l| !l.artifacts.is_empty()) {
368
        db::releases::list(&app.db, row.id).await.unwrap_or_default()
369
    } else {
370
        vec![]
371
    };
372
    Ok(Page(RunPage {
373
        shell,
374
        repo: RepoShell::new(&app, &row, "flow").with_role(role),
375
        run,
376
        graph,
377
        logs,
378
        duration,
379
        can_rerun,
380
        can_cancel,
381
        queue,
382
        releases,
383
    }))
384
}
385
386
#[derive(Deserialize)]
387
pub struct LiveQuery {
388
    /// `job:seq,job:seq`: the last log line each open job already shows.
389
    after: Option<String>,
390
}
391
392
/// `GET /{owner}/{name}/flow/{id}/live`: statuses and new log lines, for the
393
/// run page while it is live.
394
pub async fn live(
395
    State(app): State<Shared>,
396
    viewer: Viewer,
397
    Path((owner, name, id)): Path<(String, String, i64)>,
398
    Query(q): Query<LiveQuery>,
399
) -> Result<Response, Error> {
400
    let shell = Shell::new(&app, "", &viewer);
401
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
402
    let run = fdb::run(&app.db, row.id, id)
403
        .await
404
        .map_err(|e| Error::from_db(shell.clone(), e))?
405
        .ok_or_else(|| Error::not_found(shell.clone()))?;
406
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
407
    let after: std::collections::HashMap<i64, i64> = q
408
        .after
409
        .unwrap_or_default()
410
        .split(',')
411
        .filter_map(|p| p.split_once(':'))
412
        .filter_map(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))
413
        .collect();
414
    let mut out = Vec::new();
415
    for j in &jobs {
416
        let lines = match after.get(&j.id) {
417
            Some(seq) => fdb::log(&app.db, j.id, *seq, 1000).await.unwrap_or_default(),
418
            None => vec![],
419
        };
420
        out.push(serde_json::json!({
421
            "id": j.id,
422
            "name": j.name,
423
            "status": j.status,
424
            "glyph": glyph(&j.status),
425
            "duration": crate::flow::duration(j),
426
            "exit_code": j.exit_code,
427
            "lines": lines.iter().map(|l| serde_json::json!({ "seq": l.seq, "t": l.t, "stream": l.stream, "text": l.text })).collect::<Vec<_>>(),
428
        }));
429
    }
430
    Ok(Json(serde_json::json!({ "status": run.status, "live": run.live(), "jobs": out })).into_response())
431
}
432
433
// ------------------------------------------------------------ state stamps
434
435
/// In rendered Markdown, the image path that is the viewed state's stamp.
436
pub const STAMP_IMAGE: &str = ".flow/stamp";
437
/// In rendered Markdown, the link path to the viewed state's run.
438
pub const RUN_LINK: &str = ".flow/run";
439
440
/// Resolve a ref to its state address, and whether the ref can move.
441
async fn state_of(app: &Shared, owner: &str, name: &str, r: &str) -> Result<(String, bool), crate::repos::RepoError> {
442
    let repo = crate::repos::RepoName::new(owner, name).ok_or(crate::repos::RepoError::NotFound)?;
443
    let spec = r.to_string();
444
    app.repos
445
        .read(&repo, move |repo, cache| {
446
            let t = crate::repos::view::resolve(repo, cache, &spec)?;
447
            let moves = matches!(t.kind, crate::repos::view::RefKind::Bookmark | crate::repos::view::RefKind::Tag);
448
            Ok((t.permalink().unwrap_or_default(), moves))
449
        })
450
        .await
451
}
452
453
/// `GET /{owner}/{name}/flow/stamp/{ref}` (hub spec §13.2).
454
pub async fn stamp(
455
    State(app): State<Shared>,
456
    viewer: Viewer,
457
    Path((owner, name, r)): Path<(String, String, String)>,
458
) -> Result<Response, Error> {
459
    let shell = Shell::new(&app, "", &viewer);
460
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
461
    let (heads, moves) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
462
    if moves && !heads.is_empty() {
463
        let mut res = axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{heads}")).into_response();
464
        res.headers_mut().insert(axum::http::header::CACHE_CONTROL, axum::http::HeaderValue::from_static("no-cache"));
465
        return Ok(res);
466
    }
467
    let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?;
468
    let jobs = match &run {
469
        Some(r) => fdb::jobs(&app.db, r.id).await.map_err(|e| Error::from_db(shell.clone(), e))?,
470
        None => vec![],
471
    };
472
    let svg = stamp_svg(&heads, run.as_ref(), &jobs);
473
    let cache = if run.as_ref().is_some_and(|r| !r.live()) { "public, max-age=3600" } else { "public, max-age=60" };
474
    Ok((
475
        [
476
            (axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"),
477
            (axum::http::header::CACHE_CONTROL, cache),
478
            (axum::http::header::CONTENT_SECURITY_POLICY, "default-src 'none'; style-src 'unsafe-inline'"),
479
        ],
480
        svg,
481
    )
482
        .into_response())
483
}
484
485
/// `GET /{owner}/{name}/flow/at/{ref}`: the run of the ref's state, or the Flow tab.
486
pub async fn at(
487
    State(app): State<Shared>,
488
    viewer: Viewer,
489
    Path((owner, name, r)): Path<(String, String, String)>,
490
) -> Result<Response, Error> {
491
    let shell = Shell::new(&app, "", &viewer);
492
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
493
    let (heads, _) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
494
    let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?;
495
    let to = match run {
496
        Some(r) => format!("/{owner}/{name}/flow/{}", r.number),
497
        None => format!("/{owner}/{name}/flow"),
498
    };
499
    Ok(axum::response::Redirect::to(&to).into_response())
500
}
501
502
fn xml(s: &str) -> String {
503
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
504
}
505
506
/// The stamp: the mark, one glyph per job, the status, the state and the
507
/// date; the same facts machine-readable in `<metadata>`. Fixed colours,
508
/// because an image does not follow the page's theme.
509
pub fn stamp_svg(heads: &str, run: Option<&fdb::Run>, jobs: &[fdb::Job]) -> String {
510
    const CH: f64 = 6.6; // IBM Plex Mono at 11px
511
    let colour = |s: &str| match s {
512
        "passed" => "#5fe3a1",
513
        "failed" | "error" => "#ff5e7a",
514
        "running" => "#00e0f0",
515
        _ => "#8592ad",
516
    };
517
    let short: String = heads.chars().take(12).collect();
518
    let (status, date) = match run {
519
        Some(r) => (r.status.as_str(), crate::render::time::absolute(r.created_ms as u64).chars().take(10).collect::<String>()),
520
        None => ("no run", String::new()),
521
    };
522
    let mut ordered: Vec<&fdb::Job> = jobs.iter().collect();
523
    ordered.sort_by(|a, b| (a.depth, &a.name).cmp(&(b.depth, &b.name)));
524
    let label = "OXYGENFLOW";
525
    let label_w = 14.0 + label.len() as f64 * 6.2 + 8.0;
526
    let glyphs_w = if ordered.is_empty() { 0.0 } else { ordered.len() as f64 * 10.0 + 6.0 };
527
    let tail = if date.is_empty() { format!("{status} · {short}") } else { format!("{status} · {short} · {date}") };
528
    let right_w = 8.0 + glyphs_w + tail.chars().count() as f64 * CH + 8.0;
529
    let w = (label_w + right_w).ceil();
530
    let mut glyphs = String::new();
531
    for (i, j) in ordered.iter().enumerate() {
532
        let x = label_w + 8.0 + i as f64 * 10.0 + 4.0;
533
        glyphs.push_str(&format!(
534
            r#"<text x="{x:.1}" y="15" fill="{}" text-anchor="middle">{}</text>"#,
535
            colour(&j.status),
536
            glyph(&j.status)
537
        ));
538
    }
539
    let meta = serde_json::json!({
540
        "heads": heads.split('+').filter(|h| !h.is_empty()).collect::<Vec<_>>(),
541
        "run": run.map(|r| r.number),
542
        "status": status,
543
        "jobs": ordered.iter().map(|j| serde_json::json!({ "name": j.name, "status": j.status, "receipt": j.receipt_hash })).collect::<Vec<_>>(),
544
    });
545
    let title = match run {
546
        Some(r) => format!("OxygenFlow run #{} {status} on state {short}", r.number),
547
        None => format!("OxygenFlow: no run for state {short}"),
548
    };
549
    format!(
550
        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>"##,
551
        t = xml(&title),
552
        m = xml(&meta.to_string()),
553
        lw = label_w,
554
        lx = label_w - 4.0,
555
        tx = label_w + 8.0 + glyphs_w,
556
        sc = colour(status),
557
        tail = xml(&tail),
558
        wi = w - 1.0,
559
    )
560
}
561
562
/// A receipt kept in a repository (Oxygen spec §14.6), as pages show it.
563
#[derive(Clone, Debug)]
564
pub struct ReceiptRow {
565
    pub attest: String,
566
    pub job: String,
567
    pub exit_code: u32,
568
    pub duration: String,
569
    pub runner: String,
570
    pub run: String,
571
    /// Why it does not verify, or that its runner's key was revoked.
572
    pub problem: String,
573
    pub made_ms: i64,
574
}
575
576
impl ReceiptRow {
577
    pub fn passed(&self) -> bool {
578
        self.exit_code == 0
579
    }
580
}
581
582
/// The receipts kept for the state of `heads`.
583
pub async fn receipts_of(app: &Shared, name: &crate::repos::RepoName, heads: Vec<oxy_core::hash::ChangeHash>) -> Vec<ReceiptRow> {
584
    let base = app.config.base_url();
585
    let found = app.repos.read(name, move |repo, _| Ok(repo.receipts(&heads)?)).await.unwrap_or_default();
586
    found
587
        .into_iter()
588
        .map(|i| {
589
            let r = &i.signed.receipt;
590
            let run = i.signed.run().to_string();
591
            ReceiptRow {
592
                attest: i.attest.to_hex(),
593
                job: r.job_name.clone(),
594
                exit_code: r.exit_code,
595
                duration: crate::flow::human_ms(r.duration_ms as i64),
596
                runner: i.signed.runner.name.clone(),
597
                // Only links to this hub are followed from the page.
598
                run: if run.starts_with(base) { run } else { String::new() },
599
                problem: match (i.problem, i.revoked) {
600
                    (Some(p), _) => p,
601
                    (None, true) => "the runner's key was revoked".into(),
602
                    (None, false) => String::new(),
603
                },
604
                made_ms: i.signed.attest.hlc.wall_ms as i64,
605
            }
606
        })
607
        .collect()
608
}
609
610
/// `GET /{owner}/{name}/receipts/{attest}`: a signed receipt, for
611
/// `oxy receipt verify` or `oxy receipt import`.
612
pub async fn receipt_file(
613
    State(app): State<Shared>,
614
    viewer: Viewer,
615
    Path((owner, name, attest)): Path<(String, String, String)>,
616
) -> Result<Response, Error> {
617
    let shell = Shell::new(&app, &format!("/{owner}/{name}/receipts/{attest}"), &viewer);
618
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
619
    let Some(r) = oxy_core::hash::ObjectRef::from_hex(attest.trim_end_matches(".receipt")) else {
620
        return Err(Error::not_found(shell));
621
    };
622
    let (job, bytes) = app
623
        .repos
624
        .read(&repo, move |repo, _| {
625
            let i = repo.receipt(&r)?;
626
            Ok((i.signed.receipt.job_name.clone(), i.signed.encode()))
627
        })
628
        .await
629
        .map_err(|_| Error::not_found(shell.clone()))?;
630
    let file: String = job.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')).collect();
631
    Ok((
632
        [
633
            (axum::http::header::CONTENT_TYPE, "application/oxy-receipt".to_string()),
634
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{file}-{}.receipt\"", r.short(12))),
635
        ],
636
        bytes,
637
    )
638
        .into_response())
639
}
640
641
/// `GET /{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}`: an artifact
642
/// of a run's job, read from the repository.
643
pub async fn artifact_file(
644
    State(app): State<Shared>,
645
    viewer: Viewer,
646
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
647
) -> Result<Response, Error> {
648
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}"), &viewer);
649
    let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
650
    let run = fdb::run(&app.db, row.id, id)
651
        .await
652
        .map_err(|e| Error::from_db(shell.clone(), e))?
653
        .ok_or_else(|| Error::not_found(shell.clone()))?;
654
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
655
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
656
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
657
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
658
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
659
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|_| Error::not_found(shell.clone()))?;
660
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
661
    Ok((
662
        [
663
            (axum::http::header::CONTENT_TYPE, "application/octet-stream".to_string()),
664
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}\"", file.replace('"', ""))),
665
        ],
666
        bytes,
667
    )
668
        .into_response())
669
}
670
671
#[derive(Deserialize)]
672
pub struct AttachForm {
673
    _csrf: String,
674
    release: i64,
675
}
676
677
/// `POST /{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/attach`: add
678
/// an artifact to a release as an asset, named after its path; the release
679
/// page then shows the run and receipt that built it.
680
pub async fn attach(
681
    State(app): State<Shared>,
682
    viewer: Viewer,
683
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
684
    Form(f): Form<AttachForm>,
685
) -> Result<Response, Error> {
686
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer);
687
    require(&viewer, &shell)?;
688
    csrf(&viewer, &f._csrf, &shell)?;
689
    let (repo, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
690
    let run = fdb::run(&app.db, row.id, id)
691
        .await
692
        .map_err(|e| Error::from_db(shell.clone(), e))?
693
        .ok_or_else(|| Error::not_found(shell.clone()))?;
694
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
695
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
696
    // A failing job's `when "always"` artifacts are not in its receipt, so
697
    // they cannot stand for a release (oxygenflow#37).
698
    if j.status != "passed" {
699
        return Err(Error::bad(shell, "only a passing job's artifacts can be attached to a release"));
700
    }
701
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
702
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
703
    let releases = db::releases::list(&app.db, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
704
    let Some(rel) = releases.into_iter().find(|r| r.id == f.release) else { return Err(Error::not_found(shell)) };
705
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
706
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
707
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
708
    super::releases::store_asset(&app, rel.id, &file, "application/octet-stream", &bytes)
709
        .await
710
        .map_err(|m| Error::bad(shell.clone(), m))?;
711
    Ok(Redirect::to(&format!("/{owner}/{name}/releases/tag/{}", rel.tag)).into_response())
712
}
713
714
/// `/{owner}/{name}/flow/badge.svg`: the latest run on the default
715
/// bookmark as a small SVG for a README, for whoever may read the
716
/// repository. `passed` green, `failed` or `error` red, a run still going
717
/// blue, none grey.
718
pub async fn badge(
719
    State(app): State<Shared>,
720
    viewer: Viewer,
721
    Path((owner, name)): Path<(String, String)>,
722
) -> Result<axum::response::Response, Error> {
723
    use axum::response::IntoResponse;
724
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
725
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
726
    let latest = fdb::latest_on(&app.db, row.id, &row.default_bookmark).await.map_err(|e| Error::from_db(shell.clone(), e))?;
727
    let (text, colour) = match latest.as_ref().map(|r| r.status.as_str()) {
728
        Some("passed") => ("passing", "#2da44e"),
729
        Some("failed") | Some("error") => ("failing", "#cf222e"),
730
        Some("cancelled") => ("cancelled", "#6e7781"),
731
        Some(_) => ("running", "#0969da"),
732
        None => ("no runs", "#6e7781"),
733
    };
734
    let label = "OxygenFlow";
735
    let (lw, tw) = (label.len() as u32 * 7 + 10, text.len() as u32 * 7 + 10);
736
    let svg = format!(
737
        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>"##,
738
        w = lw + tw,
739
        lx = lw / 2,
740
        tx = lw + tw / 2,
741
    );
742
    Ok((
743
        [(axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"), (axum::http::header::CACHE_CONTROL, "no-cache, max-age=60")],
744
        svg,
745
    )
746
        .into_response())
747
}