OXYGENHUB
# a3c8288b0141 oxygenhub / crates / hub / src / web / flow.rs
22.8 KiB · Rust · last changed Keep and serve Flow job artifacts 1 month 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
}
20
21
#[derive(Template)]
22
#[template(path = "flow_runs.html")]
23
pub struct RunsPage {
24
    shell: Shell,
25
    repo: RepoShell,
26
    runs: Vec<RunRow>,
27
    enabled: bool,
28
    older: Option<i64>,
29
    /// Writers may start runs: the bookmarks to offer, default first.
30
    can_run: bool,
31
    bookmarks: Vec<String>,
32
    error: Option<String>,
33
}
34
35
#[derive(Deserialize)]
36
pub struct RunsQuery {
37
    before: Option<i64>,
38
    /// Why a "Run pipeline" or "Re-run" did not start.
39
    error: Option<String>,
40
}
41
42
const PER_PAGE: i64 = 30;
43
44
pub async fn runs(
45
    State(app): State<Shared>,
46
    viewer: Viewer,
47
    Path((owner, name)): Path<(String, String)>,
48
    Query(q): Query<RunsQuery>,
49
) -> Result<Page<RunsPage>, Error> {
50
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
51
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
52
    let list = fdb::runs(&app.db, row.id, PER_PAGE + 1, q.before).await.map_err(|e| Error::from_db(shell.clone(), e))?;
53
    let older = (list.len() as i64 > PER_PAGE).then(|| list[PER_PAGE as usize - 1].id);
54
    let mut runs = Vec::new();
55
    for r in list.into_iter().take(PER_PAGE as usize) {
56
        let jobs = fdb::jobs(&app.db, r.id).await.unwrap_or_default();
57
        let duration = match r.finished_ms {
58
            Some(f) => crate::flow::human_ms(f - r.created_ms),
59
            None if r.live() => crate::flow::human_ms(db::now_ms() - r.created_ms),
60
            None => "–".into(),
61
        };
62
        runs.push(RunRow { jobs: jobs.into_iter().map(|j| (j.name, j.status)).collect(), duration, r });
63
    }
64
    let enabled = crate::flow::enabled(&app, &row);
65
    let can_run = enabled && viewer.account().is_some() && role >= Role::Write;
66
    let bookmarks = if can_run { bookmark_names(&app, &row).await } else { vec![] };
67
    Ok(Page(RunsPage {
68
        shell,
69
        repo: RepoShell::new(&app, &row, "flow").with_role(role),
70
        runs,
71
        enabled,
72
        older,
73
        can_run,
74
        bookmarks,
75
        error: q.error,
76
    }))
77
}
78
79
/// The repository's bookmarks, its default first.
80
async fn bookmark_names(app: &Shared, row: &db::repos::RepoRow) -> Vec<String> {
81
    let Some(repo) = crate::repos::RepoName::new(&row.owner, &row.name) else { return vec![] };
82
    let mut names: Vec<String> = app.repos.read(&repo, |r, _| Ok(r.view()?.bookmarks.keys().cloned().collect())).await.unwrap_or_default();
83
    names.sort_by_key(|n| (n != &row.default_bookmark, n.clone()));
84
    names
85
}
86
87
#[derive(Deserialize)]
88
pub struct StartForm {
89
    #[serde(rename = "_csrf")]
90
    csrf_token: String,
91
    bookmark: String,
92
}
93
94
/// `POST /{owner}/{name}/flow/start`: "Run pipeline" on a bookmark.
95
pub async fn start(
96
    State(app): State<Shared>,
97
    viewer: Viewer,
98
    Path((owner, name)): Path<(String, String)>,
99
    Form(f): Form<StartForm>,
100
) -> Result<Response, Error> {
101
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer);
102
    let me = require(&viewer, &shell)?;
103
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
104
    csrf(&viewer, &f.csrf_token, &shell)?;
