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