| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | | use super::settings::{csrf, require}; |
| 5 | | use super::{filters, lookup, lookup_role, Error, Page, RepoShell, Shell}; |
| 6 | | use crate::auth::{Access, Role, Viewer}; |
| 7 | | use crate::db::{self, flow as fdb}; |
| 8 | | use crate::Shared; |
| 9 | | use askama::Template; |
| 10 | | use axum::extract::{Form, Path, Query, State}; |
| 11 | | use axum::response::{IntoResponse, Redirect, Response}; |
| 12 | | use axum::Json; |
| 13 | | use serde::Deserialize; |
| 14 | |
|
| 15 | | pub struct RunRow { |
| 16 | | pub r: fdb::Run, |
| 17 | | pub duration: String, |
| 18 | | pub jobs: Vec<(String, String)>, |
| 19 | | |
| 20 | | pub place: Option<String>, |
| 21 | | } |
| 22 | |
|
| 23 | | #[derive(Template)] |
| 24 | | #[template(path = "flow_runs.html")] |
| 25 | | pub struct RunsPage { |
| 26 | | shell: Shell, |
| 27 | | repo: RepoShell, |
| 28 | | runs: Vec<RunRow>, |
| 29 | | enabled: bool, |
| 30 | | older: Option<i64>, |
| 31 | | |
| 32 | | can_run: bool, |
| 33 | | bookmarks: Vec<String>, |
| 34 | | error: Option<String>, |
| 35 | | |
| 36 | | why_not: Option<String>, |
| 37 | | } |
| 38 | |
|
| 39 | | #[derive(Deserialize)] |
| 40 | | pub struct RunsQuery { |
| 41 | | before: Option<i64>, |
| 42 | | |
| 43 | | error: Option<String>, |
| 44 | | } |
| 45 | |
|
| 46 | |
|
| 47 | 38× | pub fn why_not_run(enabled: bool, signed_in: bool, role: Role) -> Option<String> { |
| 48 | 38× | if !enabled { |
| 49 | 30× | Some("Flow is off for this repository; a site administrator can turn it on in Settings › Pipelines.".into()) |
| 50 | 8× | } else if !signed_in { |
| 51 | 7× | Some("Sign in with write access to run the pipeline.".into()) |
| 52 | 1× | } else if role < Role::Write { |
| 53 | 0× | Some("Running the pipeline needs write access to this repository.".into()) |
| 54 | | } else { |
| 55 | 1× | None |
| 56 | | } |
| 57 | 38× | } |
| 58 | |
|
| 59 | | const PER_PAGE: i64 = 30; |
| 60 | |
|
| 61 | | #[derive(Template)] |
| 62 | | #[template(path = "deployments.html")] |
| 63 | | pub struct DeploymentsPage { |
| 64 | | shell: Shell, |
| 65 | | repo: RepoShell, |
| 66 | | |
| 67 | | current: Vec<fdb::Deployment>, |
| 68 | | |
| 69 | | history: Vec<fdb::Deployment>, |
| 70 | | } |
| 71 | |
|
| 72 | |
|
| 73 | |
|
| 74 | 1× | pub async fn deployments( |
| 75 | 1× | State(app): State<Shared>, |
| 76 | 1× | viewer: Viewer, |
| 77 | 1× | Path((owner, name)): Path<(String, String)>, |
| 78 | 1× | ) -> Result<Page<DeploymentsPage>, Error> { |
| 79 | 1× | let shell = Shell::new(&app, &format!("/{owner}/{name}/deployments"), &viewer); |
| 80 | 1× | let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 81 | 1× | let history = fdb::deployments(&app.db, row.id, 50).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 82 | 1× | let mut current: Vec<fdb::Deployment> = Vec::new(); |
| 83 | 1× | for d in &history { |
| 84 | 1× | if !current.iter().any(|c| c.environment == d.environment) { |
| 85 | 1× | current.push(d.clone()); |
| 86 | 1× | } |
| 87 | | } |
| 88 | 1× | current.sort_by(|a, b| a.environment.cmp(&b.environment)); |
| 89 | 1× | Ok(Page(DeploymentsPage { shell, repo: RepoShell::new(&app, &row, "flow").with_role(role), current, history })) |
| 90 | 1× | } |
| 91 | |
|
| 92 | 8× | pub async fn runs( |
| 93 | 8× | State(app): State<Shared>, |
| 94 | 8× | viewer: Viewer, |
| 95 | 8× | Path((owner, name)): Path<(String, String)>, |
| 96 | 8× | Query(q): Query<RunsQuery>, |
| 97 | 8× | ) -> Result<Page<RunsPage>, Error> { |
| 98 | 8× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer); |
| 99 | 8× | let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 100 | 8× | let list = fdb::runs(&app.db, row.id, PER_PAGE + 1, q.before).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 101 | 8× | let older = (list.len() as i64 > PER_PAGE).then(|| list[PER_PAGE as usize - 1].id); |
| 102 | 8× | let queue = if list.iter().any(|r| r.live()) { fdb::queue(&app.db).await.unwrap_or_default() } else { vec![] }; |
| 103 | 8× | let mut runs = Vec::new(); |
| 104 | 11× | for r in list.into_iter().take(PER_PAGE as usize) { |
| 105 | 11× | let place = if r.live() { crate::flow::queue_info(&queue, row.id, r.id).place() } else { None }; |
| 106 | 11× | let jobs = fdb::jobs(&app.db, r.id).await.unwrap_or_default(); |
| 107 | 11× | let duration = match r.finished_ms { |
| 108 | 3× | Some(f) => crate::flow::human_ms(f - r.created_ms), |
| 109 | 8× | None if r.live() => crate::flow::human_ms(db::now_ms() - r.created_ms), |
| 110 | 0× | None => "–".into(), |
| 111 | | }; |
| 112 | 30× | runs.push(RunRow { jobs: jobs.into_iter().map(|j| (j.name, j.status)).collect(), duration, r, place }); |
| 113 | | } |
| 114 | 8× | let enabled = crate::flow::enabled(&app, &row); |
| 115 | 8× | let why_not = why_not_run(enabled, viewer.account().is_some(), role); |
| 116 | 8× | let can_run = why_not.is_none(); |
| 117 | 8× | let bookmarks = if can_run { bookmark_names(&app, &row).await } else { vec![] }; |
| 118 | 8× | Ok(Page(RunsPage { |
| 119 | 8× | shell, |
| 120 | 8× | repo: RepoShell::new(&app, &row, "flow").with_role(role), |
| 121 | 8× | runs, |
| 122 | 8× | enabled, |
| 123 | 8× | older, |
| 124 | 8× | can_run, |
| 125 | 8× | bookmarks, |
| 126 | 8× | error: q.error, |
| 127 | 8× | why_not, |
| 128 | 8× | })) |
| 129 | 8× | } |
| 130 | |
|
| 131 | |
|
| 132 | | #[derive(serde::Serialize)] |
| 133 | | pub struct TabJob { |
| 134 | | name: String, |
| 135 | | exec: Vec<String>, |
| 136 | | env: std::collections::BTreeMap<String, String>, |
| 137 | | memory_mib: u32, |
| 138 | | } |
| 139 | |
|
| 140 | | #[derive(Template)] |
| 141 | | #[template(path = "flow_tab.html")] |
| 142 | | pub struct TabPage { |
| 143 | | shell: Shell, |
| 144 | | repo: RepoShell, |
| 145 | | bookmark: String, |
| 146 | | bookmarks: Vec<String>, |
| 147 | | |
| 148 | | jobs_json: String, |
| 149 | | jobs: usize, |
| 150 | | |
| 151 | | |
| 152 | | problem: Option<String>, |
| 153 | | archive: String, |
| 154 | | } |
| 155 | |
|
| 156 | | #[derive(Deserialize)] |
| 157 | | pub struct TabQuery { |
| 158 | | bookmark: Option<String>, |
| 159 | | } |
| 160 | |
|
| 161 | |
|
| 162 | |
|
| 163 | 2× | pub fn wasm_jobs(p: &flow_core::Pipeline) -> Vec<TabJob> { |
| 164 | 2× | p.jobs |
| 165 | 2× | .values() |
| 166 | 2× | .filter_map(|j| { |
| 167 | 2× | let sb = p.sandboxes.get(&j.sandbox)?; |
| 168 | 2× | (sb.runtime == flow_core::Runtime::Wasm && !j.exec.is_empty()).then(|| { |
| 169 | 2× | let mut env = sb.env.clone(); |
| 170 | 2× | env.extend(j.env.clone()); |
| 171 | 2× | TabJob { name: j.name.clone(), exec: j.exec.clone(), env, memory_mib: sb.memory_mib } |
| 172 | 2× | }) |
| 173 | 2× | }) |
| 174 | 2× | .collect() |
| 175 | 2× | } |
| 176 | |
|
| 177 | |
|
| 178 | |
|
| 179 | |
|
| 180 | |
|
| 181 | |
|
| 182 | 2× | pub async fn tab( |
| 183 | 2× | State(app): State<Shared>, |
| 184 | 2× | viewer: Viewer, |
| 185 | 2× | Path((owner, name)): Path<(String, String)>, |
| 186 | 2× | Query(q): Query<TabQuery>, |
| 187 | 2× | ) -> Result<Page<TabPage>, Error> { |
| 188 | 2× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/tab"), &viewer); |
| 189 | 2× | let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 190 | 2× | let bookmarks = bookmark_names(&app, &row).await; |
| 191 | 2× | let bookmark = q.bookmark.filter(|b| bookmarks.contains(b)).unwrap_or_else(|| row.default_bookmark.clone()); |
| 192 | 2× | let b = bookmark.clone(); |
| 193 | 2× | let text = app |
| 194 | 2× | .repos |
| 195 | 2× | .read(&repo, move |r, cache| { |
| 196 | 2× | let Some(st) = r.view()?.bookmarks.get(&b).copied() else { return Ok(None) }; |
| 197 | 2× | let heads = r.store().get_state(&st)?.heads; |
| 198 | 2× | let loaded = cache.load(r, &heads)?; |
| 199 | 2× | Ok(match loaded.snapshot.files.get(flow_core::PIPELINE_PATH).map(|f| &f.content) { |
| 200 | 2× | Some(oxy_core::state::FileContent::Text { bytes, .. }) => Some(String::from_utf8_lossy(bytes).into_owned()), |
| 201 | 0× | _ => None, |
| 202 | | }) |
| 203 | 2× | }) |
| 204 | 2× | .await |
| 205 | 2× | .unwrap_or(None); |
| 206 | 2× | let (jobs, problem) = match text.map(|t| flow_core::Pipeline::parse(&t)) { |
| 207 | 0× | None => (vec![], Some(format!("{bookmark} has no {}.", flow_core::PIPELINE_PATH))), |
| 208 | 0× | Some(Err(e)) => (vec![], Some(format!("The pipeline on {bookmark} does not read: {e}"))), |
| 209 | 2× | Some(Ok(p)) => { |
| 210 | 2× | let jobs = wasm_jobs(&p); |
| 211 | 2× | let problem = |
| 212 | 2× | jobs.is_empty().then(|| format!("The pipeline on {bookmark} has no WASM jobs (a sandbox with runtime \"wasm\").")); |
| 213 | 2× | (jobs, problem) |
| 214 | | } |
| 215 | | }; |
| 216 | | Ok(Page(TabPage { |
| 217 | 2× | shell, |
| 218 | 2× | repo: RepoShell::new(&app, &row, "flow").with_role(role), |
| 219 | 2× | archive: format!("/{owner}/{name}/archive?ref={}&format=zip", urlencoding(&bookmark)), |
| 220 | 2× | bookmark, |
| 221 | 2× | bookmarks, |
| 222 | 2× | jobs: jobs.len(), |
| 223 | 2× | jobs_json: serde_json::to_string(&jobs).unwrap_or_else(|_| "[]".into()), |
| 224 | 2× | problem, |
| 225 | | })) |
| 226 | 2× | } |
| 227 | |
|
| 228 | |
|
| 229 | 3× | async fn bookmark_names(app: &Shared, row: &db::repos::RepoRow) -> Vec<String> { |
| 230 | 3× | let Some(repo) = crate::repos::RepoName::new(&row.owner, &row.name) else { return vec![] }; |
| 231 | 3× | let mut names: Vec<String> = app.repos.read(&repo, |r, _| Ok(r.view()?.bookmarks.keys().cloned().collect())).await.unwrap_or_default(); |
| 232 | 3× | names.sort_by_key(|n| (n != &row.default_bookmark, n.clone())); |
| 233 | 3× | names |
| 234 | 3× | } |
| 235 | |
|
| 236 | | #[derive(Deserialize)] |
| 237 | | pub struct StartForm { |
| 238 | | #[serde(rename = "_csrf")] |
| 239 | | csrf_token: String, |
| 240 | | #[serde(default)] |
| 241 | | bookmark: String, |
| 242 | | |
| 243 | | #[serde(default)] |
| 244 | | change: String, |
| 245 | | } |
| 246 | |
|
| 247 | |
|
| 248 | |
|
| 249 | 0× | pub async fn start( |
| 250 | 0× | State(app): State<Shared>, |
| 251 | 0× | viewer: Viewer, |
| 252 | 0× | Path((owner, name)): Path<(String, String)>, |
| 253 | 0× | Form(f): Form<StartForm>, |
| 254 | 0× | ) -> Result<Response, Error> { |
| 255 | 0× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer); |
| 256 | 0× | let me = require(&viewer, &shell)?; |
| 257 | 0× | let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?; |
| 258 | 0× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 259 | 0× | let (started, what) = if f.change.trim().is_empty() { |
| 260 | 0× | (crate::flow::run_bookmark(&app, &row, f.bookmark.trim(), &me.account.username, &[]).await, f.bookmark.trim().to_string()) |
| 261 | | } else { |
| 262 | 0× | (crate::flow::run_change(&app, &row, &f.change, &me.account.username, &[]).await, format!("change {}", f.change.trim())) |
| 263 | | }; |
| 264 | 0× | Ok(match started { |
| 265 | 0× | Ok(n) => { |
| 266 | 0× | db::accounts::audit(&app.db, Some(&me.account), "flow.run", &format!("{owner}/{name}"), &format!("#{n} {what}")).await.ok(); |
| 267 | 0× | Redirect::to(&format!("/{owner}/{name}/flow/{n}")).into_response() |
| 268 | | } |
| 269 | 0× | Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(), |
| 270 | | }) |
| 271 | 0× | } |
| 272 | |
|
| 273 | | #[derive(Deserialize)] |
| 274 | | pub struct RerunForm { |
| 275 | | #[serde(rename = "_csrf")] |
| 276 | | csrf_token: String, |
| 277 | | } |
| 278 | |
|
| 279 | |
|
| 280 | 0× | pub async fn rerun( |
| 281 | 0× | State(app): State<Shared>, |
| 282 | 0× | viewer: Viewer, |
| 283 | 0× | Path((owner, name, number)): Path<(String, String, i64)>, |
| 284 | 0× | Form(f): Form<RerunForm>, |
| 285 | 0× | ) -> Result<Response, Error> { |
| 286 | 0× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer); |
| 287 | 0× | let me = require(&viewer, &shell)?; |
| 288 | 0× | let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?; |
| 289 | 0× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 290 | 0× | let run = fdb::run(&app.db, row.id, number) |
| 291 | 0× | .await |
| 292 | 0× | .map_err(|e| Error::from_db(shell.clone(), e))? |
| 293 | 0× | .ok_or_else(|| Error::not_found(shell.clone()))?; |
| 294 | 0× | Ok(match crate::flow::rerun(&app, &row, &run, &me.account.username).await { |
| 295 | 0× | Ok(n) => { |
| 296 | 0× | db::accounts::audit(&app.db, Some(&me.account), "flow.rerun", &format!("{owner}/{name}"), &format!("#{n} of #{number}")) |
| 297 | 0× | .await |
| 298 | 0× | .ok(); |
| 299 | 0× | Redirect::to(&format!("/{owner}/{name}/flow/{n}")).into_response() |
| 300 | | } |
| 301 | 0× | Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(), |
| 302 | | }) |
| 303 | 0× | } |
| 304 | |
|
| 305 | |
|
| 306 | 0× | pub async fn rerun_job( |
| 307 | 0× | State(app): State<Shared>, |
| 308 | 0× | viewer: Viewer, |
| 309 | 0× | Path((owner, name, number, job)): Path<(String, String, i64, String)>, |
| 310 | 0× | Form(f): Form<RerunForm>, |
| 311 | 0× | ) -> Result<Response, Error> { |
| 312 | 0× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer); |
| 313 | 0× | let me = require(&viewer, &shell)?; |
| 314 | 0× | let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?; |
| 315 | 0× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 316 | 0× | let run = fdb::run(&app.db, row.id, number) |
| 317 | 0× | .await |
| 318 | 0× | .map_err(|e| Error::from_db(shell.clone(), e))? |
| 319 | 0× | .ok_or_else(|| Error::not_found(shell.clone()))?; |
| 320 | 0× | Ok(match crate::flow::rerun_job(&app, &row, &run, &job, &me.account.username).await { |
| 321 | | Ok(_) => { |
| 322 | 0× | db::accounts::audit(&app.db, Some(&me.account), "flow.rerun", &format!("{owner}/{name}"), &format!("{job} of #{number}")) |
| 323 | 0× | .await |
| 324 | 0× | .ok(); |
| 325 | 0× | Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response() |
| 326 | | } |
| 327 | 0× | Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(), |
| 328 | | }) |
| 329 | 0× | } |
| 330 | |
|
| 331 | |
|
| 332 | 0× | pub async fn cancel( |
| 333 | 0× | State(app): State<Shared>, |
| 334 | 0× | viewer: Viewer, |
| 335 | 0× | Path((owner, name, number)): Path<(String, String, i64)>, |
| 336 | 0× | Form(f): Form<RerunForm>, |
| 337 | 0× | ) -> Result<Response, Error> { |
| 338 | 0× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer); |
| 339 | 0× | let me = require(&viewer, &shell)?; |
| 340 | 0× | let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?; |
| 341 | 0× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 342 | 0× | let run = fdb::run(&app.db, row.id, number) |
| 343 | 0× | .await |
| 344 | 0× | .map_err(|e| Error::from_db(shell.clone(), e))? |
| 345 | 0× | .ok_or_else(|| Error::not_found(shell.clone()))?; |
| 346 | 0× | Ok(match crate::flow::cancel(&app, &row, &run, &me.account.username).await { |
| 347 | | Ok(()) => { |
| 348 | 0× | db::accounts::audit(&app.db, Some(&me.account), "flow.cancel", &format!("{owner}/{name}"), &format!("#{number}")).await.ok(); |
| 349 | 0× | Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response() |
| 350 | | } |
| 351 | 0× | Err(msg) => Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response(), |
| 352 | | }) |
| 353 | 0× | } |
| 354 | |
|
| 355 | | #[derive(Deserialize)] |
| 356 | | pub struct ExpediteForm { |
| 357 | | #[serde(rename = "_csrf")] |
| 358 | | csrf_token: String, |
| 359 | | #[serde(default)] |
| 360 | | reason: String, |
| 361 | | } |
| 362 | |
|
| 363 | |
|
| 364 | |
|
| 365 | |
|
| 366 | 1× | pub async fn expedite( |
| 367 | 1× | State(app): State<Shared>, |
| 368 | 1× | viewer: Viewer, |
| 369 | 1× | Path((owner, name, number)): Path<(String, String, i64)>, |
| 370 | 1× | Form(f): Form<ExpediteForm>, |
| 371 | 1× | ) -> Result<Response, Error> { |
| 372 | 1× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer); |
| 373 | 1× | let me = require(&viewer, &shell)?; |
| 374 | 1× | let (_, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Maintain).await?; |
| 375 | 1× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 376 | 1× | let run = fdb::run(&app.db, row.id, number) |
| 377 | 1× | .await |
| 378 | 1× | .map_err(|e| Error::from_db(shell.clone(), e))? |
| 379 | 1× | .ok_or_else(|| Error::not_found(shell.clone()))?; |
| 380 | 1× | if let Err(msg) = crate::flow::expedite(&app, &row, &run, &me.account, &f.reason).await { |
| 381 | 0× | return Ok(Redirect::to(&format!("/{owner}/{name}/flow?error={}", urlencoding(&msg))).into_response()); |
| 382 | 1× | } |
| 383 | 1× | Ok(Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response()) |
| 384 | 1× | } |
| 385 | |
|
| 386 | |
|
| 387 | 2× | fn urlencoding(s: &str) -> String { |
| 388 | 2× | s.bytes() |
| 389 | 8× | .map(|b| match b { |
| 390 | 8× | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => (b as char).to_string(), |
| 391 | 0× | _ => format!("%{b:02X}"), |
| 392 | 8× | }) |
| 393 | 2× | .collect() |
| 394 | 2× | } |
| 395 | |
|
| 396 | |
|
| 397 | | pub struct Node { |
| 398 | | pub j: fdb::Job, |
| 399 | | pub x: i64, |
| 400 | | pub y: i64, |
| 401 | | pub duration: String, |
| 402 | | } |
| 403 | |
|
| 404 | | pub struct Edge { |
| 405 | | pub d: String, |
| 406 | | pub status: String, |
| 407 | | } |
| 408 | |
|
| 409 | | pub struct Graph { |
| 410 | | pub nodes: Vec<Node>, |
| 411 | | pub edges: Vec<Edge>, |
| 412 | | pub width: i64, |
| 413 | | pub height: i64, |
| 414 | | } |
| 415 | |
|
| 416 | | pub const NODE_W: i64 = 200; |
| 417 | | pub const NODE_H: i64 = 48; |
| 418 | | const COL_GAP: i64 = 72; |
| 419 | | const ROW_GAP: i64 = 18; |
| 420 | | const PAD: i64 = 12; |
| 421 | |
|
| 422 | |
|
| 423 | 23× | pub fn layout(jobs: Vec<fdb::Job>) -> Graph { |
| 424 | 23× | let mut by_depth: std::collections::BTreeMap<i64, Vec<fdb::Job>> = Default::default(); |
| 425 | 54× | for j in jobs { |
| 426 | 54× | by_depth.entry(j.depth).or_default().push(j); |
| 427 | 54× | } |
| 428 | 23× | let rows = by_depth.values().map(Vec::len).max().unwrap_or(0) as i64; |
| 429 | 23× | let height = PAD * 2 + rows * NODE_H + (rows - 1).max(0) * ROW_GAP; |
| 430 | 23× | let mut nodes = Vec::new(); |
| 431 | 39× | for (col, (_, mut js)) in by_depth.into_iter().enumerate() { |
| 432 | 39× | js.sort_by(|a, b| a.name.cmp(&b.name)); |
| 433 | 39× | let n = js.len() as i64; |
| 434 | 39× | let column_h = n * NODE_H + (n - 1).max(0) * ROW_GAP; |
| 435 | 39× | let top = (height - column_h) / 2; |
| 436 | 54× | for (i, j) in js.into_iter().enumerate() { |
| 437 | 54× | let duration = crate::flow::duration(&j); |
| 438 | 54× | nodes.push(Node { x: PAD + col as i64 * (NODE_W + COL_GAP), y: top + i as i64 * (NODE_H + ROW_GAP), duration, j }); |
| 439 | 54× | } |
| 440 | | } |
| 441 | 23× | let mut edges = Vec::new(); |
| 442 | 54× | for n in &nodes { |
| 443 | 54× | for d in n.j.depends_on() { |
| 444 | 20× | if let Some(from) = nodes.iter().find(|m| m.j.name == d) { |
| 445 | 18× | let (x1, y1) = (from.x + NODE_W, from.y + NODE_H / 2); |
| 446 | 18× | let (x2, y2) = (n.x, n.y + NODE_H / 2); |
| 447 | 18× | let mid = (x1 + x2) / 2; |
| 448 | 18× | edges.push(Edge { d: format!("M{x1},{y1} C{mid},{y1} {mid},{y2} {x2},{y2}"), status: from.j.status.clone() }); |
| 449 | 18× | } |
| 450 | | } |
| 451 | | } |
| 452 | 23× | let cols = nodes.iter().map(|n| n.x).max().map(|x| x + NODE_W + PAD).unwrap_or(PAD * 2); |
| 453 | 23× | Graph { nodes, edges, width: cols, height: height.max(NODE_H + PAD * 2) } |
| 454 | 23× | } |
| 455 | |
|
| 456 | 181× | pub fn glyph(status: &str) -> &'static str { |
| 457 | 181× | match status { |
| 458 | 181× | "passed" => "✓", |
| 459 | 124× | "failed" => "✕", |
| 460 | 111× | "running" => "●", |
| 461 | 96× | "skipped" => "⤼", |
| 462 | 95× | "cancelled" => "⊘", |
| 463 | 86× | "error" => "!", |
| 464 | 85× | _ => "○", |
| 465 | | } |
| 466 | 181× | } |
| 467 | |
|
| 468 | |
|
| 469 | | const SHOWN_FAILURES: i64 = 50; |
| 470 | |
|
| 471 | |
|
| 472 | |
|
| 473 | |
|
| 474 | | pub enum Segment { |
| 475 | | Line(fdb::LogLine), |
| 476 | | Group(Section), |
| 477 | | } |
| 478 | |
|
| 479 | | pub struct Section { |
| 480 | | pub title: String, |
| 481 | | |
| 482 | | pub from_t: i64, |
| 483 | | pub to_t: Option<i64>, |
| 484 | | pub lines: Vec<fdb::LogLine>, |
| 485 | | } |
| 486 | |
|
| 487 | |
|
| 488 | |
|
| 489 | 55× | pub fn sections(lines: &[fdb::LogLine]) -> Vec<Segment> { |
| 490 | 55× | let mut out: Vec<Segment> = Vec::new(); |
| 491 | 55× | let mut open: Option<Section> = None; |
| 492 | 55× | for l in lines { |
| 493 | 33× | if let Some(title) = l.text.strip_prefix("::group::") { |
| 494 | 6× | if let Some(g) = open.take() { |
| 495 | 1× | out.push(Segment::Group(Section { to_t: Some(l.t), ..g })); |
| 496 | 5× | } |
| 497 | 6× | open = Some(Section { title: title.trim().to_string(), from_t: l.t, to_t: None, lines: Vec::new() }); |
| 498 | 27× | } else if l.text.trim() == "::endgroup::" { |
| 499 | 4× | if let Some(g) = open.take() { |
| 500 | 4× | out.push(Segment::Group(Section { to_t: Some(l.t), ..g })); |
| 501 | 4× | } |
| 502 | | } else { |
| 503 | 23× | match open.as_mut() { |
| 504 | 7× | Some(g) => g.lines.push(l.clone()), |
| 505 | 16× | None => out.push(Segment::Line(l.clone())), |
| 506 | | } |
| 507 | | } |
| 508 | | } |
| 509 | 55× | if let Some(g) = open { |
| 510 | 1× | out.push(Segment::Group(g)); |
| 511 | 54× | } |
| 512 | 55× | out |
| 513 | 55× | } |
| 514 | |
|
| 515 | |
|
| 516 | 29× | pub fn secs(ms: impl std::borrow::Borrow<i64>) -> String { |
| 517 | 29× | let ms = *ms.borrow(); |
| 518 | 29× | format!("{}.{}s", ms / 1000, ms % 1000 / 100) |
| 519 | 29× | } |
| 520 | |
|
| 521 | | pub struct JobLog { |
| 522 | | pub j: fdb::Job, |
| 523 | | pub artifacts: Vec<fdb::Artifact>, |
| 524 | | pub lines: Vec<fdb::LogLine>, |
| 525 | | |
| 526 | | pub segments: Vec<Segment>, |
| 527 | | pub duration: String, |
| 528 | | |
| 529 | | pub last_seq: i64, |
| 530 | | |
| 531 | | pub coverage: Option<(i64, String)>, |
| 532 | | |
| 533 | | |
| 534 | | pub tests: Option<crate::junit::Report>, |
| 535 | | pub failures: Vec<crate::junit::Case>, |
| 536 | | } |
| 537 | |
|
| 538 | | #[derive(Template)] |
| 539 | | #[template(path = "flow_run.html")] |
| 540 | | pub struct RunPage { |
| 541 | | shell: Shell, |
| 542 | | repo: RepoShell, |
| 543 | | run: fdb::Run, |
| 544 | | graph: Graph, |
| 545 | | logs: Vec<JobLog>, |
| 546 | | duration: String, |
| 547 | | |
| 548 | | can_rerun: bool, |
| 549 | | |
| 550 | | can_cancel: bool, |
| 551 | | |
| 552 | | can_expedite: bool, |
| 553 | | |
| 554 | | queue: Option<crate::flow::QueueInfo>, |
| 555 | | |
| 556 | | releases: Vec<db::releases::Release>, |
| 557 | | |
| 558 | | approvals: Vec<ApprovalView>, |
| 559 | | } |
| 560 | |
|
| 561 | |
|
| 562 | | pub struct ApprovalView { |
| 563 | | pub job: String, |
| 564 | | pub by: String, |
| 565 | | pub others_only: bool, |
| 566 | | |
| 567 | | pub state: &'static str, |
| 568 | | pub who: String, |
| 569 | | pub when_ms: i64, |
| 570 | | |
| 571 | | pub may: Result<(), String>, |
| 572 | | |
| 573 | | |
| 574 | | pub sealed: bool, |
| 575 | | pub command: String, |
| 576 | | pub seal: String, |
| 577 | | } |
| 578 | |
|
| 579 | | impl ApprovalView { |
| 580 | 2× | pub fn may_decide(&self) -> bool { |
| 581 | 2× | self.may.is_ok() |
| 582 | 2× | } |
| 583 | |
|
| 584 | 2× | pub fn why_not(&self) -> String { |
| 585 | 2× | self.may.clone().err().unwrap_or_default() |
| 586 | 2× | } |
| 587 | | } |
| 588 | |
|
| 589 | |
|
| 590 | | const PAGE_LINES: i64 = 5000; |
| 591 | |
|
| 592 | 24× | pub async fn run( |
| 593 | 24× | State(app): State<Shared>, |
| 594 | 24× | viewer: Viewer, |
| 595 | 24× | Path((owner, name, id)): Path<(String, String, i64)>, |
| 596 | 24× | ) -> Result<Page<RunPage>, Error> { |
| 597 | 24× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer); |
| 598 | 24× | let (_repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 599 | 24× | let run = fdb::run(&app.db, row.id, id) |
| 600 | 24× | .await |
| 601 | 24× | .map_err(|e| Error::from_db(shell.clone(), e))? |
| 602 | 24× | .ok_or_else(|| Error::not_found(shell.clone()))?; |
| 603 | 23× | let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 604 | 23× | let reports = crate::coverage::for_run(&app.db, run.id).await.unwrap_or_default(); |
| 605 | 23× | let test_reports = crate::junit::for_run(&app.db, run.id).await.unwrap_or_default(); |
| 606 | 23× | let mut logs = Vec::new(); |
| 607 | 54× | for j in &jobs { |
| 608 | 54× | let lines = fdb::log(&app.db, j.id, 0, PAGE_LINES).await.unwrap_or_default(); |
| 609 | 54× | let last_seq = lines.last().map(|l| l.seq).unwrap_or(0); |
| 610 | 54× | let artifacts = fdb::artifacts(&app.db, j.id).await.unwrap_or_default(); |
| 611 | 54× | let coverage = reports |
| 612 | 54× | .iter() |
| 613 | 54× | .find(|r| r.job_id == Some(j.id)) |
| 614 | 54× | .map(|r| (r.id, r.percent().map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into()))); |
| 615 | 54× | let tests = test_reports.iter().find(|r| r.job_id == j.id).cloned(); |
| 616 | 54× | let failures = match &tests { |
| 617 | 1× | Some(r) if r.broken() > 0 => crate::junit::failures(&app.db, r.id, SHOWN_FAILURES).await.unwrap_or_default(), |
| 618 | 53× | _ => vec![], |
| 619 | | }; |
| 620 | 54× | let segments = sections(&lines); |
| 621 | 54× | logs.push(JobLog { |
| 622 | 54× | duration: crate::flow::duration(j), |
| 623 | 54× | j: j.clone(), |
| 624 | 54× | artifacts, |
| 625 | 54× | lines, |
| 626 | 54× | segments, |
| 627 | 54× | last_seq, |
| 628 | 54× | coverage, |
| 629 | 54× | tests, |
| 630 | 54× | failures, |
| 631 | 54× | }); |
| 632 | | } |
| 633 | 23× | let duration = match run.finished_ms { |
| 634 | 11× | Some(f) => crate::flow::human_ms(f - run.created_ms), |
| 635 | 12× | None => crate::flow::human_ms(db::now_ms() - run.created_ms), |
| 636 | | }; |
| 637 | 23× | let mut approvals = Vec::new(); |
| 638 | 54× | for j in jobs.iter().filter(|j| !j.approval.is_empty()) { |
| 639 | 4× | let Some(a) = serde_json::from_str::<flow_core::Job>(&j.spec).ok().and_then(|s| s.approval) else { continue }; |
| 640 | 4× | let state = match (j.approval.as_str(), j.status.as_str()) { |
| 641 | 4× | ("waiting", "queued") => "waiting", |
| 642 | 2× | ("approved", _) => "approved", |
| 643 | 0× | (_, "cancelled") if !j.approved_by.is_empty() => "rejected", |
| 644 | 0× | (_, "cancelled") if j.error.starts_with("no approval within") => "expired", |
| 645 | 0× | _ => continue, |
| 646 | | }; |
| 647 | 4× | let may = match (state, viewer.account()) { |
| 648 | 4× | ("waiting", Some(me)) => crate::flow::may_decide(&app, &row, &run, j, me).await.map(|_| ()), |
| 649 | 2× | ("waiting", None) => Err("sign in to approve".into()), |
| 650 | 2× | _ => Err(String::new()), |
| 651 | | }; |
| 652 | 4× | approvals.push(ApprovalView { |
| 653 | 4× | sealed: a.sealed, |
| 654 | 4× | command: format!("oxy seal --flow {}/{owner}/{name}/flow/{} --job {}", app.config.base_url(), run.number, j.name), |
| 655 | 4× | seal: j.approval_seal.clone(), |
| 656 | 4× | job: j.name.clone(), |
| 657 | 4× | by: a.by, |
| 658 | 4× | others_only: a.others_only, |
| 659 | 4× | state, |
| 660 | 4× | who: if j.approved_via.is_empty() { j.approved_by.clone() } else { format!("{} via {}", j.approved_by, j.approved_via) }, |
| 661 | 4× | when_ms: j.approved_ms.unwrap_or(0), |
| 662 | 4× | may, |
| 663 | | }); |
| 664 | | } |
| 665 | 23× | let graph = layout(jobs); |
| 666 | 23× | let can_write = viewer.account().is_some() && role >= Role::Write; |
| 667 | 23× | let can_rerun = !run.live() && can_write && crate::flow::enabled(&app, &row); |
| 668 | 23× | let can_cancel = run.live() && can_write; |
| 669 | 23× | let can_expedite = run.live() && run.priority.is_empty() && viewer.account().is_some() && role >= Role::Maintain; |
| 670 | 23× | let queue = if run.live() { |
| 671 | 12× | let q = fdb::queue(&app.db).await.unwrap_or_default(); |
| 672 | 12× | Some(crate::flow::queue_info(&q, row.id, run.id)).filter(|i| i.position.is_some()) |
| 673 | | } else { |
| 674 | 11× | None |
| 675 | | }; |
| 676 | 23× | let releases = if viewer.account().is_some() && role >= Role::Write && logs.iter().any(|l| !l.artifacts.is_empty()) { |
| 677 | 1× | db::releases::list(&app.db, row.id).await.unwrap_or_default() |
| 678 | | } else { |
| 679 | 22× | vec![] |
| 680 | | }; |
| 681 | 23× | Ok(Page(RunPage { |
| 682 | 23× | shell, |
| 683 | 23× | repo: RepoShell::new(&app, &row, "flow").with_role(role), |
| 684 | 23× | run, |
| 685 | 23× | graph, |
| 686 | 23× | logs, |
| 687 | 23× | duration, |
| 688 | 23× | can_rerun, |
| 689 | 23× | can_cancel, |
| 690 | 23× | can_expedite, |
| 691 | 23× | queue, |
| 692 | 23× | releases, |
| 693 | 23× | approvals, |
| 694 | 23× | })) |
| 695 | 24× | } |
| 696 | |
|
| 697 | | #[derive(Deserialize)] |
| 698 | | pub struct DecideForm { |
| 699 | | #[serde(rename = "_csrf")] |
| 700 | | csrf_token: String, |
| 701 | | |
| 702 | | action: String, |
| 703 | | } |
| 704 | |
|
| 705 | |
|
| 706 | |
|
| 707 | 0× | pub async fn decide( |
| 708 | 0× | State(app): State<Shared>, |
| 709 | 0× | viewer: Viewer, |
| 710 | 0× | Path((owner, name, number, job)): Path<(String, String, i64, String)>, |
| 711 | 0× | Form(f): Form<DecideForm>, |
| 712 | 0× | ) -> Result<Response, Error> { |
| 713 | 0× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{number}"), &viewer); |
| 714 | 0× | let me = require(&viewer, &shell)?; |
| 715 | 0× | let (_, row, _) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 716 | 0× | csrf(&viewer, &f.csrf_token, &shell)?; |
| 717 | 0× | let run = fdb::run(&app.db, row.id, number) |
| 718 | 0× | .await |
| 719 | 0× | .map_err(|e| Error::from_db(shell.clone(), e))? |
| 720 | 0× | .ok_or_else(|| Error::not_found(shell.clone()))?; |
| 721 | 0× | let approve = match f.action.as_str() { |
| 722 | 0× | "approve" => true, |
| 723 | 0× | "reject" => false, |
| 724 | 0× | _ => return Err(Error::bad(shell, "approve or reject")), |
| 725 | | }; |
| 726 | 0× | match crate::flow::decide(&app, &row, &run, &job, &me.account, approve, None).await { |
| 727 | 0× | Ok(_) => Ok(Redirect::to(&format!("/{owner}/{name}/flow/{number}")).into_response()), |
| 728 | 0× | Err(why) => Err(Error::bad(shell, why)), |
| 729 | | } |
| 730 | 0× | } |
| 731 | |
|
| 732 | | #[derive(Deserialize)] |
| 733 | | pub struct LiveQuery { |
| 734 | | |
| 735 | | after: Option<String>, |
| 736 | | } |
| 737 | |
|
| 738 | |
|
| 739 | |
|
| 740 | 1× | pub async fn live( |
| 741 | 1× | State(app): State<Shared>, |
| 742 | 1× | viewer: Viewer, |
| 743 | 1× | Path((owner, name, id)): Path<(String, String, i64)>, |
| 744 | 1× | Query(q): Query<LiveQuery>, |
| 745 | 1× | ) -> Result<Response, Error> { |
| 746 | 1× | let shell = Shell::new(&app, "", &viewer); |
| 747 | 1× | let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 748 | 1× | let run = fdb::run(&app.db, row.id, id) |
| 749 | 1× | .await |
| 750 | 1× | .map_err(|e| Error::from_db(shell.clone(), e))? |
| 751 | 1× | .ok_or_else(|| Error::not_found(shell.clone()))?; |
| 752 | 1× | let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 753 | 1× | let after: std::collections::HashMap<i64, i64> = q |
| 754 | 1× | .after |
| 755 | 1× | .unwrap_or_default() |
| 756 | 1× | .split(',') |
| 757 | 1× | .filter_map(|p| p.split_once(':')) |
| 758 | 1× | .filter_map(|(a, b)| Some((a.parse().ok()?, b.parse().ok()?))) |
| 759 | 1× | .collect(); |
| 760 | 1× | let mut out = Vec::new(); |
| 761 | 3× | for j in &jobs { |
| 762 | 3× | let lines = match after.get(&j.id) { |
| 763 | 1× | Some(seq) => fdb::log(&app.db, j.id, *seq, 1000).await.unwrap_or_default(), |
| 764 | 2× | None => vec![], |
| 765 | | }; |
| 766 | 3× | out.push(serde_json::json!({ |
| 767 | 3× | "id": j.id, |
| 768 | 3× | "name": j.name, |
| 769 | 3× | "status": j.status, |
| 770 | 3× | "glyph": glyph(&j.status), |
| 771 | 3× | "duration": crate::flow::duration(j), |
| 772 | 3× | "exit_code": j.exit_code, |
| 773 | 3× | "lines": lines.iter().map(|l| serde_json::json!({ "seq": l.seq, "t": l.t, "stream": l.stream, "text": l.text })).collect::<Vec<_>>(), |
| 774 | | })); |
| 775 | | } |
| 776 | 1× | Ok(Json(serde_json::json!({ "status": run.status, "live": run.live(), "jobs": out })).into_response()) |
| 777 | 1× | } |
| 778 | |
|
| 779 | |
|
| 780 | |
|
| 781 | |
|
| 782 | | pub const STAMP_IMAGE: &str = ".flow/stamp"; |
| 783 | |
|
| 784 | | pub const RUN_LINK: &str = ".flow/run"; |
| 785 | |
|
| 786 | |
|
| 787 | 8× | async fn state_of(app: &Shared, owner: &str, name: &str, r: &str) -> Result<(String, bool), crate::repos::RepoError> { |
| 788 | 8× | let repo = crate::repos::RepoName::new(owner, name).ok_or(crate::repos::RepoError::NotFound)?; |
| 789 | 8× | let spec = r.to_string(); |
| 790 | 8× | app.repos |
| 791 | 8× | .read(&repo, move |repo, cache| { |
| 792 | 8× | let t = crate::repos::view::resolve(repo, cache, &spec)?; |
| 793 | 8× | let moves = matches!(t.kind, crate::repos::view::RefKind::Bookmark | crate::repos::view::RefKind::Tag); |
| 794 | 8× | Ok((t.permalink().unwrap_or_default(), moves)) |
| 795 | 8× | }) |
| 796 | 8× | .await |
| 797 | 8× | } |
| 798 | |
|
| 799 | |
|
| 800 | 6× | pub async fn stamp( |
| 801 | 6× | State(app): State<Shared>, |
| 802 | 6× | viewer: Viewer, |
| 803 | 6× | Path((owner, name, r)): Path<(String, String, String)>, |
| 804 | 6× | ) -> Result<Response, Error> { |
| 805 | 6× | let shell = Shell::new(&app, "", &viewer); |
| 806 | 6× | let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 807 | 6× | let (heads, moves) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?; |
| 808 | 6× | if moves && !heads.is_empty() { |
| 809 | 2× | let mut res = axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{heads}")).into_response(); |
| 810 | 2× | res.headers_mut().insert(axum::http::header::CACHE_CONTROL, axum::http::HeaderValue::from_static("no-cache")); |
| 811 | 2× | return Ok(res); |
| 812 | 4× | } |
| 813 | 4× | let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 814 | 4× | let jobs = match &run { |
| 815 | 3× | Some(r) => fdb::jobs(&app.db, r.id).await.map_err(|e| Error::from_db(shell.clone(), e))?, |
| 816 | 1× | None => vec![], |
| 817 | | }; |
| 818 | 4× | let svg = stamp_svg(&heads, run.as_ref(), &jobs); |
| 819 | 4× | let cache = if run.as_ref().is_some_and(|r| !r.live()) { "public, max-age=3600" } else { "public, max-age=60" }; |
| 820 | 4× | Ok(( |
| 821 | 4× | [ |
| 822 | 4× | (axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"), |
| 823 | 4× | (axum::http::header::CACHE_CONTROL, cache), |
| 824 | 4× | (axum::http::header::CONTENT_SECURITY_POLICY, "default-src 'none'; style-src 'unsafe-inline'"), |
| 825 | 4× | ], |
| 826 | 4× | svg, |
| 827 | 4× | ) |
| 828 | 4× | .into_response()) |
| 829 | 6× | } |
| 830 | |
|
| 831 | |
|
| 832 | 2× | pub async fn at( |
| 833 | 2× | State(app): State<Shared>, |
| 834 | 2× | viewer: Viewer, |
| 835 | 2× | Path((owner, name, r)): Path<(String, String, String)>, |
| 836 | 2× | ) -> Result<Response, Error> { |
| 837 | 2× | let shell = Shell::new(&app, "", &viewer); |
| 838 | 2× | let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 839 | 2× | let (heads, _) = state_of(&app, &owner, &name, &r).await.map_err(|e| Error::from_repo(shell.clone(), e))?; |
| 840 | 2× | let run = fdb::latest_for_heads(&app.db, row.id, &heads).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 841 | 2× | let to = match run { |
| 842 | 1× | Some(r) => format!("/{owner}/{name}/flow/{}", r.number), |
| 843 | 1× | None => format!("/{owner}/{name}/flow"), |
| 844 | | }; |
| 845 | 2× | Ok(axum::response::Redirect::to(&to).into_response()) |
| 846 | 2× | } |
| 847 | |
|
| 848 | 12× | fn xml(s: &str) -> String { |
| 849 | 12× | s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) |
| 850 | 12× | } |
| 851 | |
|
| 852 | |
|
| 853 | |
|
| 854 | |
|
| 855 | 4× | pub fn stamp_svg(heads: &str, run: Option<&fdb::Run>, jobs: &[fdb::Job]) -> String { |
| 856 | | const CH: f64 = 6.6; |
| 857 | 7× | let colour = |s: &str| match s { |
| 858 | 7× | "passed" => "#5fe3a1", |
| 859 | 5× | "failed" | "error" => "#ff5e7a", |
| 860 | 1× | "running" => "#00e0f0", |
| 861 | 1× | _ => "#8592ad", |
| 862 | 7× | }; |
| 863 | 4× | let short: String = heads.chars().take(12).collect(); |
| 864 | 4× | let (status, date) = match run { |
| 865 | 3× | Some(r) => (r.status.as_str(), crate::render::time::absolute(r.created_ms as u64).chars().take(10).collect::<String>()), |
| 866 | 1× | None => ("no run", String::new()), |
| 867 | | }; |
| 868 | 4× | let mut ordered: Vec<&fdb::Job> = jobs.iter().collect(); |
| 869 | 4× | ordered.sort_by(|a, b| (a.depth, &a.name).cmp(&(b.depth, &b.name))); |
| 870 | 4× | let label = "OXYGENFLOW"; |
| 871 | 4× | let label_w = 18.0 + label.len() as f64 * 7.4 + 8.0; |
| 872 | 4× | let glyphs_w = if ordered.is_empty() { 0.0 } else { ordered.len() as f64 * 10.0 + 6.0 }; |
| 873 | 4× | let tail = if date.is_empty() { format!("{status} · {short}") } else { format!("{status} · {short} · {date}") }; |
| 874 | 4× | let right_w = 8.0 + glyphs_w + tail.chars().count() as f64 * CH + 8.0; |
| 875 | 4× | let w = (label_w + right_w).ceil(); |
| 876 | 4× | let mut glyphs = String::new(); |
| 877 | 4× | for (i, j) in ordered.iter().enumerate() { |
| 878 | 3× | let x = label_w + 8.0 + i as f64 * 10.0 + 4.0; |
| 879 | 3× | glyphs.push_str(&format!( |
| 880 | 3× | r#"<text x="{x:.1}" y="15" fill="{}" text-anchor="middle">{}</text>"#, |
| 881 | 3× | colour(&j.status), |
| 882 | 3× | glyph(&j.status) |
| 883 | 3× | )); |
| 884 | 3× | } |
| 885 | 4× | let meta = serde_json::json!({ |
| 886 | 10× | "heads": heads.split('+').filter(|h| !h.is_empty()).collect::<Vec<_>>(), |
| 887 | 4× | "run": run.map(|r| r.number), |
| 888 | 4× | "status": status, |
| 889 | 4× | "jobs": ordered.iter().map(|j| serde_json::json!({ "name": j.name, "status": j.status, "receipt": j.receipt_hash })).collect::<Vec<_>>(), |
| 890 | | }); |
| 891 | 4× | let title = match run { |
| 892 | 3× | Some(r) => format!("OxygenFlow run #{} {status} on state {short}", r.number), |
| 893 | 1× | None => format!("OxygenFlow: no run for state {short}"), |
| 894 | | }; |
| 895 | 4× | format!( |
| 896 | | 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>"##, |
| 897 | 4× | t = xml(&title), |
| 898 | 4× | m = xml(&meta.to_string()), |
| 899 | | lw = label_w, |
| 900 | 4× | lx = label_w - 4.0, |
| 901 | 4× | tx = label_w + 8.0 + glyphs_w, |
| 902 | 4× | sc = colour(status), |
| 903 | 4× | tail = xml(&tail), |
| 904 | 4× | wi = w - 1.0, |
| 905 | | ) |
| 906 | 4× | } |
| 907 | |
|
| 908 | |
|
| 909 | | #[derive(Clone, Debug)] |
| 910 | | pub struct ReceiptRow { |
| 911 | | pub attest: String, |
| 912 | | pub job: String, |
| 913 | | pub exit_code: u32, |
| 914 | | pub duration: String, |
| 915 | | pub runner: String, |
| 916 | | pub run: String, |
| 917 | | |
| 918 | | pub problem: String, |
| 919 | | pub made_ms: i64, |
| 920 | | } |
| 921 | |
|
| 922 | | impl ReceiptRow { |
| 923 | 3× | pub fn passed(&self) -> bool { |
| 924 | 3× | self.exit_code == 0 |
| 925 | 3× | } |
| 926 | | } |
| 927 | |
|
| 928 | |
|
| 929 | 14× | pub async fn receipts_of(app: &Shared, name: &crate::repos::RepoName, heads: Vec<oxy_core::hash::ChangeHash>) -> Vec<ReceiptRow> { |
| 930 | 14× | let base = app.config.base_url(); |
| 931 | 14× | let found = app.repos.read(name, move |repo, _| Ok(repo.receipts(&heads)?)).await.unwrap_or_default(); |
| 932 | 14× | found |
| 933 | 14× | .into_iter() |
| 934 | 14× | .map(|i| { |
| 935 | 1× | let r = &i.signed.receipt; |
| 936 | 1× | let run = i.signed.run().to_string(); |
| 937 | | ReceiptRow { |
| 938 | 1× | attest: i.attest.to_hex(), |
| 939 | 1× | job: r.job_name.clone(), |
| 940 | 1× | exit_code: r.exit_code, |
| 941 | 1× | duration: crate::flow::human_ms(r.duration_ms as i64), |
| 942 | 1× | runner: i.signed.runner.name.clone(), |
| 943 | | |
| 944 | 1× | run: if run.starts_with(base) { run } else { String::new() }, |
| 945 | 1× | problem: match (i.problem, i.revoked) { |
| 946 | 0× | (Some(p), _) => p, |
| 947 | 0× | (None, true) => "the runner's key was revoked".into(), |
| 948 | 1× | (None, false) => String::new(), |
| 949 | | }, |
| 950 | 1× | made_ms: i.signed.attest.hlc.wall_ms as i64, |
| 951 | | } |
| 952 | 1× | }) |
| 953 | 14× | .collect() |
| 954 | 14× | } |
| 955 | |
|
| 956 | |
|
| 957 | |
|
| 958 | 2× | pub async fn receipt_file( |
| 959 | 2× | State(app): State<Shared>, |
| 960 | 2× | viewer: Viewer, |
| 961 | 2× | Path((owner, name, attest)): Path<(String, String, String)>, |
| 962 | 2× | ) -> Result<Response, Error> { |
| 963 | 2× | let shell = Shell::new(&app, &format!("/{owner}/{name}/receipts/{attest}"), &viewer); |
| 964 | 2× | let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 965 | 2× | let Some(r) = oxy_core::hash::ObjectRef::from_hex(attest.trim_end_matches(".receipt")) else { |
| 966 | 0× | return Err(Error::not_found(shell)); |
| 967 | | }; |
| 968 | 2× | let (job, bytes) = app |
| 969 | 2× | .repos |
| 970 | 2× | .read(&repo, move |repo, _| { |
| 971 | 2× | let i = repo.receipt(&r)?; |
| 972 | 1× | Ok((i.signed.receipt.job_name.clone(), i.signed.encode())) |
| 973 | 2× | }) |
| 974 | 2× | .await |
| 975 | 2× | .map_err(|_| Error::not_found(shell.clone()))?; |
| 976 | 5× | let file: String = job.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')).collect(); |
| 977 | 1× | Ok(( |
| 978 | 1× | [ |
| 979 | 1× | (axum::http::header::CONTENT_TYPE, "application/oxy-receipt".to_string()), |
| 980 | 1× | (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{file}-{}.receipt\"", r.short(12))), |
| 981 | 1× | ], |
| 982 | 1× | bytes, |
| 983 | 1× | ) |
| 984 | 1× | .into_response()) |
| 985 | 2× | } |
| 986 | |
|
| 987 | |
|
| 988 | |
|
| 989 | 3× | pub async fn artifact_file( |
| 990 | 3× | State(app): State<Shared>, |
| 991 | 3× | viewer: Viewer, |
| 992 | 3× | Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>, |
| 993 | 3× | ) -> Result<Response, Error> { |
| 994 | 3× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}"), &viewer); |
| 995 | 3× | let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 996 | 3× | let run = fdb::run(&app.db, row.id, id) |
| 997 | 3× | .await |
| 998 | 3× | .map_err(|e| Error::from_db(shell.clone(), e))? |
| 999 | 3× | .ok_or_else(|| Error::not_found(shell.clone()))?; |
| 1000 | 3× | let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 1001 | 3× | let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) }; |
| 1002 | 3× | let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 1003 | 3× | let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) }; |
| 1004 | 2× | let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) }; |
| 1005 | 2× | let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|_| Error::not_found(shell.clone()))?; |
| 1006 | 2× | let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string(); |
| 1007 | 2× | Ok(( |
| 1008 | 2× | [ |
| 1009 | 2× | (axum::http::header::CONTENT_TYPE, "application/octet-stream".to_string()), |
| 1010 | 2× | (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}\"", file.replace('"', ""))), |
| 1011 | 2× | ], |
| 1012 | 2× | bytes, |
| 1013 | 2× | ) |
| 1014 | 2× | .into_response()) |
| 1015 | 3× | } |
| 1016 | |
|
| 1017 | |
|
| 1018 | |
|
| 1019 | |
|
| 1020 | |
|
| 1021 | 2× | pub async fn provenance( |
| 1022 | 2× | State(app): State<Shared>, |
| 1023 | 2× | viewer: Viewer, |
| 1024 | 2× | Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>, |
| 1025 | 2× | ) -> Result<Response, Error> { |
| 1026 | 2× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}/artifacts/{job}/{artifact}/provenance"), &viewer); |
| 1027 | 2× | let (repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 1028 | 2× | let run = fdb::run(&app.db, row.id, id) |
| 1029 | 2× | .await |
| 1030 | 2× | .map_err(|e| Error::from_db(shell.clone(), e))? |
| 1031 | 2× | .ok_or_else(|| Error::not_found(shell.clone()))?; |
| 1032 | 2× | let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 1033 | 2× | let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) }; |
| 1034 | 2× | if j.receipt_attest.is_empty() { |
| 1035 | 1× | return Err(Error::bad(shell, "This job has no signed receipt the hub kept, so the hub states no provenance for it.".to_string())); |
| 1036 | 1× | } |
| 1037 | 1× | let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 1038 | 1× | let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) }; |
| 1039 | 1× | let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) }; |
| 1040 | 1× | let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|_| Error::not_found(shell.clone()))?; |
| 1041 | 1× | let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string(); |
| 1042 | 1× | let base = app.config.base_url(); |
| 1043 | 1× | let subject = crate::provenance::Subject { |
| 1044 | 1× | name: &file, |
| 1045 | 1× | bytes: &bytes, |
| 1046 | 1× | repo: &format!("{owner}/{name}"), |
| 1047 | 1× | run_url: &format!("{base}/{owner}/{name}/flow/{id}"), |
| 1048 | 1× | bookmark: &run.bookmark, |
| 1049 | 1× | state: &run.state, |
| 1050 | 1× | heads: &run.heads, |
| 1051 | 1× | pipeline_hash: &run.pipeline_hash, |
| 1052 | 1× | job: &j.name, |
| 1053 | 1× | runner: &j.runner, |
| 1054 | 1× | receipt_signer: &j.receipt_signer, |
| 1055 | 1× | receipt_attest: &j.receipt_attest, |
| 1056 | 1× | started_ms: j.started_ms, |
| 1057 | 1× | finished_ms: j.finished_ms, |
| 1058 | 1× | }; |
| 1059 | 1× | let statement = crate::provenance::statement(base, &subject); |
| 1060 | 1× | let envelope = crate::provenance::envelope(&app, &statement).map_err(|e| Error::bad(shell.clone(), e.to_string()))?; |
| 1061 | 1× | Ok(( |
| 1062 | 1× | [ |
| 1063 | 1× | (axum::http::header::CONTENT_TYPE, "application/json".to_string()), |
| 1064 | 1× | (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}.intoto.json\"", file.replace('"', ""))), |
| 1065 | 1× | ], |
| 1066 | 1× | serde_json::to_string(&envelope).unwrap_or_default(), |
| 1067 | 1× | ) |
| 1068 | 1× | .into_response()) |
| 1069 | 2× | } |
| 1070 | |
|
| 1071 | |
|
| 1072 | |
|
| 1073 | 1× | pub async fn signing_key(State(app): State<Shared>) -> Response { |
| 1074 | 1× | ([(axum::http::header::CONTENT_TYPE, "application/x-pem-file")], crate::provenance::public_pem(&app)).into_response() |
| 1075 | 1× | } |
| 1076 | |
|
| 1077 | | #[derive(Deserialize)] |
| 1078 | | pub struct AttachForm { |
| 1079 | | _csrf: String, |
| 1080 | | release: i64, |
| 1081 | | } |
| 1082 | |
|
| 1083 | |
|
| 1084 | |
|
| 1085 | |
|
| 1086 | 1× | pub async fn attach( |
| 1087 | 1× | State(app): State<Shared>, |
| 1088 | 1× | viewer: Viewer, |
| 1089 | 1× | Path((owner, name, id, job, artifact)): Path<(String, String, i64, String, String)>, |
| 1090 | 1× | Form(f): Form<AttachForm>, |
| 1091 | 1× | ) -> Result<Response, Error> { |
| 1092 | 1× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow/{id}"), &viewer); |
| 1093 | 1× | require(&viewer, &shell)?; |
| 1094 | 1× | csrf(&viewer, &f._csrf, &shell)?; |
| 1095 | 1× | let (repo, row, _) = lookup_role(&app, &shell, &viewer, &owner, &name, Access::Write).await?; |
| 1096 | 1× | let run = fdb::run(&app.db, row.id, id) |
| 1097 | 1× | .await |
| 1098 | 1× | .map_err(|e| Error::from_db(shell.clone(), e))? |
| 1099 | 1× | .ok_or_else(|| Error::not_found(shell.clone()))?; |
| 1100 | 1× | let jobs = fdb::jobs(&app.db, run.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 1101 | 1× | let Some(j) = jobs.iter().find(|j| j.name == job) else { return Err(Error::not_found(shell)) }; |
| 1102 | | |
| 1103 | | |
| 1104 | 1× | if j.status != "passed" { |
| 1105 | 0× | return Err(Error::bad(shell, "only a passing job's artifacts can be attached to a release")); |
| 1106 | 1× | } |
| 1107 | 1× | let arts = fdb::artifacts(&app.db, j.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 1108 | 1× | let Some(a) = arts.into_iter().find(|a| a.name == artifact) else { return Err(Error::not_found(shell)) }; |
| 1109 | 1× | let releases = db::releases::list(&app.db, row.id).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 1110 | 1× | let Some(rel) = releases.into_iter().find(|r| r.id == f.release) else { return Err(Error::not_found(shell)) }; |
| 1111 | 1× | let Some(blob) = oxy_core::hash::ObjectRef::from_hex(&a.blob) else { return Err(Error::not_found(shell)) }; |
| 1112 | 1× | let bytes = app.repos.read(&repo, move |r, _| Ok(r.read_blob(&blob)?)).await.map_err(|e| Error::from_repo(shell.clone(), e))?; |
| 1113 | 1× | let file = a.path.rsplit('/').next().unwrap_or(&a.name).to_string(); |
| 1114 | 1× | super::releases::store_asset(&app, rel.id, &file, "application/octet-stream", &bytes) |
| 1115 | 1× | .await |
| 1116 | 1× | .map_err(|m| Error::bad(shell.clone(), m))?; |
| 1117 | 1× | Ok(Redirect::to(&format!("/{owner}/{name}/releases/tag/{}", rel.tag)).into_response()) |
| 1118 | 1× | } |
| 1119 | |
|
| 1120 | |
|
| 1121 | |
|
| 1122 | |
|
| 1123 | |
|
| 1124 | 1× | pub async fn badge( |
| 1125 | 1× | State(app): State<Shared>, |
| 1126 | 1× | viewer: Viewer, |
| 1127 | 1× | Path((owner, name)): Path<(String, String)>, |
| 1128 | 1× | ) -> Result<axum::response::Response, Error> { |
| 1129 | | use axum::response::IntoResponse; |
| 1130 | 1× | let shell = Shell::new(&app, &format!("/{owner}/{name}/flow"), &viewer); |
| 1131 | 1× | let (_repo, row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?; |
| 1132 | 1× | let latest = fdb::latest_on(&app.db, row.id, &row.default_bookmark).await.map_err(|e| Error::from_db(shell.clone(), e))?; |
| 1133 | 1× | let (text, colour) = match latest.as_ref().map(|r| r.status.as_str()) { |
| 1134 | 0× | Some("passed") => ("passing", "#2da44e"), |
| 1135 | 0× | Some("failed") | Some("error") => ("failing", "#cf222e"), |
| 1136 | 0× | Some("cancelled") => ("cancelled", "#6e7781"), |
| 1137 | 0× | Some(_) => ("running", "#0969da"), |
| 1138 | 1× | None => ("no runs", "#6e7781"), |
| 1139 | | }; |
| 1140 | 1× | let label = "OxygenFlow"; |
| 1141 | 1× | let (lw, tw) = (label.len() as u32 * 7 + 10, text.len() as u32 * 7 + 10); |
| 1142 | 1× | let svg = format!( |
| 1143 | | 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>"##, |
| 1144 | 1× | w = lw + tw, |
| 1145 | 1× | lx = lw / 2, |
| 1146 | 1× | tx = lw + tw / 2, |
| 1147 | | ); |
| 1148 | 1× | Ok(( |
| 1149 | 1× | [(axum::http::header::CONTENT_TYPE, "image/svg+xml; charset=utf-8"), (axum::http::header::CACHE_CONTROL, "no-cache, max-age=60")], |
| 1150 | 1× | svg, |
| 1151 | 1× | ) |
| 1152 | 1× | .into_response()) |
| 1153 | 1× | } |
| 1154 | |
|
| 1155 | | #[cfg(test)] |
| 1156 | | mod section_tests { |
| 1157 | | use super::*; |
| 1158 | |
|
| 1159 | 9× | fn line(seq: i64, t: i64, text: &str) -> fdb::LogLine { |
| 1160 | 9× | fdb::LogLine { seq, t, stream: "out".into(), text: text.into() } |
| 1161 | 9× | } |
| 1162 | |
|
| 1163 | | #[test] |
| 1164 | 1× | fn marked_lines_fold_into_sections() { |
| 1165 | 1× | let lines = vec![ |
| 1166 | 1× | line(1, 0, "booting"), |
| 1167 | 1× | line(2, 100, "::group::cargo build"), |
| 1168 | 1× | line(3, 200, "Compiling a"), |
| 1169 | 1× | line(4, 900, "Compiling b"), |
| 1170 | 1× | line(5, 4_300, "::endgroup::"), |
| 1171 | 1× | line(6, 4_400, "::group::cargo test"), |
| 1172 | 1× | line(7, 4_500, "test x ... ok"), |
| 1173 | 1× | line(8, 5_000, "::group::lint"), |
| 1174 | 1× | line(9, 5_100, "clean"), |
| 1175 | | ]; |
| 1176 | 1× | let segs = sections(&lines); |
| 1177 | 1× | assert_eq!(segs.len(), 4); |
| 1178 | 1× | assert!(matches!(&segs[0], Segment::Line(l) if l.text == "booting")); |
| 1179 | 1× | let Segment::Group(build) = &segs[1] else { panic!("a section") }; |
| 1180 | 1× | assert_eq!((build.title.as_str(), build.from_t, build.to_t, build.lines.len()), ("cargo build", 100, Some(4_300), 2)); |
| 1181 | 1× | let Segment::Group(test) = &segs[2] else { panic!("a section") }; |
| 1182 | 1× | assert_eq!(test.to_t, Some(5_000), "a new section ends the one before"); |
| 1183 | 1× | let Segment::Group(lint) = &segs[3] else { panic!("a section") }; |
| 1184 | 1× | assert_eq!((lint.to_t, lint.lines.len()), (None, 1), "still going"); |
| 1185 | 1× | assert_eq!(secs(4_200), "4.2s"); |
| 1186 | 1× | } |
| 1187 | | } |