105
    Ok(match crate::flow::run_bookmark(&app, &row, f.bookmark.trim(), &me.account.username).await {
106
        Ok(n) => {
107
            db::accounts::audit(&app.db, Some(&me.account), "flow.run", &format!("{owner}/{name}"), &format!("#{n} {}", f.bookmark.trim()))
108
                .await
109
                .ok();
110
            Redirect::to(&format!("/{owner}/{name}/flow/{n}")).into_response()
111
        }
112
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
113
    })
114
}
115
116
#[derive(Deserialize)]
117
pub struct RerunForm {
118
    #[serde(rename = "_csrf")]
119
    csrf_token: String,
120
}
121
122
/// `POST /{owner}/{name}/flow/{number}/rerun`.
123
pub async fn rerun(
124
    State(app): State<Shared>,
125
    viewer: Viewer,
126
    Path((owner, name, number)): Path<(String, String, i64)>,
127
    Form(f): Form<RerunForm>,
128
) -> Result<Response, Error> {
129
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer);
130
    let me = require(&viewer, &shell)?;
131
    let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?;
132
    csrf(&viewer, &f.csrf_token, &shell)?;
133
    let run = fdb::run(&app.db, row.id, number)
134
        .await
135
        .map_err(|e| Error::from_db(shell.clone(), e))?
136
        .ok_or_else(|| Error::not_found(shell.clone()))?;
137
    Ok(match crate::flow::rerun(&app, &row, &run, &me.account.username).await {
138
        Ok(n) => {
139
            db::accounts::audit(&app.db, Some(&me.account), "flow.rerun", &format!("{owner}/{name}"), &format!("#{n} of #{number}"))
140
                .await
141
                .ok();
142
            Redirect::to(&format!("/{owner}/{name}/flow/{n}")).into_response()
143
        }
144
        Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(),
145
    })
146
}
147
148
/// Percent-encode a message for a query string.
149
fn urlencoding(s: &str) -> String {
150
    s.bytes()
151
        .map(|b| match b {
152
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(),
153
            _ => format!("%{b:02X}"),
154
        })
155
        .collect()
156
}
157
158
/// A job placed in the graph.
159
pub struct Node {
160
    pub j: fdb::Job,
161
    pub x: i64,
162
    pub y: i64,
163
    pub duration: String,
164
}
165
166
pub struct Edge {
167
    pub d: String,
168
    pub status: String,
169
}
170
171
pub struct Graph {
172
    pub nodes: Vec<Node>,
173
    pub edges: Vec<Edge>,
174
    pub width: i64,
175
    pub height: i64,
176
}
177
178
pub const NODE_W: i64 = 200;
179
pub const NODE_H: i64 = 48;
180
const COL_GAP: i64 = 72;
181
const ROW_GAP: i64 = 18;
182
const PAD: i64 = 12;
183
184
/// Columns by dependency depth, jobs in each column in name order.
185
pub fn layout(jobs: Vec<fdb::Job>) -> Graph {
186
    let mut by_depth: std::collections::BTreeMap<i64, Vec<fdb::Job>> = Default::default();
187
    for j in jobs {
188
        by_depth.entry(j.depth).or_default().push(j);
189
    }
190
    let rows = by_depth.values().map(Vec::len).max().unwrap_or(0) as i64;
191
    let height = PAD * 2 + rows * NODE_H + (rows - 1).max(0) * ROW_GAP;
192
    let mut nodes = Vec::new();
193
    for (col, (_, mut js)) in by_depth.into_iter().enumerate() {
194
        js.sort_by(|a, b| a.name.cmp(&b.name));
195
        let n = js.len() as i64;
196
        let column_h = n * NODE_H + (n - 1).max(0) * ROW_GAP;
197
        let top = (height - column_h) / 2;
198
        for (i, j) in js.into_iter().enumerate() {
199
            let duration = crate::flow::duration(&j);
200
            nodes.push(Node { x: PAD + col as i64 * (NODE_W + COL_GAP), y: top + i as i64 * (NODE_H + ROW_GAP), duration, j });
201
        }
202
    }
203
    let mut edges = Vec::new();
204
    for n in &nodes {
205
        for d in n.j.depends_on() {
206
            if let Some(from) = nodes.iter().find(|m| m.j.name == d) {
207
                let (x1, y1) = (from.x + NODE_W, from.y + NODE_H / 2);
208
                let (x2, y2) = (n.x, n.y + NODE_H / 2);
209
                let mid = (x1 + x2) / 2;
210
                edges.push(Edge { d: format!("M{x1},{y1} C{mid},{y1} {mid},{y2} {x2},{y2}"), status: from.j.status.clone() });
211
            }
212
        }
213
    }
214
    let cols = nodes.iter().map(|n| n.x).max().map(|x| x + NODE_W + PAD).unwrap_or(PAD * 2);
215
    Graph { nodes, edges, width: cols, height: height.max(NODE_H + PAD * 2) }
216
}
217
218
pub fn glyph(status: &str) -> &'static str {
219
    match status {
220
        "passed" => "✓",
221
        "failed" => "✕",
222
        "running" => "●",
223
        "skipped" => "⤼",
224
        "error" => "!",
225
        _ => "○",
226
    }
