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