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