227
}
228
229
pub struct JobLog {
230
    pub j: fdb::Job,
231
    pub artifacts: Vec<fdb::Artifact>,
232
    pub lines: Vec<fdb::LogLine>,
233
    pub duration: String,
234
    /// The last line shown; the live view asks for what follows.
235
    pub last_seq: i64,
236
}
237
238
#[derive(Template)]
239
#[template(path = "flow_run.html")]
240
pub struct RunPage {
241
    shell: Shell,
242
    repo: RepoShell,
243
    run: fdb::Run,
244
    graph: Graph,
245
    logs: Vec<JobLog>,
246
    duration: String,
247
    /// Whether the viewer may re-run it.
248
    can_rerun: bool,
249
}
250
251
/// Lines of a job's log a page shows before "the rest is loaded as it comes".
252
const PAGE_LINES: i64 = 5000;
253
254
pub async fn run(
255
    State(app): State<Shared>,
256
    viewer: Viewer,
257
    Path((owner, name, id)): Path<(String, String, i64)>,
258
) -> Result<Page<RunPage>, Error> {
259
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer);
260
    let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
261
    let run = fdb::run(&app.db, row.id, id)
262
        .await
263
        .map_err(|e| Error::from_db(shell.clone(), e))?
264
        .ok_or_else(|| Error::not_found(shell.clone()))?;
265
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
266
    let mut logs = Vec::new();
267
    for j in &jobs {
268
        let lines = fdb::log(&app.db, j.id, 0, PAGE_LINES).await.unwrap_or_default();
269
        let last_seq = lines.last().map(|l| l.seq).unwrap_or(0);
270
        let artifacts = fdb::artifacts(&app.db, j.id).await.unwrap_or_default();
271
        logs.push(JobLog { duration: crate::flow::duration(j), j: j.clone(), artifacts, lines, last_seq });
272
    }
273
    let duration = match run.finished_ms {
274
        Some(f) => crate::flow::human_ms(f - run.created_ms),
275
        None => crate::flow::human_ms(db::now_ms() - run.created_ms),
276
    };
277
    let graph = layout(jobs);
278
    let can_rerun = !run.live() && viewer.account().is_some() && role >= Role::Write && crate::flow::enabled(&app, &row);
279
    Ok(Page(RunPage { shell, repo: RepoShell::new(&app, &row, "flow").with_role(role), run, graph, logs, duration, can_rerun }))
280
}
281
282
#[derive(Deserialize)]
283
pub struct LiveQuery {
284
    /// `job:seq,job:seq`: the last log line each open job already shows.
285
    after: Option<String>,
286
}
287
288
/// `GET /{owner}/{name}/flow/{id}/live`: statuses and new log lines, for the
289
/// run page while it is live.
290
pub async fn live(
291
    State(app): State<Shared>,
292
    viewer: Viewer,
293
    Path((owner, name, id)): Path<(String, String, i64)>,
294
    Query(q): Query<LiveQuery>,
295
) -> Result<Response, Error> {
296
    let shell = Shell::new(&app, "", &viewer);
297
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
298
    let run = fdb::run(&app.db, row.id, id)
299
        .await
300
        .map_err(|e| Error::from_db(shell.clone(), e))?
301
        .ok_or_else(|| Error::not_found(shell.clone()))?;
302
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
303
    let after: std::collections::HashMap<i64, i64> = q
304
        .after
305
        .unwrap_or_default()
306
        .split(',')
307
        .filter_map(|p| p.split_once(':'))
308
        .filter_map(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?)))
309
        .collect();
310
    let mut out = Vec::new();
311
    for j in &jobs {
312
        let lines = match after.get(&j.id) {
313
            Some(seq) => fdb::log(&app.db, j.id, *seq, 1000).await.unwrap_or_default(),
314
            None => vec![],
315
        };
316
        out.push(serde_json::json!({
317
            "id": j.id,
318
            "name": j.name,
319
            "status": j.status,
320
            "glyph": glyph(&j.status),
321
            "duration": crate::flow::duration(j),
322
            "exit_code": j.exit_code,
323
            "lines": lines.iter().map(|l| serde_json::json!({ "seq": l.seq, "t": l.t, "stream": l.stream, "text": l.text })).collect::<Vec<_>>(),
324
        }));
325
    }
326
    Ok(Json(serde_json::json!({ "status": run.status, "live": run.live(), "jobs": out })).into_response())
327
}
328
329
// ------------------------------------------------------------ state stamps
330
331
/// In rendered Markdown, the image path that is the viewed state's stamp.
332
pub const STAMP_IMAGE: &str = ".flow/stamp";
333
/// In rendered Markdown, the link path to the viewed state's run.
334
pub const RUN_LINK: &str = ".flow/run";
335
336
/// Resolve a ref to its state address, and whether the ref can move.
337
async fn state_of(app: &Shared, owner: &str, name: &str, r: &str) -> Result<(String, bool), crate::repos::RepoError> {
338
    let repo = crate::repos::RepoName::new(owner, name).ok_or(crate::repos::RepoError::NotFound)?;
339
    let spec = r.to_string();
340
    app.repos
341
        .read(&repo, move |repo, cache| {
342
            let t = crate::repos::view::resolve(repo, cache, &spec)?;
343
            let moves = matches!(t.kind, crate::repos::view::RefKind::Bookmark | crate::repos::view::RefKind::Tag);
344
            Ok((t.permalink().unwrap_or_default(), moves))
345
        })
346
        .await
347
}
348
349
/// `GET /{owner}/{name}/flow/stamp/{ref}` (hub spec §13.2).
350
pub async fn stamp(
351
    State(app): State<Shared>,
352
    viewer: Viewer,
353
    Path((owner, name, r)): Path<(String, String, String)>,
354
) -> Result<Response, Error> {
355
    let shell = Shell::new(&app, "", &viewer);
356
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
357
    let (heads, moves) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
358
    if moves && !heads.is_empty() {
359
        let mut res = axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{heads}")).into_response();
360
        res.headers_mut().insert(axum::http::header::CACHE_CONTROL, axum::http::HeaderValue::from_static("no-cache"));
361
        return Ok(res);
362
    }
363
    let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?;
364
    let jobs = match &run {
365
        Some(r) => fdb::jobs(&app.db, r.id).await.map_err(|e| Error::from_db(shell.clone(), e))?,
366
        None => vec![],
367
    };
368
    let svg = stamp_svg(&heads, run.as_ref(), &jobs);
369
    let cache = if run.as_ref().is_some_and(|r| !r.live()) { "public, max-age=3600" } else { "public, max-age=60" };
370
    Ok((
371
        [
372
            (axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"),
373
            (axum::http::header::CACHE_CONTROL, cache),
374
            (axum::http::header::CONTENT_SECURITY_POLICY, "default-src 'none'; style-src 'unsafe-inline'"),
375
        ],
376
        svg,
377
    )
378
        .into_response())
379
}
380
381
/// `GET /{owner}/{name}/flow/at/{ref}`: the run of the ref's state, or the Flow tab.
382
pub async fn at(
383
    State(app): State<Shared>,
384
    viewer: Viewer,
385
    Path((owner, name, r)): Path<(String, String, String)>,
386
) -> Result<Response, Error> {
387
    let shell = Shell::new(&app, "", &viewer);
388
    let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
389
    let (heads, _) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
390
    let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?;
391
    let to = match run {
392
        Some(r) => format!("/{owner}/{name}/flow/{}", r.number),
393
        None => format!("/{owner}/{name}/flow"),
394
    };
395
    Ok(axum::response::Redirect::to(&to).into_response())
396
}
397
398
fn xml(s: &str) -> String {
399
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
400
}
401
402
/// The stamp: the mark, one glyph per job, the status, the state and the
403
/// date; the same facts machine-readable in `<metadata>`. Fixed colours,
404
/// because an image does not follow the page's theme.
405
pub fn stamp_svg(heads: &str, run: Option<&fdb::Run>, jobs: &[fdb::Job]) -> String {
406
    const CH: f64 = 6.6; // IBM Plex Mono at 11px
407
    let colour = |s: &str| match s {
408
        "passed" => "#5fe3a1",
409
        "failed" | "error" => "#ff5e7a",
410
        "running" => "#00e0f0",
411
        _ => "#8592ad",
412
    };
413
    let short: String = heads.chars().take(12).collect();
414
    let (status, date) = match run {
415
        Some(r) => (r.status.as_str(), crate::render::time::absolute(r.created_ms as u64).chars().take(10).collect::<String>()),
416
        None => ("no run", String::new()),
417
    };
418
    let mut ordered: Vec<&fdb::Job> = jobs.iter().collect();
419
    ordered.sort_by(|a, b| (a.depth, &a.name).cmp(&(b.depth, &b.name)));
420
    let label = "OXYGENFLOW";
421
    let label_w = 14.0 + label.len() as f64 * 6.2 + 8.0;
422
    let glyphs_w = if ordered.is_empty() { 0.0 } else { ordered.len() as f64 * 10.0 + 6.0 };
423
    let tail = if date.is_empty() { format!("{status} · {short}") } else { format!("{status} · {short} · {date}") };
424
    let right_w = 8.0 + glyphs_w + tail.chars().count() as f64 * CH + 8.0;
425
    let w = (label_w + right_w).ceil();
426
    let mut glyphs = String::new();
427
    for (i, j) in ordered.iter().enumerate() {
428
        let x = label_w + 8.0 + i as f64 * 10.0 + 4.0;
429
        glyphs.push_str(&format!(
430
            r#"<text x="{x:.1}" y="15" fill="{}" text-anchor="middle">{}</text>"#,
431
            colour(&j.status),
432
            glyph(&j.status)
433
        ));
434
    }
435
    let meta = serde_json::json!({
436
        "heads": heads.split('+').filter(|h| !h.is_empty()).collect::<Vec<_>>(),
437
        "run": run.map(|r| r.number),
438
        "status": status,
439
        "jobs": ordered.iter().map(|j| serde_json::json!({ "name": j.name, "status": j.status, "receipt": j.receipt_hash })).collect::<Vec<_>>(),
440
    });
441
    let title = match run {
442
        Some(r) => format!("OxygenFlow run #{} {status} on state {short}", r.number),
443
        None => format!("OxygenFlow: no run for state {short}"),
444
    };
445
    format!(
446
        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>"##,
447
        t = xml(&title),
448
        m = xml(&meta.to_string()),
449
        lw = label_w,
450
        lx = label_w - 4.0,
451
        tx = label_w + 8.0 + glyphs_w,
452
        sc = colour(status),
453
        tail = xml(&tail),
454
        wi = w - 1.0,
455
    )
456
}
457
458
/// A receipt kept in a repository (Oxygen spec §14.6), as pages show it.
459
#[derive(Clone, Debug)]
460
pub struct ReceiptRow {
461
    pub attest: String,
462
    pub job: String,
463
    pub exit_code: u32,
464
    pub duration: String,
465
    pub runner: String,
466
    pub run: String,
467
    /// Why it does not verify, or that its runner's key was revoked.
468
    pub problem: String,
469
    pub made_ms: i64,
470
}
471
472
impl ReceiptRow {
473
    pub fn passed(&self) -> bool {
474
        self.exit_code == 0
475
    }
476
}
477
478
/// The receipts kept for the state of `heads`.
479
pub async fn receipts_of(app: &Shared, name: &crate::repos::RepoName, heads: Vec<oxy_core::hash::ChangeHash>) -> Vec<ReceiptRow> {
480
    let base = app.config.base_url();
481
    let found = app.repos.read(name, move |repo, _| Ok(repo.receipts(&heads)?)).await.unwrap_or_default();
482
    found
483
        .into_iter()
484
        .map(|i| {
485
            let r = &i.signed.receipt;
486
            let run = i.signed.run().to_string();
487
            ReceiptRow {
488
                attest: i.attest.to_hex(),
489
                job: r.job_name.clone(),
490
                exit_code: r.exit_code,
491
                duration: crate::flow::human_ms(r.duration_ms as i64),
492
                runner: i.signed.runner.name.clone(),
493
                // Only links to this hub are followed from the page.
494
                run: if run.starts_with(base) { run } else { String::new() },
495
                problem: match (i.problem, i.revoked) {
496
                    (Some(p), _) => p,
497
                    (None, true) => "the runner's key was revoked".into(),
498
                    (None, false) => String::new(),
499
                },
500
                made_ms: i.signed.attest.hlc.wall_ms as i64,
501
            }
502
        })
503
        .collect()
504
}
505
506
/// `GET /{owner}/{name}/receipts/{attest}`: a signed receipt, for
507
/// `oxy receipt verify` or `oxy receipt import`.
508
pub async fn receipt_file(
509
    State(app): State<Shared>,
510
    viewer: Viewer,
511
    Path((owner, name, attest)): Path<(String, String, String)>,
512
) -> Result<Response, Error> {
513
    let shell = Shell::new(&app, &format!("/{owner}/{name}/receipts/{attest}"), &viewer);
514
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
515
    let Some(r) = oxy_core::hash::ObjectRef::from_hex(attest.trim_end_matches(".receipt")) else {
516
        return Err(Error::not_found(shell));
517
    };
518
    let (job, bytes) = app
519
        .repos
520
        .read(&repo, move |repo, _| {
521
            let i = repo.receipt(&r)?;
522
            Ok((i.signed.receipt.job_name.clone(), i.signed.encode()))
523
        })
524
        .await
525
        .map_err(|_| Error::not_found(shell.clone()))?;
526
    let file: String = job.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')).collect();
527
    Ok((
528
        [
529
            (axum::http::header::CONTENT_TYPE, "application/oxy-receipt".to_string()),
530
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{file}-{}.receipt\"", r.short(12))),
531
        ],
532
        bytes,
533
    )
534
        .into_response())
535
}
536
537
/// `GET /{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}`: an artifact
538
/// of a run's job, read from the repository.
539
pub async fn artifact_file(
540
    State(app): State<Shared>,
541
    viewer: Viewer,
542
    Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>,
543
) -> Result<Response, Error> {
544
    let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}"), &viewer);
545
    let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
546
    let run = fdb::run(&app.db, row.id, id)
547
        .await
548
        .map_err(|e| Error::from_db(shell.clone(), e))?
549
        .ok_or_else(|| Error::not_found(shell.clone()))?;
550
    let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
551
    let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) };
552
    let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
553
    let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) };
554
    let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) };
555
    let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|_| Error::not_found(shell.clone()))?;
556
    let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string();
557
    Ok((
558
        [
559
            (axum::http::header::CONTENT_TYPE, "application/octet-stream".to_string()),
560
            (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}\"", file.replace('"', ""))),
561
        ],
562
        bytes,
563
    )
564
        .into_response())
565
}