CI run UX, partial re-runs, run artifacts zip, ANSI log viewer, superseded runs, config warnings
Browse files at this commit264395ddeb185d1c92d8bc18577f8b2f2d59ccbcParent: 48664c5- feat
- CI run UX, partial re-runs, run artifacts zip, ANSI log viewer, superseded runs, config warnings
13 changed files +1724 -48
- crates/forge-ci/src/config.rs +14 -0
- crates/forge-core/migrations/0050_run_warnings.sql +4 -0
- crates/forge-core/src/store/ci.rs +273 -21
- crates/forge-core/src/store/migrate.rs +1 -0
- crates/forge-web/Cargo.toml +1 -1
- crates/forge-web/assets/nav.js +337 -2
- crates/forge-web/src/ci/schedule.rs +89 -1
- crates/forge-web/src/i18n/releases_ci.rs +70 -0
- crates/forge-web/src/pages/ci_job.rs +91 -11
- crates/forge-web/src/pages/ci_runs.rs +288 -11
- crates/forge-web/src/pages/ci_tests.rs +245 -0
- docs/ci.md +42 -1
- style/main.scss +269 -0
crates/forge-ci/src/config.rsmodified+14 -0
| @@ -145,6 +145,9 @@ pub struct Triggers { | |||
| 145 | pub pull_request: bool, | 145 | pub pull_request: bool, |
| 146 | /// Defaults to `true`. | 146 | /// Defaults to `true`. |
| 147 | pub manual: bool, | 147 | pub manual: bool, |
| 148 | + /// Defaults to `false`. When set, a push to a branch cancels the queued and running runs of | ||
| 149 | + /// older commits on that branch. | ||
| 150 | + pub cancel_superseded: bool, | ||
| 148 | } | 151 | } |
| 149 | 152 | ||
| 150 | impl Default for Triggers { | 153 | impl Default for Triggers { |
| @@ -154,6 +157,7 @@ impl Default for Triggers { | |||
| 154 | tags: Vec::new(), | 157 | tags: Vec::new(), |
| 155 | pull_request: false, | 158 | pull_request: false, |
| 156 | manual: true, | 159 | manual: true, |
| 160 | + cancel_superseded: false, | ||
| 157 | } | 161 | } |
| 158 | } | 162 | } |
| 159 | } | 163 | } |
| @@ -700,6 +704,16 @@ artifacts = ["target/release/forge"] | |||
| 700 | assert!(cfg.on.push.is_empty()); | 704 | assert!(cfg.on.push.is_empty()); |
| 701 | } | 705 | } |
| 702 | 706 | ||
| 707 | + #[test] | ||
| 708 | + fn cancel_superseded_is_opt_in() { | ||
| 709 | + let cfg = parse_config(&job_toml("")).unwrap(); | ||
| 710 | + assert!(!cfg.on.cancel_superseded); | ||
| 711 | + let cfg = | ||
| 712 | + parse_config(&format!("[on]\ncancel_superseded = true\n{}", job_toml(""))).unwrap(); | ||
| 713 | + assert!(cfg.on.cancel_superseded); | ||
| 714 | + assert!(cfg.warnings.is_empty(), "{:?}", cfg.warnings); | ||
| 715 | + } | ||
| 716 | + | ||
| 703 | #[test] | 717 | #[test] |
| 704 | fn manual_can_be_disabled() { | 718 | fn manual_can_be_disabled() { |
| 705 | let cfg = parse_config(&format!("[on]\nmanual = false\n{}", job_toml(""))).unwrap(); | 719 | let cfg = parse_config(&format!("[on]\nmanual = false\n{}", job_toml(""))).unwrap(); |
crates/forge-core/migrations/0050_run_warnings.sqladded+4 -0
| @@ -0,0 +1,4 @@ | |||
| 1 | +-- Config warnings of a run (ignored ci.toml keys), one per line, shown as a banner on the run page. | ||
| 2 | +-- NULL when the run had none. Applied by store/migrate.rs. | ||
| 3 | + | ||
| 4 | +ALTER TABLE ci_runs ADD COLUMN config_warnings TEXT; | ||
crates/forge-core/src/store/ci.rsmodified+273 -21
| @@ -142,6 +142,17 @@ fn map_artifact(row: &Row) -> Result<CiArtifact> { | |||
| 142 | }) | 142 | }) |
| 143 | } | 143 | } |
| 144 | 144 | ||
| 145 | +/// `spec` with its `needs` array replaced. Malformed input is returned as it is. | ||
| 146 | +fn spec_with_needs(spec: &str, needs: &[String]) -> String { | ||
| 147 | + match serde_json::from_str::<serde_json::Value>(spec) { | ||
| 148 | + Ok(mut value) if value.is_object() => { | ||
| 149 | + value["needs"] = serde_json::Value::from(needs.to_vec()); | ||
| 150 | + value.to_string() | ||
| 151 | + } | ||
| 152 | + _ => spec.to_owned(), | ||
| 153 | + } | ||
| 154 | +} | ||
| 155 | + | ||
| 145 | /// The `needs` array of a JobSpec. Missing or malformed input gives no needs. | 156 | /// The `needs` array of a JobSpec. Missing or malformed input gives no needs. |
| 146 | fn spec_needs(spec: &str) -> Vec<String> { | 157 | fn spec_needs(spec: &str) -> Vec<String> { |
| 147 | serde_json::from_str::<serde_json::Value>(spec) | 158 | serde_json::from_str::<serde_json::Value>(spec) |
| @@ -1021,20 +1032,91 @@ impl Store { | |||
| 1021 | /// A new run, with the next number, for the same commit, ref, trigger and job specs. The | 1032 | /// A new run, with the next number, for the same commit, ref, trigger and job specs. The |
| 1022 | /// new run is queued at once, without approval. | 1033 | /// new run is queued at once, without approval. |
| 1023 | pub async fn rerun(&self, run_id: &str, actor_id: &str) -> Result<CiRun> { | 1034 | pub async fn rerun(&self, run_id: &str, actor_id: &str) -> Result<CiRun> { |
| 1024 | - let (run, jobs) = { | 1035 | + let (run, jobs) = self.run_and_jobs(run_id).await?; |
| 1025 | - let conn = self.read_conn().await; | 1036 | + let names: Vec<String> = jobs.iter().map(|j| j.name.clone()).collect(); |
| 1026 | - let run = load_run(&conn, run_id).await?.ok_or(Error::NotFound)?; | 1037 | + self.rerun_subset(&run, &jobs, &names, actor_id).await |
| 1027 | - let jobs = jobs_of_run(&conn, run_id).await?; | 1038 | + } |
| 1028 | - (run, jobs) | 1039 | + |
| 1029 | - }; | 1040 | + /// A new run with only the failed, errored and cancelled jobs of a finished run, and every |
| 1041 | + /// job that depends on them (directly or not). Specs are the originals; a need on a job that | ||
| 1042 | + /// is not in the new run is dropped, since that job succeeded in the original run. | ||
| 1043 | + /// `Conflict` when the run is not finished or has no such job. | ||
| 1044 | + pub async fn rerun_failed(&self, run_id: &str, actor_id: &str) -> Result<CiRun> { | ||
| 1045 | + let (run, jobs) = self.run_and_jobs(run_id).await?; | ||
| 1046 | + if !run.state.is_terminal() { | ||
| 1047 | + return Err(Error::Conflict("the run has not finished".into())); | ||
| 1048 | + } | ||
| 1049 | + let seeds: Vec<String> = jobs | ||
| 1050 | + .iter() | ||
| 1051 | + .filter(|j| { | ||
| 1052 | + matches!( | ||
| 1053 | + j.state, | ||
| 1054 | + JobState::Failure | JobState::Error | JobState::Cancelled | ||
| 1055 | + ) | ||
| 1056 | + }) | ||
| 1057 | + .map(|j| j.name.clone()) | ||
| 1058 | + .collect(); | ||
| 1059 | + if seeds.is_empty() { | ||
| 1060 | + return Err(Error::Conflict("the run has no failed jobs".into())); | ||
| 1061 | + } | ||
| 1062 | + self.rerun_subset(&run, &jobs, &seeds, actor_id).await | ||
| 1063 | + } | ||
| 1064 | + | ||
| 1065 | + /// A new run with one finished job of `run_id` and the jobs that depend on it. `NotFound` when | ||
| 1066 | + /// the job is not in the run, `Conflict` when it has not finished. | ||
| 1067 | + pub async fn rerun_job(&self, run_id: &str, job_id: &str, actor_id: &str) -> Result<CiRun> { | ||
| 1068 | + let (run, jobs) = self.run_and_jobs(run_id).await?; | ||
| 1069 | + let job = jobs | ||
| 1070 | + .iter() | ||
| 1071 | + .find(|j| j.id == job_id) | ||
| 1072 | + .ok_or(Error::NotFound)?; | ||
| 1073 | + if !job.state.is_terminal() { | ||
| 1074 | + return Err(Error::Conflict("the job has not finished".into())); | ||
| 1075 | + } | ||
| 1076 | + self.rerun_subset(&run, &jobs, std::slice::from_ref(&job.name), actor_id) | ||
| 1077 | + .await | ||
| 1078 | + } | ||
| 1079 | + | ||
| 1080 | + async fn run_and_jobs(&self, run_id: &str) -> Result<(CiRun, Vec<CiJob>)> { | ||
| 1081 | + let conn = self.read_conn().await; | ||
| 1082 | + let run = load_run(&conn, run_id).await?.ok_or(Error::NotFound)?; | ||
| 1083 | + let jobs = jobs_of_run(&conn, run_id).await?; | ||
| 1084 | + Ok((run, jobs)) | ||
| 1085 | + } | ||
| 1086 | + | ||
| 1087 | + /// Creates a run of `seeds` and their dependants out of `jobs`, and copies the warnings. | ||
| 1088 | + async fn rerun_subset( | ||
| 1089 | + &self, | ||
| 1090 | + run: &CiRun, | ||
| 1091 | + jobs: &[CiJob], | ||
| 1092 | + seeds: &[String], | ||
| 1093 | + actor_id: &str, | ||
| 1094 | + ) -> Result<CiRun> { | ||
| 1095 | + let mut chosen: Vec<&str> = seeds.iter().map(String::as_str).collect(); | ||
| 1096 | + loop { | ||
| 1097 | + let before = chosen.len(); | ||
| 1098 | + for job in jobs { | ||
| 1099 | + if !chosen.contains(&job.name.as_str()) | ||
| 1100 | + && spec_needs(&job.spec_json) | ||
| 1101 | + .iter() | ||
| 1102 | + .any(|need| chosen.contains(&need.as_str())) | ||
| 1103 | + { | ||
| 1104 | + chosen.push(job.name.as_str()); | ||
| 1105 | + } | ||
| 1106 | + } | ||
| 1107 | + if chosen.len() == before { | ||
| 1108 | + break; | ||
| 1109 | + } | ||
| 1110 | + } | ||
| 1030 | let owned: Vec<(String, String, Vec<String>)> = jobs | 1111 | let owned: Vec<(String, String, Vec<String>)> = jobs |
| 1031 | .iter() | 1112 | .iter() |
| 1113 | + .filter(|j| chosen.contains(&j.name.as_str())) | ||
| 1032 | .map(|j| { | 1114 | .map(|j| { |
| 1033 | - ( | 1115 | + let needs: Vec<String> = spec_needs(&j.spec_json) |
| 1034 | - j.name.clone(), | 1116 | + .into_iter() |
| 1035 | - j.spec_json.clone(), | 1117 | + .filter(|need| chosen.contains(&need.as_str())) |
| 1036 | - spec_needs(&j.spec_json), | 1118 | + .collect(); |
| 1037 | - ) | 1119 | + (j.name.clone(), spec_with_needs(&j.spec_json, &needs), needs) |
| 1038 | }) | 1120 | }) |
| 1039 | .collect(); | 1121 | .collect(); |
| 1040 | let new_jobs: Vec<NewJob<'_>> = owned | 1122 | let new_jobs: Vec<NewJob<'_>> = owned |
| @@ -1045,16 +1127,77 @@ impl Store { | |||
| 1045 | needs, | 1127 | needs, |
| 1046 | }) | 1128 | }) |
| 1047 | .collect(); | 1129 | .collect(); |
| 1048 | - self.create_run( | 1130 | + let created = self |
| 1049 | - &run.repo_id, | 1131 | + .create_run( |
| 1050 | - &run.trigger, | 1132 | + &run.repo_id, |
| 1051 | - &run.git_ref, | 1133 | + &run.trigger, |
| 1052 | - &run.commit_oid, | 1134 | + &run.git_ref, |
| 1053 | - run.pull_number, | 1135 | + &run.commit_oid, |
| 1054 | - actor_id, | 1136 | + run.pull_number, |
| 1055 | - false, | 1137 | + actor_id, |
| 1056 | - &new_jobs, | 1138 | + false, |
| 1057 | - run.config_error.as_deref(), | 1139 | + &new_jobs, |
| 1140 | + run.config_error.as_deref(), | ||
| 1141 | + ) | ||
| 1142 | + .await?; | ||
| 1143 | + let warnings = self.run_warnings(&run.id).await?; | ||
| 1144 | + if !warnings.is_empty() { | ||
| 1145 | + self.set_run_warnings(&created.id, &warnings).await?; | ||
| 1146 | + } | ||
| 1147 | + Ok(created) | ||
| 1148 | + } | ||
| 1149 | + | ||
| 1150 | + /// Stores the config warnings of a run, replacing any earlier ones. | ||
| 1151 | + pub async fn set_run_warnings(&self, run_id: &str, warnings: &[String]) -> Result<()> { | ||
| 1152 | + let joined = (!warnings.is_empty()).then(|| warnings.join("\n")); | ||
| 1153 | + let conn = self.inner.conn.lock().await; | ||
| 1154 | + conn.execute( | ||
| 1155 | + "UPDATE ci_runs SET config_warnings = ?2 WHERE id = ?1", | ||
| 1156 | + vec![text(run_id), opt_text(joined.as_deref())], | ||
| 1157 | + ) | ||
| 1158 | + .await | ||
| 1159 | + .map_err(db_err)?; | ||
| 1160 | + Ok(()) | ||
| 1161 | + } | ||
| 1162 | + | ||
| 1163 | + /// The config warnings stored for a run, in order. | ||
| 1164 | + pub async fn run_warnings(&self, run_id: &str) -> Result<Vec<String>> { | ||
| 1165 | + let conn = self.read_conn().await; | ||
| 1166 | + let joined = fetch_opt( | ||
| 1167 | + &conn, | ||
| 1168 | + "SELECT config_warnings FROM ci_runs WHERE id = ?1", | ||
| 1169 | + (run_id.to_string(),), | ||
| 1170 | + |row| col_opt_text(row, 0), | ||
| 1171 | + ) | ||
| 1172 | + .await? | ||
| 1173 | + .flatten(); | ||
| 1174 | + Ok(joined | ||
| 1175 | + .map(|text| text.lines().map(str::to_owned).collect()) | ||
| 1176 | + .unwrap_or_default()) | ||
| 1177 | + } | ||
| 1178 | + | ||
| 1179 | + /// Runs on `git_ref` of the repo that are still queued or running, were started by a push, and | ||
| 1180 | + /// are for a commit other than `commit_oid`. The runs a newer push supersedes. | ||
| 1181 | + pub async fn superseded_candidates( | ||
| 1182 | + &self, | ||
| 1183 | + repo_id: &str, | ||
| 1184 | + git_ref: &str, | ||
| 1185 | + commit_oid: &str, | ||
| 1186 | + ) -> Result<Vec<CiRun>> { | ||
| 1187 | + let conn = self.read_conn().await; | ||
| 1188 | + fetch_all( | ||
| 1189 | + &conn, | ||
| 1190 | + &format!( | ||
| 1191 | + "SELECT {RUN_COLS} FROM ci_runs WHERE repo_id = ?1 AND git_ref = ?2 \ | ||
| 1192 | + AND trigger = 'push' AND commit_oid <> ?3 \ | ||
| 1193 | + AND state IN ('queued', 'running') ORDER BY number" | ||
| 1194 | + ), | ||
| 1195 | + ( | ||
| 1196 | + repo_id.to_string(), | ||
| 1197 | + git_ref.to_string(), | ||
| 1198 | + commit_oid.to_string(), | ||
| 1199 | + ), | ||
| 1200 | + map_run, | ||
| 1058 | ) | 1201 | ) |
| 1059 | .await | 1202 | .await |
| 1060 | } | 1203 | } |
| @@ -2273,6 +2416,115 @@ mod tests { | |||
| 2273 | )); | 2416 | )); |
| 2274 | } | 2417 | } |
| 2275 | 2418 | ||
| 2419 | + #[tokio::test] | ||
| 2420 | + async fn partial_reruns_take_failed_jobs_and_their_dependants() { | ||
| 2421 | + let fx = fixture().await; | ||
| 2422 | + let jobs = [ | ||
| 2423 | + job("a", &[], &[]), | ||
| 2424 | + job("b", &["a"], &[]), | ||
| 2425 | + job("c", &["b"], &[]), | ||
| 2426 | + job("d", &[], &[]), | ||
| 2427 | + ]; | ||
| 2428 | + let first = create(&fx.store, &fx.repo.id, &fx.tahinli.id, &jobs, false).await; | ||
| 2429 | + assert!(matches!( | ||
| 2430 | + fx.store.rerun_failed(&first.id, &fx.tahinli.id).await, | ||
| 2431 | + Err(Error::Conflict(_)) | ||
| 2432 | + )); | ||
| 2433 | + let a = job_named(&fx.store, &first.id, "a").await; | ||
| 2434 | + fx.store | ||
| 2435 | + .finish_job(&a.id, JobState::Success, Some(0), None) | ||
| 2436 | + .await | ||
| 2437 | + .unwrap(); | ||
| 2438 | + let b = job_named(&fx.store, &first.id, "b").await; | ||
| 2439 | + fx.store | ||
| 2440 | + .finish_job(&b.id, JobState::Failure, Some(1), None) | ||
| 2441 | + .await | ||
| 2442 | + .unwrap(); | ||
| 2443 | + // Fail fast cancels the queued `d` and skips `c`. | ||
| 2444 | + let done = fx.store.run_by_id(&first.id).await.unwrap().unwrap(); | ||
| 2445 | + assert_eq!(done.state, RunState::Failure); | ||
| 2446 | + assert_eq!( | ||
| 2447 | + job_named(&fx.store, &first.id, "d").await.state, | ||
| 2448 | + JobState::Cancelled | ||
| 2449 | + ); | ||
| 2450 | + | ||
| 2451 | + let again = fx | ||
| 2452 | + .store | ||
| 2453 | + .rerun_failed(&first.id, &fx.tahinli.id) | ||
| 2454 | + .await | ||
| 2455 | + .unwrap(); | ||
| 2456 | + let names: Vec<String> = fx | ||
| 2457 | + .store | ||
| 2458 | + .jobs_for_run(&again.id) | ||
| 2459 | + .await | ||
| 2460 | + .unwrap() | ||
| 2461 | + .into_iter() | ||
| 2462 | + .map(|j| j.name) | ||
| 2463 | + .collect(); | ||
| 2464 | + assert_eq!(names, ["b", "c", "d"]); | ||
| 2465 | + let b2 = job_named(&fx.store, &again.id, "b").await; | ||
| 2466 | + assert_eq!(b2.state, JobState::Queued, "its need succeeded before"); | ||
| 2467 | + assert!(spec_needs(&b2.spec_json).is_empty()); | ||
| 2468 | + let c2 = job_named(&fx.store, &again.id, "c").await; | ||
| 2469 | + assert_eq!(c2.state, JobState::Blocked); | ||
| 2470 | + assert_eq!(spec_needs(&c2.spec_json), ["b"]); | ||
| 2471 | + | ||
| 2472 | + // One finished job brings its dependants; a live one is refused. | ||
| 2473 | + let single = fx | ||
| 2474 | + .store | ||
| 2475 | + .rerun_job(&first.id, &a.id, &fx.tahinli.id) | ||
| 2476 | + .await | ||
| 2477 | + .unwrap(); | ||
| 2478 | + assert_eq!(fx.store.jobs_for_run(&single.id).await.unwrap().len(), 3); | ||
| 2479 | + assert!(matches!( | ||
| 2480 | + fx.store.rerun_job(&again.id, &b2.id, &fx.tahinli.id).await, | ||
| 2481 | + Err(Error::Conflict(_)) | ||
| 2482 | + )); | ||
| 2483 | + assert!(matches!( | ||
| 2484 | + fx.store.rerun_job(&again.id, &a.id, &fx.tahinli.id).await, | ||
| 2485 | + Err(Error::NotFound) | ||
| 2486 | + )); | ||
| 2487 | + } | ||
| 2488 | + | ||
| 2489 | + #[tokio::test] | ||
| 2490 | + async fn warnings_are_stored_and_carried_into_reruns() { | ||
| 2491 | + let fx = fixture().await; | ||
| 2492 | + let jobs = [job("a", &[], &[])]; | ||
| 2493 | + let run = create(&fx.store, &fx.repo.id, &fx.tahinli.id, &jobs, false).await; | ||
| 2494 | + assert!(fx.store.run_warnings(&run.id).await.unwrap().is_empty()); | ||
| 2495 | + let warnings = vec!["unknown key `on.schedule`".to_owned(), "second".to_owned()]; | ||
| 2496 | + fx.store.set_run_warnings(&run.id, &warnings).await.unwrap(); | ||
| 2497 | + assert_eq!(fx.store.run_warnings(&run.id).await.unwrap(), warnings); | ||
| 2498 | + let again = fx.store.rerun(&run.id, &fx.tahinli.id).await.unwrap(); | ||
| 2499 | + assert_eq!(fx.store.run_warnings(&again.id).await.unwrap(), warnings); | ||
| 2500 | + } | ||
| 2501 | + | ||
| 2502 | + #[tokio::test] | ||
| 2503 | + async fn superseded_candidates_are_older_live_push_runs_on_the_ref() { | ||
| 2504 | + let fx = fixture().await; | ||
| 2505 | + let jobs = [job("a", &[], &[])]; | ||
| 2506 | + let first = create(&fx.store, &fx.repo.id, &fx.tahinli.id, &jobs, false).await; | ||
| 2507 | + let found = fx | ||
| 2508 | + .store | ||
| 2509 | + .superseded_candidates(&fx.repo.id, "refs/heads/main", "def456") | ||
| 2510 | + .await | ||
| 2511 | + .unwrap(); | ||
| 2512 | + assert_eq!(found.len(), 1); | ||
| 2513 | + assert_eq!(found[0].id, first.id); | ||
| 2514 | + let same = fx | ||
| 2515 | + .store | ||
| 2516 | + .superseded_candidates(&fx.repo.id, "refs/heads/main", "abc123") | ||
| 2517 | + .await | ||
| 2518 | + .unwrap(); | ||
| 2519 | + assert!(same.is_empty()); | ||
| 2520 | + let elsewhere = fx | ||
| 2521 | + .store | ||
| 2522 | + .superseded_candidates(&fx.repo.id, "refs/heads/other", "def456") | ||
| 2523 | + .await | ||
| 2524 | + .unwrap(); | ||
| 2525 | + assert!(elsewhere.is_empty()); | ||
| 2526 | + } | ||
| 2527 | + | ||
| 2276 | #[tokio::test] | 2528 | #[tokio::test] |
| 2277 | async fn reap_lost_jobs_errors_stale_running_jobs() { | 2529 | async fn reap_lost_jobs_errors_stale_running_jobs() { |
| 2278 | let fx = fixture().await; | 2530 | let fx = fixture().await; |
crates/forge-core/src/store/migrate.rsmodified+1 -0
| @@ -71,6 +71,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 71 | 46, | 71 | 46, |
| 72 | include_str!("../../migrations/0046_server_settings.sql"), | 72 | include_str!("../../migrations/0046_server_settings.sql"), |
| 73 | ), | 73 | ), |
| 74 | + (50, include_str!("../../migrations/0050_run_warnings.sql")), | ||
| 74 | ]; | 75 | ]; |
| 75 | 76 | ||
| 76 | /// The highest migration version this binary knows about. | 77 | /// The highest migration version this binary knows about. |
crates/forge-web/Cargo.tomlmodified+1 -1
| @@ -52,6 +52,7 @@ multer.workspace = true | |||
| 52 | ulid.workspace = true | 52 | ulid.workspace = true |
| 53 | forge-runner = { workspace = true } | 53 | forge-runner = { workspace = true } |
| 54 | lettre.workspace = true | 54 | lettre.workspace = true |
| 55 | +zip = { workspace = true } | ||
| 55 | 56 | ||
| 56 | [build-dependencies] | 57 | [build-dependencies] |
| 57 | grass.workspace = true | 58 | grass.workspace = true |
| @@ -63,4 +64,3 @@ tempfile.workspace = true | |||
| 63 | forge-runner = { workspace = true, features = ["test-host-executor"] } | 64 | forge-runner = { workspace = true, features = ["test-host-executor"] } |
| 64 | image = { workspace = true } | 65 | image = { workspace = true } |
| 65 | scraper = { workspace = true } | 66 | scraper = { workspace = true } |
| 66 | -zip = { workspace = true } | ||
crates/forge-web/assets/nav.jsmodified+337 -2
| @@ -150,6 +150,7 @@ | |||
| 150 | if (dd) { openDropdowns(dd); } | 150 | if (dd) { openDropdowns(dd); } |
| 151 | if (kept) { restoreFields(kept); } | 151 | if (kept) { restoreFields(kept); } |
| 152 | if (dd) { focusDropdown(dd); } | 152 | if (dd) { focusDropdown(dd); } |
| 153 | + syncLog(); | ||
| 153 | followTail(); | 154 | followTail(); |
| 154 | restoreJobs(jobs); | 155 | restoreJobs(jobs); |
| 155 | syncUnread(); | 156 | syncUnread(); |
| @@ -160,7 +161,7 @@ | |||
| 160 | // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place. | 161 | // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place. |
| 161 | function followTail() { | 162 | function followTail() { |
| 162 | var pre = document.querySelector('[data-live-log]'); | 163 | var pre = document.querySelector('[data-live-log]'); |
| 163 | - if (pre) { pre.scrollTop = pre.scrollHeight; } | 164 | + if (pre && !pre.querySelector('.ll-sel')) { pre.scrollTop = pre.scrollHeight; } |
| 164 | } | 165 | } |
| 165 | 166 | ||
| 166 | // The run page's job rows each have a last-line preview and a tail that opens under the row | 167 | // The run page's job rows each have a last-line preview and a tail that opens under the row |
| @@ -576,6 +577,338 @@ | |||
| 576 | 577 | ||
| 577 | syncUnread(); | 578 | syncUnread(); |
| 578 | 579 | ||
| 580 | + // The CI log (a job page's [data-live-log]). The server sends the raw text; this turns it into | ||
| 581 | + // numbered lines (#L12 anchors) with ANSI colours as spans, `::group::name` / `::endgroup::` | ||
| 582 | + // sections as <details>, and a search box with highlight and next/previous. Streamed bytes go | ||
| 583 | + // through the same feed. All text is set with textContent, never as HTML. | ||
| 584 | + var logQuery = ''; // the search text survives a live swap of the page | ||
| 585 | + var LOG_MAX_MARKS = 2000; | ||
| 586 | + | ||
| 587 | + function ansiState() { return { fg: null, bg: null, b: false, d: false, i: false, u: false, v: false }; } | ||
| 588 | + | ||
| 589 | + function ansiCopy(s) { return { fg: s.fg, bg: s.bg, b: s.b, d: s.d, i: s.i, u: s.u, v: s.v }; } | ||
| 590 | + | ||
| 591 | + // The rgb of an xterm 256-colour index above the 16 named ones, as a CSS colour. | ||
| 592 | + function ansi256(n) { | ||
| 593 | + if (n < 16) { return n; } | ||
| 594 | + if (n >= 232) { var g = 8 + (n - 232) * 10; return 'rgb(' + g + ',' + g + ',' + g + ')'; } | ||
| 595 | + n -= 16; | ||
| 596 | + var lv = [0, 95, 135, 175, 215, 255]; | ||
| 597 | + return 'rgb(' + lv[Math.floor(n / 36) % 6] + ',' + lv[Math.floor(n / 6) % 6] + ',' + lv[n % 6] + ')'; | ||
| 598 | + } | ||
| 599 | + | ||
| 600 | + // Applies the numbers of one SGR sequence (ESC [ ... m) to `s`. | ||
| 601 | + function ansiApply(s, codes) { | ||
| 602 | + if (!codes.length) { codes = [0]; } | ||
| 603 | + for (var k = 0; k < codes.length; k++) { | ||
| 604 | + var c = codes[k]; | ||
| 605 | + if (c === 0) { var z = ansiState(); s.fg = z.fg; s.bg = z.bg; s.b = s.d = s.i = s.u = s.v = false; } | ||
| 606 | + else if (c === 1) { s.b = true; } | ||
| 607 | + else if (c === 2) { s.d = true; } | ||
| 608 | + else if (c === 3) { s.i = true; } | ||
| 609 | + else if (c === 4) { s.u = true; } | ||
| 610 | + else if (c === 7) { s.v = true; } | ||
| 611 | + else if (c === 22) { s.b = false; s.d = false; } | ||
| 612 | + else if (c === 23) { s.i = false; } | ||
| 613 | + else if (c === 24) { s.u = false; } | ||
| 614 | + else if (c === 27) { s.v = false; } | ||
| 615 | + else if (c >= 30 && c <= 37) { s.fg = c - 30; } | ||
| 616 | + else if (c >= 90 && c <= 97) { s.fg = c - 90 + 8; } | ||
| 617 | + else if (c >= 40 && c <= 47) { s.bg = c - 40; } | ||
| 618 | + else if (c >= 100 && c <= 107) { s.bg = c - 100 + 8; } | ||
| 619 | + else if (c === 39) { s.fg = null; } | ||
| 620 | + else if (c === 49) { s.bg = null; } | ||
| 621 | + else if (c === 38 || c === 48) { | ||
| 622 | + var val = null; | ||
| 623 | + if (codes[k + 1] === 5 && k + 2 < codes.length) { val = ansi256(codes[k + 2]); k += 2; } | ||
| 624 | + else if (codes[k + 1] === 2 && k + 4 < codes.length) { | ||
| 625 | + val = 'rgb(' + codes[k + 2] + ',' + codes[k + 3] + ',' + codes[k + 4] + ')'; k += 4; | ||
| 626 | + } else { break; } | ||
| 627 | + if (c === 38) { s.fg = val; } else { s.bg = val; } | ||
| 628 | + } | ||
| 629 | + } | ||
| 630 | + } | ||
| 631 | + | ||
| 632 | + // The span for a run of text in state `s`: a class per named colour (so the theme tokens apply | ||
| 633 | + // in light and dark), an inline colour only for the 256 and rgb ones. | ||
| 634 | + function ansiSpan(s, text) { | ||
| 635 | + var plain = s.fg === null && s.bg === null && !s.b && !s.d && !s.i && !s.u && !s.v; | ||
| 636 | + if (plain) { return document.createTextNode(text); } | ||
| 637 | + var el = document.createElement('span'); | ||
| 638 | + var cls = []; | ||
| 639 | + if (typeof s.fg === 'number') { cls.push('a-fg-' + s.fg); } else if (s.fg) { el.style.color = s.fg; } | ||
| 640 | + if (typeof s.bg === 'number') { cls.push('a-bg-' + s.bg); } else if (s.bg) { el.style.backgroundColor = s.bg; } | ||
| 641 | + if (s.b) { cls.push('a-b'); } | ||
| 642 | + if (s.d) { cls.push('a-d'); } | ||
| 643 | + if (s.i) { cls.push('a-i'); } | ||
| 644 | + if (s.u) { cls.push('a-u'); } | ||
| 645 | + if (s.v) { cls.push('a-v'); } | ||
| 646 | + el.className = cls.join(' '); | ||
| 647 | + el.textContent = text; | ||
| 648 | + return el; | ||
| 649 | + } | ||
| 650 | + | ||
| 651 | + // Renders `raw` (one line) from state `start` into `into`. Returns the state at the line's end. | ||
| 652 | + // A carriage return overwrites the line, so only what follows the last one shows. | ||
| 653 | + function ansiLine(into, raw, start) { | ||
| 654 | + var parts = raw.split('\r'); | ||
| 655 | + var shown = parts[0]; | ||
| 656 | + for (var p = 1; p < parts.length; p++) { if (parts[p] !== '') { shown = parts[p]; } } | ||
| 657 | + var s = ansiCopy(start); | ||
| 658 | + var re = /\u001b\[([0-9;:]*)([@-~])|\u001b/g; | ||
| 659 | + var last = 0, m; | ||
| 660 | + into.textContent = ''; | ||
| 661 | + while ((m = re.exec(shown))) { | ||
| 662 | + if (m.index > last) { into.appendChild(ansiSpan(s, shown.slice(last, m.index))); } | ||
| 663 | + last = re.lastIndex; | ||
| 664 | + if (m[2] === 'm') { | ||
| 665 | + ansiApply(s, m[1] === '' ? [] : m[1].split(/[;:]/).map(function (n) { return parseInt(n, 10) || 0; })); | ||
| 666 | + } | ||
| 667 | + } | ||
| 668 | + if (last < shown.length) { into.appendChild(ansiSpan(s, shown.slice(last))); } | ||
| 669 | + return s; | ||
| 670 | + } | ||
| 671 | + | ||
| 672 | + function logLineEl(n) { | ||
| 673 | + var row = document.createElement('div'); | ||
| 674 | + row.className = 'll'; | ||
| 675 | + row.id = 'L' + n; | ||
| 676 | + var num = document.createElement('a'); | ||
| 677 | + num.className = 'ln'; | ||
| 678 | + num.href = '#L' + n; | ||
| 679 | + num.setAttribute('data-n', n); | ||
| 680 | + num.setAttribute('aria-label', 'L' + n); | ||
| 681 | + var text = document.createElement('span'); | ||
| 682 | + text.className = 'lt'; | ||
| 683 | + row.appendChild(num); | ||
| 684 | + row.appendChild(text); | ||
| 685 | + return row; | ||
| 686 | + } | ||
| 687 | + | ||
| 688 | + // Takes the text the server put in `pre` and starts the log state on it. | ||
| 689 | + function logInit(pre) { | ||
| 690 | + var raw = pre.textContent; | ||
| 691 | + var first = parseInt(pre.getAttribute('data-first') || '1', 10) || 1; | ||
| 692 | + pre.textContent = ''; | ||
| 693 | + pre._ci = { next: first, cur: null, st: ansiState(), stack: [pre], groups: 0, hit: -1 }; | ||
| 694 | + logFeed(pre, raw); | ||
| 695 | + pre.setAttribute('data-ci', '1'); | ||
| 696 | + } | ||
| 697 | + | ||
| 698 | + function logTop(ci) { return ci.stack[ci.stack.length - 1]; } | ||
| 699 | + | ||
| 700 | + // Adds text to the log: completes the open line, then makes a line for each newline. | ||
| 701 | + function logFeed(pre, text) { | ||
| 702 | + var ci = pre._ci; | ||
| 703 | + var pieces = text.split('\n'); | ||
| 704 | + for (var i = 0; i < pieces.length; i++) { | ||
| 705 | + var ends = i < pieces.length - 1; | ||
| 706 | + if (pieces[i] !== '' || ci.cur || ends) { | ||
| 707 | + if (!ci.cur) { | ||
| 708 | + var el = logLineEl(ci.next); | ||
| 709 | + logTop(ci).appendChild(el); | ||
| 710 | + ci.cur = { el: el, raw: '', start: ansiCopy(ci.st) }; | ||
| 711 | + } | ||
| 712 | + ci.cur.raw += pieces[i]; | ||
| 713 | + ansiLine(ci.cur.el.lastChild, ci.cur.raw, ci.cur.start); | ||
| 714 | + } | ||
| 715 | + if (ends) { logDone(pre); } | ||
| 716 | + } | ||
| 717 | + } | ||
| 718 | + | ||
| 719 | + // The open line is complete: carry its colours on, and turn group markers into sections. | ||
| 720 | + function logDone(pre) { | ||
| 721 | + var ci = pre._ci; | ||
| 722 | + var cur = ci.cur; | ||
| 723 | + ci.cur = null; | ||
| 724 | + var n = ci.next++; | ||
| 725 | + ci.st = ansiLine(cur.el.lastChild, cur.raw, cur.start); | ||
| 726 | + var plain = cur.el.lastChild.textContent; | ||
| 727 | + var g = /^::group::(.*)$/.exec(plain); | ||
| 728 | + if (g) { | ||
| 729 | + var det = document.createElement('details'); | ||
| 730 | + det.className = 'lg'; | ||
| 731 | + det.open = true; | ||
| 732 | + var sum = document.createElement('summary'); | ||
| 733 | + sum.className = 'll lgs'; | ||
| 734 | + sum.id = 'L' + n; | ||
| 735 | + var num = cur.el.firstChild; | ||
| 736 | + var title = document.createElement('span'); | ||
| 737 | + title.className = 'lt'; | ||
| 738 | + title.textContent = g[1].trim() || 'group'; | ||
| 739 | + sum.appendChild(num); | ||
| 740 | + sum.appendChild(title); | ||
| 741 | + det.appendChild(sum); | ||
| 742 | + cur.el.replaceWith(det); | ||
| 743 | + ci.stack.push(det); | ||
| 744 | + ci.groups++; | ||
| 745 | + var fold = document.querySelector('[data-log-fold-box]'); | ||
| 746 | + if (fold) { fold.hidden = false; } | ||
| 747 | + } else if (/^::endgroup::\s*$/.test(plain)) { | ||
| 748 | + cur.el.remove(); | ||
| 749 | + if (ci.stack.length > 1) { ci.stack.pop(); } | ||
| 750 | + } | ||
| 751 | + } | ||
| 752 | + | ||
| 753 | + function logOpenAround(el) { | ||
| 754 | + for (var p = el.parentNode; p && p.nodeType === 1; p = p.parentNode) { | ||
| 755 | + if (p.tagName === 'DETAILS') { p.open = true; } | ||
| 756 | + } | ||
| 757 | + } | ||
| 758 | + | ||
| 759 | + // Marks the line of a #L123 fragment and brings it into view. | ||
| 760 | + function logSelect(id, scroll) { | ||
| 761 | + var pre = document.querySelector('[data-live-log]'); | ||
| 762 | + if (!pre) { return false; } | ||
| 763 | + var prev = pre.querySelector('.ll-sel'); | ||
| 764 | + if (prev) { prev.classList.remove('ll-sel'); } | ||
| 765 | + var el = id ? document.getElementById(id) : null; | ||
| 766 | + if (!el || !pre.contains(el)) { return false; } | ||
| 767 | + logOpenAround(el); | ||
| 768 | + el.classList.add('ll-sel'); | ||
| 769 | + if (scroll) { el.scrollIntoView({ block: 'center' }); } | ||
| 770 | + return true; | ||
| 771 | + } | ||
| 772 | + | ||
| 773 | + function logClear(pre) { | ||
| 774 | + Array.prototype.forEach.call(pre.querySelectorAll('mark.lm'), function (mark) { | ||
| 775 | + var parent = mark.parentNode; | ||
| 776 | + parent.replaceChild(document.createTextNode(mark.textContent), mark); | ||
| 777 | + parent.normalize(); | ||
| 778 | + }); | ||
| 779 | + pre._ci.hit = -1; | ||
| 780 | + } | ||
| 781 | + | ||
| 782 | + function logCount(text, none) { | ||
| 783 | + var out = document.querySelector('[data-log-count]'); | ||
| 784 | + if (!out) { return; } | ||
| 785 | + out.textContent = text; | ||
| 786 | + out.classList.toggle('ci-none', !!none); | ||
| 787 | + } | ||
| 788 | + | ||
| 789 | + // Highlights every match of `q` (case-insensitive) in the log and selects the one at `keep`. | ||
| 790 | + function logFind(pre, q, keep) { | ||
| 791 | + logClear(pre); | ||
| 792 | + logCount('', false); | ||
| 793 | + if (!q) { return; } | ||
| 794 | + var needle = q.toLowerCase(); | ||
| 795 | + var total = 0; | ||
| 796 | + var texts = pre.querySelectorAll('.lt'); | ||
| 797 | + for (var t = 0; t < texts.length && total < LOG_MAX_MARKS; t++) { | ||
| 798 | + var walker = document.createTreeWalker(texts[t], NodeFilter.SHOW_TEXT); | ||
| 799 | + var nodes = []; | ||
| 800 | + while (walker.nextNode()) { nodes.push(walker.currentNode); } | ||
| 801 | + for (var k = 0; k < nodes.length && total < LOG_MAX_MARKS; k++) { | ||
| 802 | + var node = nodes[k]; | ||
| 803 | + var lower = node.data.toLowerCase(); | ||
| 804 | + var at = [], from = 0, idx; | ||
| 805 | + while ((idx = lower.indexOf(needle, from)) >= 0 && total + at.length < LOG_MAX_MARKS) { | ||
| 806 | + at.push(idx); | ||
| 807 | + from = idx + needle.length; | ||
| 808 | + } | ||
| 809 | + for (var m = at.length - 1; m >= 0; m--) { | ||
| 810 | + var mid = node.splitText(at[m]); | ||
| 811 | + mid.splitText(needle.length); | ||
| 812 | + var mark = document.createElement('mark'); | ||
| 813 | + mark.className = 'lm'; | ||
| 814 | + mid.parentNode.replaceChild(mark, mid); | ||
| 815 | + mark.appendChild(mid); | ||
| 816 | + } | ||
| 817 | + total += at.length; | ||
| 818 | + } | ||
| 819 | + } | ||
| 820 | + var marks = pre.querySelectorAll('mark.lm'); | ||
| 821 | + if (!marks.length) { | ||
| 822 | + var none = document.querySelector('[data-log-count]'); | ||
| 823 | + logCount(none ? none.getAttribute('data-none') || '' : '', true); | ||
| 824 | + return; | ||
| 825 | + } | ||
| 826 | + logGo(pre, keep >= 0 && keep < marks.length ? keep : 0, false); | ||
| 827 | + } | ||
| 828 | + | ||
| 829 | + // Makes match `i` the current one (wrapping) and scrolls to it. | ||
| 830 | + function logGo(pre, i, scroll) { | ||
| 831 | + var marks = pre.querySelectorAll('mark.lm'); | ||
| 832 | + if (!marks.length) { return; } | ||
| 833 | + i = (i + marks.length) % marks.length; | ||
| 834 | + var was = pre.querySelector('mark.lm-cur'); | ||
| 835 | + if (was) { was.classList.remove('lm-cur'); } | ||
| 836 | + var mark = marks[i]; | ||
| 837 | + mark.classList.add('lm-cur'); | ||
| 838 | + pre._ci.hit = i; | ||
| 839 | + logOpenAround(mark); | ||
| 840 | + if (scroll !== false) { mark.scrollIntoView({ block: 'center', inline: 'nearest' }); } | ||
| 841 | + logCount((i + 1) + ' / ' + marks.length + (marks.length >= LOG_MAX_MARKS ? '+' : ''), false); | ||
| 842 | + } | ||
| 843 | + | ||
| 844 | + var logFindFrame = 0; | ||
| 845 | + function logRefind(pre) { | ||
| 846 | + if (!logQuery || logFindFrame) { return; } | ||
| 847 | + logFindFrame = requestAnimationFrame(function () { | ||
| 848 | + logFindFrame = 0; | ||
| 849 | + if (pre._ci) { logFind(pre, logQuery, pre._ci.hit); } | ||
| 850 | + }); | ||
| 851 | + } | ||
| 852 | + | ||
| 853 | + function syncLog() { | ||
| 854 | + var pre = document.querySelector('[data-live-log]'); | ||
| 855 | + if (!pre || pre.getAttribute('data-ci')) { return; } | ||
| 856 | + logInit(pre); | ||
| 857 | + var input = document.querySelector('[data-log-q]'); | ||
| 858 | + if (input && logQuery) { input.value = logQuery; logFind(pre, logQuery, -1); } | ||
| 859 | + if (location.hash && /^#L\d+$/.test(location.hash)) { logSelect(location.hash.slice(1), true); } | ||
| 860 | + } | ||
| 861 | + | ||
| 862 | + document.addEventListener('input', function (e) { | ||
| 863 | + var input = e.target; | ||
| 864 | + if (!input || !input.hasAttribute || !input.hasAttribute('data-log-q')) { return; } | ||
| 865 | + var pre = document.querySelector('[data-live-log]'); | ||
| 866 | + if (!pre || !pre._ci) { return; } | ||
| 867 | + logQuery = input.value; | ||
| 868 | + logFind(pre, logQuery, -1); | ||
| 869 | + }); | ||
| 870 | + | ||
| 871 | + document.addEventListener('keydown', function (e) { | ||
| 872 | + var input = e.target; | ||
| 873 | + if (!input || !input.hasAttribute || !input.hasAttribute('data-log-q')) { return; } | ||
| 874 | + var pre = document.querySelector('[data-live-log]'); | ||
| 875 | + if (!pre || !pre._ci) { return; } | ||
| 876 | + if (e.key === 'Enter') { | ||
| 877 | + e.preventDefault(); | ||
| 878 | + logGo(pre, pre._ci.hit + (e.shiftKey ? -1 : 1), true); | ||
| 879 | + } else if (e.key === 'Escape') { | ||
| 880 | + input.value = ''; | ||
| 881 | + logQuery = ''; | ||
| 882 | + logFind(pre, '', -1); | ||
| 883 | + } | ||
| 884 | + }); | ||
| 885 | + | ||
| 886 | + document.addEventListener('click', function (e) { | ||
| 887 | + var el = e.target && e.target.closest ? e.target.closest('[data-log-prev],[data-log-next],[data-log-fold],a.ln') : null; | ||
| 888 | + if (!el) { return; } | ||
| 889 | + var pre = document.querySelector('[data-live-log]'); | ||
| 890 | + if (!pre || !pre._ci) { return; } | ||
| 891 | + if (el.classList.contains('ln')) { | ||
| 892 | + e.preventDefault(); | ||
| 893 | + e.stopPropagation(); | ||
| 894 | + var id = el.getAttribute('href').slice(1); | ||
| 895 | + history.replaceState(history.state, '', '#' + id); | ||
| 896 | + logSelect(id, false); | ||
| 897 | + return; | ||
| 898 | + } | ||
| 899 | + e.preventDefault(); | ||
| 900 | + if (el.hasAttribute('data-log-prev')) { logGo(pre, pre._ci.hit - 1, true); } | ||
| 901 | + else if (el.hasAttribute('data-log-next')) { logGo(pre, pre._ci.hit + 1, true); } | ||
| 902 | + else { | ||
| 903 | + var open = el.getAttribute('data-log-fold') === 'open'; | ||
| 904 | + Array.prototype.forEach.call(pre.querySelectorAll('details.lg'), function (d) { d.open = open; }); | ||
| 905 | + } | ||
| 906 | + }, true); | ||
| 907 | + | ||
| 908 | + window.addEventListener('hashchange', function () { | ||
| 909 | + if (/^#L\d+$/.test(location.hash)) { logSelect(location.hash.slice(1), true); } | ||
| 910 | + }); | ||
| 911 | + | ||
| 579 | // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of | 912 | // Live pages. A run or job page that is not finished marks its wrapper with data-live, the URL of |
| 580 | // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in | 913 | // its event stream. One EventSource follows it. A `changed` event re-fetches the page and swaps it in |
| 581 | // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose | 914 | // with no history entry and the scroll kept. A job page also has a log tail (data-live-log) whose |
| @@ -624,7 +957,8 @@ | |||
| 624 | var pre = document.querySelector('[data-live-log]'); | 957 | var pre = document.querySelector('[data-live-log]'); |
| 625 | if (!pre || !text) { return; } | 958 | if (!pre || !text) { return; } |
| 626 | var atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 24; | 959 | var atEnd = pre.scrollTop + pre.clientHeight >= pre.scrollHeight - 24; |
| 627 | - pre.appendChild(document.createTextNode(text)); | 960 | + if (pre._ci) { logFeed(pre, text); logRefind(pre); } |
| 961 | + else { pre.appendChild(document.createTextNode(text)); } | ||
| 628 | if (atEnd) { pre.scrollTop = pre.scrollHeight; } | 962 | if (atEnd) { pre.scrollTop = pre.scrollHeight; } |
| 629 | } | 963 | } |
| 630 | 964 | ||
| @@ -721,6 +1055,7 @@ | |||
| 721 | }); | 1055 | }); |
| 722 | } | 1056 | } |
| 723 | 1057 | ||
| 1058 | + syncLog(); | ||
| 724 | followTail(); | 1059 | followTail(); |
| 725 | syncLive(); | 1060 | syncLive(); |
| 726 | syncTick(); | 1061 | syncTick(); |
crates/forge-web/src/ci/schedule.rsmodified+89 -1
| @@ -47,6 +47,8 @@ enum Plan { | |||
| 47 | jobs: Vec<PlannedJob>, | 47 | jobs: Vec<PlannedJob>, |
| 48 | config_error: Option<String>, | 48 | config_error: Option<String>, |
| 49 | warnings: Vec<String>, | 49 | warnings: Vec<String>, |
| 50 | + /// `[on] cancel_superseded`: a push cancels the older live runs on its branch. | ||
| 51 | + cancel_superseded: bool, | ||
| 50 | }, | 52 | }, |
| 51 | } | 53 | } |
| 52 | 54 | ||
| @@ -87,9 +89,10 @@ pub async fn on_ref_update( | |||
| 87 | jobs, | 89 | jobs, |
| 88 | config_error, | 90 | config_error, |
| 89 | warnings, | 91 | warnings, |
| 92 | + cancel_superseded, | ||
| 90 | } = plan_for(loaded, &event)? | 93 | } = plan_for(loaded, &event)? |
| 91 | { | 94 | { |
| 92 | - create( | 95 | + let run = create( |
| 93 | state, | 96 | state, |
| 94 | Request { | 97 | Request { |
| 95 | repo, | 98 | repo, |
| @@ -105,6 +108,9 @@ pub async fn on_ref_update( | |||
| 105 | &warnings, | 108 | &warnings, |
| 106 | ) | 109 | ) |
| 107 | .await?; | 110 | .await?; |
| 111 | + if cancel_superseded && trigger == "push" { | ||
| 112 | + cancel_superseded_runs(state, &run).await?; | ||
| 113 | + } | ||
| 108 | } | 114 | } |
| 109 | forge_core::Result::Ok(()) | 115 | forge_core::Result::Ok(()) |
| 110 | } | 116 | } |
| @@ -137,6 +143,7 @@ async fn pull_run( | |||
| 137 | jobs, | 143 | jobs, |
| 138 | config_error, | 144 | config_error, |
| 139 | warnings, | 145 | warnings, |
| 146 | + .. | ||
| 140 | } = plan_for(loaded, &Event::PullRequest)? | 147 | } = plan_for(loaded, &Event::PullRequest)? |
| 141 | else { | 148 | else { |
| 142 | return Ok(()); | 149 | return Ok(()); |
| @@ -190,6 +197,7 @@ pub async fn manual_run( | |||
| 190 | jobs, | 197 | jobs, |
| 191 | config_error, | 198 | config_error, |
| 192 | warnings, | 199 | warnings, |
| 200 | + .. | ||
| 193 | } => { | 201 | } => { |
| 194 | create( | 202 | create( |
| 195 | state, | 203 | state, |
| @@ -249,6 +257,7 @@ async fn create( | |||
| 249 | ) | 257 | ) |
| 250 | .await?; | 258 | .await?; |
| 251 | state.ci_live.bump_repo(&run.repo_id); | 259 | state.ci_live.bump_repo(&run.repo_id); |
| 260 | + state.store.set_run_warnings(&run.id, warnings).await?; | ||
| 252 | note_warnings(state, &run, warnings).await?; | 261 | note_warnings(state, &run, warnings).await?; |
| 253 | if let Some(message) = config_error { | 262 | if let Some(message) = config_error { |
| 254 | let url = format!( | 263 | let url = format!( |
| @@ -275,6 +284,23 @@ async fn create( | |||
| 275 | Ok(run) | 284 | Ok(run) |
| 276 | } | 285 | } |
| 277 | 286 | ||
| 287 | +/// Cancels the queued and running push runs on the branch of `run` that are for older commits. | ||
| 288 | +/// Queued jobs are cancelled at once; running jobs stop at their next heartbeat. | ||
| 289 | +async fn cancel_superseded_runs(state: &AppState, run: &CiRun) -> forge_core::Result<()> { | ||
| 290 | + let older = state | ||
| 291 | + .store | ||
| 292 | + .superseded_candidates(&run.repo_id, &run.git_ref, &run.commit_oid) | ||
| 293 | + .await?; | ||
| 294 | + for old in older.into_iter().filter(|old| old.number < run.number) { | ||
| 295 | + let before = state.store.jobs_for_run(&old.id).await?; | ||
| 296 | + state.store.request_cancel(&old.id).await?; | ||
| 297 | + if let Err(e) = crate::pages::ci_runs::after_change(state, &old.id, &before).await { | ||
| 298 | + tracing::error!(error = %e, run_id = %old.id, "ci: syncing a superseded run failed"); | ||
| 299 | + } | ||
| 300 | + } | ||
| 301 | + Ok(()) | ||
| 302 | +} | ||
| 303 | + | ||
| 278 | /// Writes the config warnings as `[forge] warning: ...` lines at the start of every job's log, and | 304 | /// Writes the config warnings as `[forge] warning: ...` lines at the start of every job's log, and |
| 279 | /// logs them. Runs before the runners are woken, so the lines come first. A failed write is logged | 305 | /// logs them. Runs before the runners are woken, so the lines come first. A failed write is logged |
| 280 | /// and does not fail the run. | 306 | /// and does not fail the run. |
| @@ -342,6 +368,7 @@ fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result<Plan> { | |||
| 342 | jobs: Vec::new(), | 368 | jobs: Vec::new(), |
| 343 | config_error: Some(message), | 369 | config_error: Some(message), |
| 344 | warnings: Vec::new(), | 370 | warnings: Vec::new(), |
| 371 | + cancel_superseded: false, | ||
| 345 | }), | 372 | }), |
| 346 | Loaded::Valid(cfg) => { | 373 | Loaded::Valid(cfg) => { |
| 347 | if !cfg.triggered_by(event) { | 374 | if !cfg.triggered_by(event) { |
| @@ -351,6 +378,7 @@ fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result<Plan> { | |||
| 351 | jobs: plan_jobs(&cfg)?, | 378 | jobs: plan_jobs(&cfg)?, |
| 352 | config_error: None, | 379 | config_error: None, |
| 353 | warnings: cfg.warnings.clone(), | 380 | warnings: cfg.warnings.clone(), |
| 381 | + cancel_superseded: cfg.on.cancel_superseded, | ||
| 354 | }) | 382 | }) |
| 355 | } | 383 | } |
| 356 | } | 384 | } |
| @@ -1026,4 +1054,64 @@ run = "make" | |||
| 1026 | assert_eq!(logs, 1); | 1054 | assert_eq!(logs, 1); |
| 1027 | assert!(!path.exists(), "log file is deleted"); | 1055 | assert!(!path.exists(), "log file is deleted"); |
| 1028 | } | 1056 | } |
| 1057 | + | ||
| 1058 | + const CONFIG_SUPERSEDE: &str = r#" | ||
| 1059 | +[on] | ||
| 1060 | +push = ["main"] | ||
| 1061 | +cancel_superseded = true | ||
| 1062 | + | ||
| 1063 | +[jobs.build] | ||
| 1064 | +image = "alpine:3" | ||
| 1065 | +run = "make" | ||
| 1066 | +"#; | ||
| 1067 | + | ||
| 1068 | + #[tokio::test] | ||
| 1069 | + async fn a_newer_push_cancels_older_live_runs_when_asked() { | ||
| 1070 | + let fx = fixture().await; | ||
| 1071 | + push(&fx, &[(CONFIG_PATH, CONFIG_SUPERSEDE)], "refs/heads/main").await; | ||
| 1072 | + push(&fx, &[("a.txt", "a")], "refs/heads/main").await; | ||
| 1073 | + let store = &fx.state.store; | ||
| 1074 | + let first = store.run_by_number(&fx.repo.id, 1).await.unwrap().unwrap(); | ||
| 1075 | + let second = store.run_by_number(&fx.repo.id, 2).await.unwrap().unwrap(); | ||
| 1076 | + assert_eq!( | ||
| 1077 | + first.state, | ||
| 1078 | + RunState::Cancelled, | ||
| 1079 | + "the older run is cancelled" | ||
| 1080 | + ); | ||
| 1081 | + assert_eq!(second.state, RunState::Queued, "the newest run keeps going"); | ||
| 1082 | + let jobs = store.jobs_for_run(&first.id).await.unwrap(); | ||
| 1083 | + assert_eq!(state_of(&jobs, "build"), Some(JobState::Cancelled)); | ||
| 1084 | + } | ||
| 1085 | + | ||
| 1086 | + #[tokio::test] | ||
| 1087 | + async fn older_runs_are_kept_without_the_key() { | ||
| 1088 | + let fx = fixture().await; | ||
| 1089 | + push(&fx, &[(CONFIG_PATH, CONFIG_ONE_JOB)], "refs/heads/main").await; | ||
| 1090 | + push(&fx, &[("a.txt", "a")], "refs/heads/main").await; | ||
| 1091 | + let first = fx | ||
| 1092 | + .state | ||
| 1093 | + .store | ||
| 1094 | + .run_by_number(&fx.repo.id, 1) | ||
| 1095 | + .await | ||
| 1096 | + .unwrap() | ||
| 1097 | + .unwrap(); | ||
| 1098 | + assert_eq!(first.state, RunState::Queued); | ||
| 1099 | + } | ||
| 1100 | + | ||
| 1101 | + #[tokio::test] | ||
| 1102 | + async fn ignored_config_keys_are_stored_as_run_warnings() { | ||
| 1103 | + let fx = fixture().await; | ||
| 1104 | + let config = "[on]\npush = [\"main\"]\nschedule = true\n\n[jobs.build]\nimage = \"alpine:3\"\nrun = \"make\"\n"; | ||
| 1105 | + push(&fx, &[(CONFIG_PATH, config)], "refs/heads/main").await; | ||
| 1106 | + let run = fx | ||
| 1107 | + .state | ||
| 1108 | + .store | ||
| 1109 | + .run_by_number(&fx.repo.id, 1) | ||
| 1110 | + .await | ||
| 1111 | + .unwrap() | ||
| 1112 | + .unwrap(); | ||
| 1113 | + let warnings = fx.state.store.run_warnings(&run.id).await.unwrap(); | ||
| 1114 | + assert_eq!(warnings.len(), 1); | ||
| 1115 | + assert!(warnings[0].contains("`on.schedule`"), "{warnings:?}"); | ||
| 1116 | + } | ||
| 1029 | } | 1117 | } |
crates/forge-web/src/i18n/releases_ci.rsmodified+70 -0
| @@ -27,6 +27,21 @@ pub enum K { | |||
| 27 | ApproveAndRun, | 27 | ApproveAndRun, |
| 28 | Cancel, | 28 | Cancel, |
| 29 | Rerun, | 29 | Rerun, |
| 30 | + RerunFailed, | ||
| 31 | + RerunJob, | ||
| 32 | + DownloadAll, | ||
| 33 | + Download, | ||
| 34 | + ConfigWarnings, | ||
| 35 | + ConfigWarningsHint, | ||
| 36 | + CiNoticeNoFailed, | ||
| 37 | + CiNoticeNotDone, | ||
| 38 | + CiNoticeTooBig, | ||
| 39 | + LogSearch, | ||
| 40 | + LogPrev, | ||
| 41 | + LogNext, | ||
| 42 | + LogNoMatches, | ||
| 43 | + LogCollapseAll, | ||
| 44 | + LogExpandAll, | ||
| 30 | Runs, | 45 | Runs, |
| 31 | NoRunsYet, | 46 | NoRunsYet, |
| 32 | NoRunsHint, | 47 | NoRunsHint, |
| @@ -166,6 +181,46 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 166 | (ApproveAndRun, Tr) => "Onayla ve çalıştır", | 181 | (ApproveAndRun, Tr) => "Onayla ve çalıştır", |
| 167 | (Cancel, En) => "Cancel", | 182 | (Cancel, En) => "Cancel", |
| 168 | (Cancel, Tr) => "İptal et", | 183 | (Cancel, Tr) => "İptal et", |
| 184 | + (RerunFailed, En) => "Re-run failed jobs", | ||
| 185 | + (RerunFailed, Tr) => "Başarısız işleri yeniden çalıştır", | ||
| 186 | + (RerunJob, En) => "Re-run this job", | ||
| 187 | + (RerunJob, Tr) => "Bu işi yeniden çalıştır", | ||
| 188 | + (DownloadAll, En) => "Download all (.zip)", | ||
| 189 | + (DownloadAll, Tr) => "Hepsini indir (.zip)", | ||
| 190 | + (Download, En) => "Download", | ||
| 191 | + (Download, Tr) => "İndir", | ||
| 192 | + (ConfigWarnings, En) => "Config warnings", | ||
| 193 | + (ConfigWarnings, Tr) => "Yapılandırma uyarıları", | ||
| 194 | + (ConfigWarningsHint, En) => { | ||
| 195 | + "These keys of .forge/ci.toml were ignored, so they have no effect on this run." | ||
| 196 | + } | ||
| 197 | + (ConfigWarningsHint, Tr) => { | ||
| 198 | + "Bu .forge/ci.toml anahtarları yok sayıldı, bu çalıştırmayı etkilemiyor." | ||
| 199 | + } | ||
| 200 | + (CiNoticeNoFailed, En) => "This run has no failed or cancelled jobs to run again.", | ||
| 201 | + (CiNoticeNoFailed, Tr) => { | ||
| 202 | + "Bu çalıştırmada yeniden çalıştırılacak başarısız ya da iptal edilmiş iş yok." | ||
| 203 | + } | ||
| 204 | + (CiNoticeNotDone, En) => "That run or job has not finished yet. Nothing was changed.", | ||
| 205 | + (CiNoticeNotDone, Tr) => "Bu çalıştırma ya da iş henüz bitmedi. Hiçbir şey değiştirilmedi.", | ||
| 206 | + (CiNoticeTooBig, En) => { | ||
| 207 | + "The artifacts are too large to download as one file. Download them one by one." | ||
| 208 | + } | ||
| 209 | + (CiNoticeTooBig, Tr) => { | ||
| 210 | + "Yapıtlar tek dosya olarak indirilemeyecek kadar büyük. Tek tek indirin." | ||
| 211 | + } | ||
| 212 | + (LogSearch, En) => "Search the log", | ||
| 213 | + (LogSearch, Tr) => "Günlükte ara", | ||
| 214 | + (LogPrev, En) => "Previous match", | ||
| 215 | + (LogPrev, Tr) => "Önceki eşleşme", | ||
| 216 | + (LogNext, En) => "Next match", | ||
| 217 | + (LogNext, Tr) => "Sonraki eşleşme", | ||
| 218 | + (LogNoMatches, En) => "No matches", | ||
| 219 | + (LogNoMatches, Tr) => "Eşleşme yok", | ||
| 220 | + (LogCollapseAll, En) => "Collapse groups", | ||
| 221 | + (LogCollapseAll, Tr) => "Grupları daralt", | ||
| 222 | + (LogExpandAll, En) => "Expand groups", | ||
| 223 | + (LogExpandAll, Tr) => "Grupları genişlet", | ||
| 169 | (Rerun, En) => "Re-run", | 224 | (Rerun, En) => "Re-run", |
| 170 | (Rerun, Tr) => "Yeniden çalıştır", | 225 | (Rerun, Tr) => "Yeniden çalıştır", |
| 171 | (Runs, En) => "Runs", | 226 | (Runs, En) => "Runs", |
| @@ -492,6 +547,21 @@ mod tests { | |||
| 492 | K::ApproveAndRun, | 547 | K::ApproveAndRun, |
| 493 | K::Cancel, | 548 | K::Cancel, |
| 494 | K::Rerun, | 549 | K::Rerun, |
| 550 | + K::RerunFailed, | ||
| 551 | + K::RerunJob, | ||
| 552 | + K::DownloadAll, | ||
| 553 | + K::Download, | ||
| 554 | + K::ConfigWarnings, | ||
| 555 | + K::ConfigWarningsHint, | ||
| 556 | + K::CiNoticeNoFailed, | ||
| 557 | + K::CiNoticeNotDone, | ||
| 558 | + K::CiNoticeTooBig, | ||
| 559 | + K::LogSearch, | ||
| 560 | + K::LogPrev, | ||
| 561 | + K::LogNext, | ||
| 562 | + K::LogNoMatches, | ||
| 563 | + K::LogCollapseAll, | ||
| 564 | + K::LogExpandAll, | ||
| 495 | K::Runs, | 565 | K::Runs, |
| 496 | K::NoRunsYet, | 566 | K::NoRunsYet, |
| 497 | K::NoRunsHint, | 567 | K::NoRunsHint, |
crates/forge-web/src/pages/ci_job.rsmodified+91 -11
| @@ -34,7 +34,7 @@ use crate::i18n::{ | |||
| 34 | releases_ci::{self as g, K}, | 34 | releases_ci::{self as g, K}, |
| 35 | }; | 35 | }; |
| 36 | use crate::pages::ci_runs::{ | 36 | use crate::pages::ci_runs::{ |
| 37 | - changed_event, events_response, job_href, job_status, run_href, state_text, | 37 | + can_write, changed_event, events_response, job_href, job_status, run_href, state_text, |
| 38 | }; | 38 | }; |
| 39 | use crate::pages::repo::repo_head; | 39 | use crate::pages::repo::repo_head; |
| 40 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; | 40 | use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo}; |
| @@ -78,12 +78,50 @@ fn whole_utf8_len(buf: &[u8]) -> usize { | |||
| 78 | } | 78 | } |
| 79 | } | 79 | } |
| 80 | 80 | ||
| 81 | -/// The last `TAIL_BYTES` of a log, from a line boundary, whether anything was cut, and the byte | 81 | +/// What the job page shows of a log: the text, whether the start was cut, the byte offset just |
| 82 | -/// offset just past the text shown. A log that does not exist yet is empty. | 82 | +/// past the text, and the number of its first line in the whole log. |
| 83 | -async fn log_tail(path: &Path) -> Result<(String, bool, u64)> { | 83 | +struct Tail { |
| 84 | + text: String, | ||
| 85 | + truncated: bool, | ||
| 86 | + offset: u64, | ||
| 87 | + first_line: u64, | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// The number of newlines in the first `end` bytes of the file, so a cut log keeps true line numbers. | ||
| 91 | +async fn newlines_before(path: &Path, end: u64) -> Result<u64> { | ||
| 92 | + let mut file = tokio::fs::File::open(path) | ||
| 93 | + .await | ||
| 94 | + .map_err(forge_core::Error::Io)?; | ||
| 95 | + let mut left = end; | ||
| 96 | + let mut count = 0u64; | ||
| 97 | + let mut buf = vec![0u8; CHUNK_BYTES]; | ||
| 98 | + while left > 0 { | ||
| 99 | + let want = usize::try_from(left).map_or(CHUNK_BYTES, |n| n.min(CHUNK_BYTES)); | ||
| 100 | + let n = file | ||
| 101 | + .read(&mut buf[..want]) | ||
| 102 | + .await | ||
| 103 | + .map_err(forge_core::Error::Io)?; | ||
| 104 | + if n == 0 { | ||
| 105 | + break; | ||
| 106 | + } | ||
| 107 | + count += buf[..n].iter().filter(|byte| **byte == b'\n').count() as u64; | ||
| 108 | + left -= n as u64; | ||
| 109 | + } | ||
| 110 | + Ok(count) | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/// The last `TAIL_BYTES` of a log, from a line boundary. A log that does not exist yet is empty. | ||
| 114 | +async fn log_tail(path: &Path) -> Result<Tail> { | ||
| 84 | let mut file = match tokio::fs::File::open(path).await { | 115 | let mut file = match tokio::fs::File::open(path).await { |
| 85 | Ok(file) => file, | 116 | Ok(file) => file, |
| 86 | - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((String::new(), false, 0)), | 117 | + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 118 | + return Ok(Tail { | ||
| 119 | + text: String::new(), | ||
| 120 | + truncated: false, | ||
| 121 | + offset: 0, | ||
| 122 | + first_line: 1, | ||
| 123 | + }); | ||
| 124 | + } | ||
| 87 | Err(e) => return Err(forge_core::Error::Io(e).into()), | 125 | Err(e) => return Err(forge_core::Error::Io(e).into()), |
| 88 | }; | 126 | }; |
| 89 | let len = file.metadata().await.map_err(forge_core::Error::Io)?.len(); | 127 | let len = file.metadata().await.map_err(forge_core::Error::Io)?.len(); |
| @@ -107,11 +145,17 @@ async fn log_tail(path: &Path) -> Result<(String, bool, u64)> { | |||
| 107 | } | 145 | } |
| 108 | buf.truncate(whole_utf8_len(&buf)); | 146 | buf.truncate(whole_utf8_len(&buf)); |
| 109 | let offset = start + buf.len() as u64; | 147 | let offset = start + buf.len() as u64; |
| 110 | - Ok(( | 148 | + let first_line = if start > 0 { |
| 111 | - String::from_utf8_lossy(&buf).into_owned(), | 149 | + newlines_before(path, start).await? + 1 |
| 150 | + } else { | ||
| 151 | + 1 | ||
| 152 | + }; | ||
| 153 | + Ok(Tail { | ||
| 154 | + text: String::from_utf8_lossy(&buf).into_owned(), | ||
| 112 | truncated, | 155 | truncated, |
| 113 | offset, | 156 | offset, |
| 114 | - )) | 157 | + first_line, |
| 158 | + }) | ||
| 115 | } | 159 | } |
| 116 | 160 | ||
| 117 | /// Follows a log: yields what the file holds, then sends new bytes each time the job changes (its | 161 | /// Follows a log: yields what the file holds, then sends new bytes each time the job changes (its |
| @@ -213,6 +257,8 @@ struct JobView { | |||
| 213 | run_href: String, | 257 | run_href: String, |
| 214 | run_number: i64, | 258 | run_number: i64, |
| 215 | log_href: String, | 259 | log_href: String, |
| 260 | + /// The POST target that runs the job again and the CSRF token, for a writer once it finished. | ||
| 261 | + rerun: Option<(String, String)>, | ||
| 216 | } | 262 | } |
| 217 | 263 | ||
| 218 | /// One artifact row: its link and its size. | 264 | /// One artifact row: its link and its size. |
| @@ -231,6 +277,7 @@ async fn job_body( | |||
| 231 | job: JobView, | 277 | job: JobView, |
| 232 | log: String, | 278 | log: String, |
| 233 | log_offset: String, | 279 | log_offset: String, |
| 280 | + first_line: String, | ||
| 234 | truncated: bool, | 281 | truncated: bool, |
| 235 | artifacts: Vec<ArtifactRow>, | 282 | artifacts: Vec<ArtifactRow>, |
| 236 | live: Option<String>, | 283 | live: Option<String>, |
| @@ -259,6 +306,14 @@ async fn job_body( | |||
| 259 | if !job.message.is_empty() { | 306 | if !job.message.is_empty() { |
| 260 | <p>(job.message.as_str())</p> | 307 | <p>(job.message.as_str())</p> |
| 261 | } | 308 | } |
| 309 | + if let Some((action, csrf)) = job.rerun.as_ref() { | ||
| 310 | + <div class="ci-actions"> | ||
| 311 | + <form method="post" action=(action.as_str()) class="inline-form"> | ||
| 312 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 313 | + <button type="submit">(g::t(lang, K::RerunJob))</button> | ||
| 314 | + </form> | ||
| 315 | + </div> | ||
| 316 | + } | ||
| 262 | </section> | 317 | </section> |
| 263 | <section class="card"> | 318 | <section class="card"> |
| 264 | <h2>(g::t(lang, K::Log))</h2> | 319 | <h2>(g::t(lang, K::Log))</h2> |
| @@ -266,7 +321,17 @@ async fn job_body( | |||
| 266 | if truncated { | 321 | if truncated { |
| 267 | <p class="muted small">(g::t(lang, K::LogTruncated))</p> | 322 | <p class="muted small">(g::t(lang, K::LogTruncated))</p> |
| 268 | } | 323 | } |
| 269 | - <pre class="ci-log" data-live-log="true" data-offset=(log_offset.as_str())>(log.as_str())</pre> | 324 | + <div class="ci-logbar"> |
| 325 | + <input type="search" class="ci-logsearch" data-log-q="true" placeholder=(g::t(lang, K::LogSearch)) aria-label=(g::t(lang, K::LogSearch)) autocomplete="off" spellcheck="false"> | ||
| 326 | + <span class="ci-logcount" data-log-count="true" data-none=(g::t(lang, K::LogNoMatches)) aria-live="polite"></span> | ||
| 327 | + <button type="button" class="ci-mini" data-log-prev="true" aria-label=(g::t(lang, K::LogPrev)) title=(g::t(lang, K::LogPrev))>"\u{2191}"</button> | ||
| 328 | + <button type="button" class="ci-mini" data-log-next="true" aria-label=(g::t(lang, K::LogNext)) title=(g::t(lang, K::LogNext))>"\u{2193}"</button> | ||
| 329 | + <span class="ci-logfold" data-log-fold-box="true" hidden="hidden"> | ||
| 330 | + <button type="button" class="ci-mini" data-log-fold="close">(g::t(lang, K::LogCollapseAll))</button> | ||
| 331 | + <button type="button" class="ci-mini" data-log-fold="open">(g::t(lang, K::LogExpandAll))</button> | ||
| 332 | + </span> | ||
| 333 | + </div> | ||
| 334 | + <pre class="ci-log" data-live-log="true" data-offset=(log_offset.as_str()) data-first=(first_line.as_str())>(log.as_str())</pre> | ||
| 270 | </section> | 335 | </section> |
| 271 | if !artifacts.is_empty() { | 336 | if !artifacts.is_empty() { |
| 272 | <section class="card"> | 337 | <section class="card"> |
| @@ -292,7 +357,12 @@ async fn job_page(cx: &Cx) -> Result<impl View> { | |||
| 292 | let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); | 357 | let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user)); |
| 293 | let state = app_context::<AppState>(cx); | 358 | let state = app_context::<AppState>(cx); |
| 294 | let (job, run) = job_of(state, &ctx, &id).await?; | 359 | let (job, run) = job_of(state, &ctx, &id).await?; |
| 295 | - let (log, truncated, log_offset) = log_tail(&log_path(&state.config.data_dir, &job.id)).await?; | 360 | + let Tail { |
| 361 | + text: log, | ||
| 362 | + truncated, | ||
| 363 | + offset: log_offset, | ||
| 364 | + first_line, | ||
| 365 | + } = log_tail(&log_path(&state.config.data_dir, &job.id)).await?; | ||
| 296 | let artifacts = state | 366 | let artifacts = state |
| 297 | .store | 367 | .store |
| 298 | .list_artifacts(&job.id) | 368 | .list_artifacts(&job.id) |
| @@ -337,12 +407,22 @@ async fn job_page(cx: &Cx) -> Result<impl View> { | |||
| 337 | run_href: run_href(&title, run.number), | 407 | run_href: run_href(&title, run.number), |
| 338 | run_number: run.number, | 408 | run_number: run.number, |
| 339 | log_href: format!("{}/log.txt", job_href(&title, &job.id)), | 409 | log_href: format!("{}/log.txt", job_href(&title, &job.id)), |
| 410 | + rerun: if job.state.is_terminal() && can_write(&ctx) { | ||
| 411 | + ctx.viewer.as_ref().map(|(_, session)| { | ||
| 412 | + ( | ||
| 413 | + format!("{}/rerun", job_href(&title, &job.id)), | ||
| 414 | + session.csrf_token.clone(), | ||
| 415 | + ) | ||
| 416 | + }) | ||
| 417 | + } else { | ||
| 418 | + None | ||
| 419 | + }, | ||
| 340 | }; | 420 | }; |
| 341 | let head = ctx.head(state, "ci").await?; | 421 | let head = ctx.head(state, "ci").await?; |
| 342 | let page_title = format!("{title} \u{b7} CI \u{b7} {}", view.name); | 422 | let page_title = format!("{title} \u{b7} CI \u{b7} {}", view.name); |
| 343 | Ok(view! { | 423 | Ok(view! { |
| 344 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), | 424 | shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), |
| 345 | - job_body(head: head, lang: lang, job: view, log: log, log_offset: log_offset.to_string(), | 425 | + job_body(head: head, lang: lang, job: view, log: log, log_offset: log_offset.to_string(), first_line: first_line.to_string(), |
| 346 | truncated: truncated, artifacts: artifacts, live: live)) | 426 | truncated: truncated, artifacts: artifacts, live: live)) |
| 347 | }) | 427 | }) |
| 348 | } | 428 | } |
crates/forge-web/src/pages/ci_runs.rsmodified+288 -11
| @@ -47,6 +47,7 @@ use crate::views::{alert, enc, human_size, now_unix, relative_time, shell, short | |||
| 47 | path_param!(owner); | 47 | path_param!(owner); |
| 48 | path_param!(repo); | 48 | path_param!(repo); |
| 49 | path_param!(run_number); | 49 | path_param!(run_number); |
| 50 | +path_param!(job_id); | ||
| 50 | 51 | ||
| 51 | /// Runs per list page. | 52 | /// Runs per list page. |
| 52 | const PER_PAGE: u32 = 25; | 53 | const PER_PAGE: u32 = 25; |
| @@ -54,7 +55,7 @@ const PER_PAGE: u32 = 25; | |||
| 54 | const MAX_PAGE: u32 = 1000; | 55 | const MAX_PAGE: u32 = 1000; |
| 55 | 56 | ||
| 56 | /// Notice words (the only text a `?notice=` query can show), their text and whether they are errors. | 57 | /// Notice words (the only text a `?notice=` query can show), their text and whether they are errors. |
| 57 | -const NOTICES: [(&str, K, bool); 8] = [ | 58 | +const NOTICES: [(&str, K, bool); 11] = [ |
| 58 | ("started", K::CiNoticeStarted, false), | 59 | ("started", K::CiNoticeStarted, false), |
| 59 | ("cancelled", K::CiNoticeCancelled, false), | 60 | ("cancelled", K::CiNoticeCancelled, false), |
| 60 | ("approved", K::CiNoticeApproved, false), | 61 | ("approved", K::CiNoticeApproved, false), |
| @@ -63,6 +64,9 @@ const NOTICES: [(&str, K, bool); 8] = [ | |||
| 63 | ("not-waiting", K::CiNoticeNotWaiting, true), | 64 | ("not-waiting", K::CiNoticeNotWaiting, true), |
| 64 | ("no-branch", K::CiNoticeNoBranch, true), | 65 | ("no-branch", K::CiNoticeNoBranch, true), |
| 65 | ("no-manual", K::CiNoticeNoManual, true), | 66 | ("no-manual", K::CiNoticeNoManual, true), |
| 67 | + ("no-failed", K::CiNoticeNoFailed, true), | ||
| 68 | + ("not-done", K::CiNoticeNotDone, true), | ||
| 69 | + ("too-big", K::CiNoticeTooBig, true), | ||
| 66 | ]; | 70 | ]; |
| 67 | 71 | ||
| 68 | #[derive(Deserialize)] | 72 | #[derive(Deserialize)] |
| @@ -85,7 +89,7 @@ fn viewer_user(ctx: &RepoCtx) -> Option<&User> { | |||
| 85 | } | 89 | } |
| 86 | 90 | ||
| 87 | /// Whether the viewer may change CI runs of this repo. Archived repos refuse. | 91 | /// Whether the viewer may change CI runs of this repo. Archived repos refuse. |
| 88 | -fn can_write(ctx: &RepoCtx) -> bool { | 92 | +pub(crate) fn can_write(ctx: &RepoCtx) -> bool { |
| 89 | authorize( | 93 | authorize( |
| 90 | viewer_user(ctx), | 94 | viewer_user(ctx), |
| 91 | &ctx.repo, | 95 | &ctx.repo, |
| @@ -270,7 +274,7 @@ async fn run_of(state: &AppState, ctx: &RepoCtx, number: &str) -> Result<CiRun> | |||
| 270 | 274 | ||
| 271 | /// Wakes the job queue and syncs the commit status of every job whose state changed since `before`. | 275 | /// Wakes the job queue and syncs the commit status of every job whose state changed since `before`. |
| 272 | /// A job missing from `before` (a fresh run) counts as changed. | 276 | /// A job missing from `before` (a fresh run) counts as changed. |
| 273 | -async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Result<()> { | 277 | +pub(crate) async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> Result<()> { |
| 274 | state.ci_waker.notify_waiters(); | 278 | state.ci_waker.notify_waiters(); |
| 275 | let Some(run) = state.store.run_by_id(run_id).await? else { | 279 | let Some(run) = state.store.run_by_id(run_id).await? else { |
| 276 | return Ok(()); | 280 | return Ok(()); |
| @@ -339,7 +343,7 @@ struct JobLine { | |||
| 339 | href: String, | 343 | href: String, |
| 340 | name: String, | 344 | name: String, |
| 341 | dot: String, | 345 | dot: String, |
| 342 | - /// The image and the artifacts with their sizes, joined with a middle dot. | 346 | + /// The short image name. |
| 343 | detail: String, | 347 | detail: String, |
| 344 | runner: String, | 348 | runner: String, |
| 345 | duration: String, | 349 | duration: String, |
| @@ -353,6 +357,16 @@ struct JobLine { | |||
| 353 | tail: String, | 357 | tail: String, |
| 354 | /// Whether the row starts with its tail open. | 358 | /// Whether the row starts with its tail open. |
| 355 | expanded: bool, | 359 | expanded: bool, |
| 360 | + /// The POST target that runs this job again. Set for a writer, once the job has finished. | ||
| 361 | + rerun: Option<String>, | ||
| 362 | +} | ||
| 363 | + | ||
| 364 | +/// One artifact of the run: its download link, the job that made it, its name and size. | ||
| 365 | +struct ArtifactLine { | ||
| 366 | + href: String, | ||
| 367 | + job: String, | ||
| 368 | + name: String, | ||
| 369 | + size: String, | ||
| 356 | } | 370 | } |
| 357 | 371 | ||
| 358 | /// The right column: the selected run, its timeline, its jobs and the log tail. | 372 | /// The right column: the selected run, its timeline, its jobs and the log tail. |
| @@ -374,6 +388,13 @@ struct RunDetail { | |||
| 374 | action_base: String, | 388 | action_base: String, |
| 375 | can_approve: bool, | 389 | can_approve: bool, |
| 376 | can_cancel: bool, | 390 | can_cancel: bool, |
| 391 | + /// A finished run with a failed, errored or cancelled job, for a writer. | ||
| 392 | + can_rerun_failed: bool, | ||
| 393 | + /// The config keys this forge ignored when it made the run. | ||
| 394 | + warnings: Vec<String>, | ||
| 395 | + artifacts: Vec<ArtifactLine>, | ||
| 396 | + /// The zip of every artifact of the run. | ||
| 397 | + zip_href: Option<String>, | ||
| 377 | writer_csrf: Option<String>, | 398 | writer_csrf: Option<String>, |
| 378 | gantt: Option<Gantt>, | 399 | gantt: Option<Gantt>, |
| 379 | jobs: Vec<JobLine>, | 400 | jobs: Vec<JobLine>, |
| @@ -1399,15 +1420,21 @@ async fn run_detail( | |||
| 1399 | let jobs = timings_of(state, &run.id, runners, lang).await?; | 1420 | let jobs = timings_of(state, &run.id, runners, lang).await?; |
| 1400 | let gantt = | 1421 | let gantt = |
| 1401 | (!jobs.is_empty()).then(|| gantt(&jobs, origin_of(run, now), run_end(run, now), now, lang)); | 1422 | (!jobs.is_empty()).then(|| gantt(&jobs, origin_of(run, now), run_end(run, now), now, lang)); |
| 1423 | + let writer = header.writer_csrf.is_some(); | ||
| 1402 | let mut lines = Vec::with_capacity(jobs.len()); | 1424 | let mut lines = Vec::with_capacity(jobs.len()); |
| 1425 | + let mut artifacts = Vec::new(); | ||
| 1403 | for job in jobs.iter() { | 1426 | for job in jobs.iter() { |
| 1404 | - let mut parts = Vec::new(); | ||
| 1405 | - if !job.image.is_empty() { | ||
| 1406 | - parts.push(job.image.clone()); | ||
| 1407 | - } | ||
| 1408 | for artifact in state.store.list_artifacts(&job.id).await? { | 1427 | for artifact in state.store.list_artifacts(&job.id).await? { |
| 1409 | - let size = human_size(lang, u64::try_from(artifact.size).unwrap_or(0)); | 1428 | + artifacts.push(ArtifactLine { |
| 1410 | - parts.push(format!("{} {size}", artifact.name)); | 1429 | + href: format!( |
| 1430 | + "{}/artifacts/{}", | ||
| 1431 | + job_href(title, &job.id), | ||
| 1432 | + enc(&artifact.name) | ||
| 1433 | + ), | ||
| 1434 | + job: job.name.clone(), | ||
| 1435 | + size: human_size(lang, u64::try_from(artifact.size).unwrap_or(0)), | ||
| 1436 | + name: artifact.name, | ||
| 1437 | + }); | ||
| 1411 | } | 1438 | } |
| 1412 | let tail = log_last_lines(&log_path(&state.config.data_dir, &job.id)).await; | 1439 | let tail = log_last_lines(&log_path(&state.config.data_dir, &job.id)).await; |
| 1413 | let preview = match last_line(&tail) { | 1440 | let preview = match last_line(&tail) { |
| @@ -1424,7 +1451,9 @@ async fn run_detail( | |||
| 1424 | href: job_href(title, &job.id), | 1451 | href: job_href(title, &job.id), |
| 1425 | name: job.name.clone(), | 1452 | name: job.name.clone(), |
| 1426 | dot: format!("ci-dot ci-{}", job.state.as_str()), | 1453 | dot: format!("ci-dot ci-{}", job.state.as_str()), |
| 1427 | - detail: parts.join(" \u{b7} "), | 1454 | + detail: job.image.clone(), |
| 1455 | + rerun: (writer && job.state.is_terminal()) | ||
| 1456 | + .then(|| format!("{}/rerun", job_href(title, &job.id))), | ||
| 1428 | runner: job.runner.clone(), | 1457 | runner: job.runner.clone(), |
| 1429 | duration: job.duration.clone(), | 1458 | duration: job.duration.clone(), |
| 1430 | since: (job.finished.is_none() && job.state == JobState::Running) | 1459 | since: (job.finished.is_none() && job.state == JobState::Running) |
| @@ -1432,6 +1461,17 @@ async fn run_detail( | |||
| 1432 | .flatten(), | 1461 | .flatten(), |
| 1433 | }); | 1462 | }); |
| 1434 | } | 1463 | } |
| 1464 | + let can_rerun_failed = writer | ||
| 1465 | + && run_finished(&run.state) | ||
| 1466 | + && jobs.iter().any(|job| { | ||
| 1467 | + matches!( | ||
| 1468 | + job.state, | ||
| 1469 | + JobState::Failure | JobState::Error | JobState::Cancelled | ||
| 1470 | + ) | ||
| 1471 | + }); | ||
| 1472 | + let zip_href = | ||
| 1473 | + (!artifacts.is_empty()).then(|| format!("{}/artifacts.zip", run_href(title, run.number))); | ||
| 1474 | + let warnings = state.store.run_warnings(&run.id).await?; | ||
| 1435 | Ok(RunDetail { | 1475 | Ok(RunDetail { |
| 1436 | number: run.number, | 1476 | number: run.number, |
| 1437 | title: header.title, | 1477 | title: header.title, |
| @@ -1455,6 +1495,10 @@ async fn run_detail( | |||
| 1455 | action_base: run_href(title, run.number), | 1495 | action_base: run_href(title, run.number), |
| 1456 | can_approve: header.writer_csrf.is_some() && run.state == RunState::WaitingApproval, | 1496 | can_approve: header.writer_csrf.is_some() && run.state == RunState::WaitingApproval, |
| 1457 | can_cancel: header.writer_csrf.is_some() && !run_finished(&run.state), | 1497 | can_cancel: header.writer_csrf.is_some() && !run_finished(&run.state), |
| 1498 | + can_rerun_failed, | ||
| 1499 | + warnings, | ||
| 1500 | + artifacts, | ||
| 1501 | + zip_href, | ||
| 1458 | writer_csrf: header.writer_csrf, | 1502 | writer_csrf: header.writer_csrf, |
| 1459 | gantt, | 1503 | gantt, |
| 1460 | jobs: lines, | 1504 | jobs: lines, |
| @@ -1585,6 +1629,9 @@ async fn runs_body( | |||
| 1585 | if run.can_cancel { | 1629 | if run.can_cancel { |
| 1586 | action_button(action: format!("{}/cancel", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::Cancel)) | 1630 | action_button(action: format!("{}/cancel", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::Cancel)) |
| 1587 | } | 1631 | } |
| 1632 | + if run.can_rerun_failed { | ||
| 1633 | + action_button(action: format!("{}/rerun-failed", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::RerunFailed)) | ||
| 1634 | + } | ||
| 1588 | action_button(action: format!("{}/rerun", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::Rerun)) | 1635 | action_button(action: format!("{}/rerun", run.action_base), csrf: csrf.clone(), label: g::t(lang, K::Rerun)) |
| 1589 | </div> | 1636 | </div> |
| 1590 | } | 1637 | } |
| @@ -1606,6 +1653,17 @@ async fn runs_body( | |||
| 1606 | if let Some(message) = run.config_error.as_ref() { | 1653 | if let Some(message) = run.config_error.as_ref() { |
| 1607 | <pre class="ci-config-error">(message.as_str())</pre> | 1654 | <pre class="ci-config-error">(message.as_str())</pre> |
| 1608 | } | 1655 | } |
| 1656 | + if !run.warnings.is_empty() { | ||
| 1657 | + <section class="ci-warnings" role="status"> | ||
| 1658 | + <p class="ci-warnings-title">(g::t(lang, K::ConfigWarnings))</p> | ||
| 1659 | + <p class="muted small">(g::t(lang, K::ConfigWarningsHint))</p> | ||
| 1660 | + <ul> | ||
| 1661 | + for warning in run.warnings.iter() { | ||
| 1662 | + <li><code>(warning.as_str())</code></li> | ||
| 1663 | + } | ||
| 1664 | + </ul> | ||
| 1665 | + </section> | ||
| 1666 | + } | ||
| 1609 | if let Some(g) = run.gantt.as_ref() { | 1667 | if let Some(g) = run.gantt.as_ref() { |
| 1610 | <div class="ci-gantt-scroll"> | 1668 | <div class="ci-gantt-scroll"> |
| 1611 | <svg class="ci-gantt" viewBox=(g.view_box.as_str()) role="img" aria-label=(g::t(lang, K::Timeline)) data-origin=(g.origin.as_str()) data-len=(g.len.as_str()) data-live-gantt=(g.live.then_some("true"))> | 1669 | <svg class="ci-gantt" viewBox=(g.view_box.as_str()) role="img" aria-label=(g::t(lang, K::Timeline)) data-origin=(g.origin.as_str()) data-len=(g.len.as_str()) data-live-gantt=(g.live.then_some("true"))> |
| @@ -1650,6 +1708,7 @@ async fn runs_body( | |||
| 1650 | <ul class="ci-job-list"> | 1708 | <ul class="ci-job-list"> |
| 1651 | for job in run.jobs.iter() { | 1709 | for job in run.jobs.iter() { |
| 1652 | <li data-job-row=(job.id.as_str()) data-open=(if job.expanded { "true" } else { "false" })> | 1710 | <li data-job-row=(job.id.as_str()) data-open=(if job.expanded { "true" } else { "false" })> |
| 1711 | + <div class="ci-job-item"> | ||
| 1653 | <a class="ci-job-line" href=(job.href.as_str())> | 1712 | <a class="ci-job-line" href=(job.href.as_str())> |
| 1654 | <span class=(job.dot.as_str())></span> | 1713 | <span class=(job.dot.as_str())></span> |
| 1655 | <span class="ci-job-main"> | 1714 | <span class="ci-job-main"> |
| @@ -1662,6 +1721,13 @@ async fn runs_body( | |||
| 1662 | <span class="ci-job-dur" data-since=(job.since.as_deref())>(job.duration.as_str())</span> | 1721 | <span class="ci-job-dur" data-since=(job.since.as_deref())>(job.duration.as_str())</span> |
| 1663 | <span class="ci-chev" aria-hidden="true"></span> | 1722 | <span class="ci-chev" aria-hidden="true"></span> |
| 1664 | </a> | 1723 | </a> |
| 1724 | + if let (Some(action), Some(csrf)) = (job.rerun.as_ref(), run.writer_csrf.as_ref()) { | ||
| 1725 | + <form method="post" action=(action.as_str()) class="inline-form ci-job-rerun"> | ||
| 1726 | + <input type="hidden" name="csrf" value=(csrf.as_str())> | ||
| 1727 | + <button type="submit" class="ci-mini">(g::t(lang, K::Rerun))</button> | ||
| 1728 | + </form> | ||
| 1729 | + } | ||
| 1730 | + </div> | ||
| 1665 | if !job.tail.is_empty() { | 1731 | if !job.tail.is_empty() { |
| 1666 | <button type="button" class="ci-job-last" data-job-toggle="true" aria-expanded=(if job.expanded { "true" } else { "false" }) title=(job.preview.as_str())> | 1732 | <button type="button" class="ci-job-last" data-job-toggle="true" aria-expanded=(if job.expanded { "true" } else { "false" }) title=(job.preview.as_str())> |
| 1667 | <span class="ci-job-caret" aria-hidden="true"></span> | 1733 | <span class="ci-job-caret" aria-hidden="true"></span> |
| @@ -1680,6 +1746,23 @@ async fn runs_body( | |||
| 1680 | } | 1746 | } |
| 1681 | </ul> | 1747 | </ul> |
| 1682 | } | 1748 | } |
| 1749 | + if !run.artifacts.is_empty() { | ||
| 1750 | + <div class="ci-art-head"> | ||
| 1751 | + <h4 class="ci-art-title">(g::t(lang, K::Artifacts))</h4> | ||
| 1752 | + if let Some(href) = run.zip_href.as_ref() { | ||
| 1753 | + <a class="button ci-mini" href=(href.as_str()) download="">(g::t(lang, K::DownloadAll))</a> | ||
| 1754 | + } | ||
| 1755 | + </div> | ||
| 1756 | + <ul class="ci-art-list"> | ||
| 1757 | + for artifact in run.artifacts.iter() { | ||
| 1758 | + <li> | ||
| 1759 | + <span class="ci-art-name">(artifact.name.as_str())</span> | ||
| 1760 | + <span class="muted small">(artifact.job.as_str()) " \u{b7} " (artifact.size.as_str())</span> | ||
| 1761 | + <a class="ci-art-dl" href=(artifact.href.as_str()) download="">(g::t(lang, K::Download))</a> | ||
| 1762 | + </li> | ||
| 1763 | + } | ||
| 1764 | + </ul> | ||
| 1765 | + } | ||
| 1683 | } else { | 1766 | } else { |
| 1684 | <div class="ci-empty"> | 1767 | <div class="ci-empty"> |
| 1685 | <p>(g::t(lang, K::NoRunsYet))</p> | 1768 | <p>(g::t(lang, K::NoRunsYet))</p> |
| @@ -1971,10 +2054,204 @@ async fn run_rerun(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | |||
| 1971 | )) | 2054 | )) |
| 1972 | } | 2055 | } |
| 1973 | 2056 | ||
| 2057 | +/// Starts a new run with only the failed, errored and cancelled jobs of a finished run, plus the | ||
| 2058 | +/// jobs that depend on them. The specs are the originals. | ||
| 2059 | +#[route(POST "/{owner}/{repo}/ci/runs/{run_number}/rerun-failed")] | ||
| 2060 | +async fn run_rerun_failed(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | ||
| 2061 | + let owner = path_param::<Owner>(cx); | ||
| 2062 | + let name = path_param::<Repo>(cx); | ||
| 2063 | + let number = path_param::<RunNumber>(cx).to_owned(); | ||
| 2064 | + let ctx = load_repo(cx, owner, name).await?; | ||
| 2065 | + let (user, _) = require_csrf(cx, &form.csrf).await?; | ||
| 2066 | + require_write(&ctx)?; | ||
| 2067 | + let state = app_context::<AppState>(cx); | ||
| 2068 | + let run = run_of(state, &ctx, &number).await?; | ||
| 2069 | + let href = run_href(&title_of(&ctx), run.number); | ||
| 2070 | + match state.store.rerun_failed(&run.id, &user.id).await { | ||
| 2071 | + Ok(new_run) => { | ||
| 2072 | + after_change(state, &new_run.id, &[]).await?; | ||
| 2073 | + Ok(notice_redirect( | ||
| 2074 | + &run_href(&title_of(&ctx), new_run.number), | ||
| 2075 | + "rerun", | ||
| 2076 | + )) | ||
| 2077 | + } | ||
| 2078 | + Err(forge_core::Error::Conflict(_)) => { | ||
| 2079 | + let word = if run_finished(&run.state) { | ||
| 2080 | + "no-failed" | ||
| 2081 | + } else { | ||
| 2082 | + "not-done" | ||
| 2083 | + }; | ||
| 2084 | + Ok(notice_redirect(&href, word)) | ||
| 2085 | + } | ||
| 2086 | + Err(e) => Err(e.into()), | ||
| 2087 | + } | ||
| 2088 | +} | ||
| 2089 | + | ||
| 2090 | +/// Starts a new run with one finished job and the jobs that depend on it. The specs are the | ||
| 2091 | +/// originals. | ||
| 2092 | +#[route(POST "/{owner}/{repo}/ci/jobs/{job_id}/rerun")] | ||
| 2093 | +async fn job_rerun(cx: &Cx, Form(form): Form<CsrfForm>) -> Result<SeeOther> { | ||
| 2094 | + let owner = path_param::<Owner>(cx); | ||
| 2095 | + let name = path_param::<Repo>(cx); | ||
| 2096 | + let id = path_param::<JobId>(cx).to_owned(); | ||
| 2097 | + let ctx = load_repo(cx, owner, name).await?; | ||
| 2098 | + let (user, _) = require_csrf(cx, &form.csrf).await?; | ||
| 2099 | + require_write(&ctx)?; | ||
| 2100 | + let state = app_context::<AppState>(cx); | ||
| 2101 | + let Some(job) = state.store.job_by_id(&id).await? else { | ||
| 2102 | + return Err(not_found().into()); | ||
| 2103 | + }; | ||
| 2104 | + let Some(run) = state.store.run_by_id(&job.run_id).await? else { | ||
| 2105 | + return Err(not_found().into()); | ||
| 2106 | + }; | ||
| 2107 | + if run.repo_id != ctx.repo.id { | ||
| 2108 | + return Err(not_found().into()); | ||
| 2109 | + } | ||
| 2110 | + match state.store.rerun_job(&run.id, &job.id, &user.id).await { | ||
| 2111 | + Ok(new_run) => { | ||
| 2112 | + after_change(state, &new_run.id, &[]).await?; | ||
| 2113 | + Ok(notice_redirect( | ||
| 2114 | + &run_href(&title_of(&ctx), new_run.number), | ||
| 2115 | + "rerun", | ||
| 2116 | + )) | ||
| 2117 | + } | ||
| 2118 | + Err(forge_core::Error::Conflict(_)) => Ok(notice_redirect( | ||
| 2119 | + &run_href(&title_of(&ctx), run.number), | ||
| 2120 | + "not-done", | ||
| 2121 | + )), | ||
| 2122 | + Err(e) => Err(e.into()), | ||
| 2123 | + } | ||
| 2124 | +} | ||
| 2125 | + | ||
| 2126 | +/// Most bytes of artifacts the zip download builds in memory. | ||
| 2127 | +const MAX_ZIP_BYTES: i64 = 256 * 1024 * 1024; | ||
| 2128 | + | ||
| 2129 | +/// A zip of `files` (path in the zip, bytes), deflated. Paths use `/`. | ||
| 2130 | +fn build_zip(files: Vec<(String, Vec<u8>)>) -> std::io::Result<Vec<u8>> { | ||
| 2131 | + use std::io::{Cursor, Write}; | ||
| 2132 | + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); | ||
| 2133 | + let options = zip::write::SimpleFileOptions::default() | ||
| 2134 | + .compression_method(zip::CompressionMethod::Deflated); | ||
| 2135 | + for (path, bytes) in files { | ||
| 2136 | + zip.start_file(path, options) | ||
| 2137 | + .map_err(std::io::Error::other)?; | ||
| 2138 | + zip.write_all(&bytes)?; | ||
| 2139 | + } | ||
| 2140 | + Ok(zip.finish().map_err(std::io::Error::other)?.into_inner()) | ||
| 2141 | +} | ||
| 2142 | + | ||
| 2143 | +/// The path of an artifact inside the run's zip: `<job>/<name>`, with path separators in either | ||
| 2144 | +/// part made harmless. | ||
| 2145 | +fn zip_path(job: &str, artifact: &str) -> String { | ||
| 2146 | + let clean = |part: &str| part.replace(['/', '\\'], "_"); | ||
| 2147 | + format!("{}/{}", clean(job), clean(artifact)) | ||
| 2148 | +} | ||
| 2149 | + | ||
| 2150 | +/// Every artifact of a run as one zip, a folder per job. Readers of the repo may download it. | ||
| 2151 | +#[route(GET "/{owner}/{repo}/ci/runs/{run_number}/artifacts.zip")] | ||
| 2152 | +async fn run_artifacts_zip(cx: &Cx) -> Result<Response> { | ||
| 2153 | + use futures_util::TryStreamExt; | ||
| 2154 | + let owner = path_param::<Owner>(cx); | ||
| 2155 | + let name = path_param::<Repo>(cx); | ||
| 2156 | + let number = path_param::<RunNumber>(cx).to_owned(); | ||
| 2157 | + let ctx = load_repo(cx, owner, name).await?; | ||
| 2158 | + let state = app_context::<AppState>(cx); | ||
| 2159 | + let run = run_of(state, &ctx, &number).await?; | ||
| 2160 | + let href = run_href(&title_of(&ctx), run.number); | ||
| 2161 | + let mut entries = Vec::new(); | ||
| 2162 | + let mut total = 0i64; | ||
| 2163 | + for job in state.store.jobs_for_run(&run.id).await? { | ||
| 2164 | + for artifact in state.store.list_artifacts(&job.id).await? { | ||
| 2165 | + total = total.saturating_add(artifact.size); | ||
| 2166 | + entries.push((zip_path(&job.name, &artifact.name), artifact)); | ||
| 2167 | + } | ||
| 2168 | + } | ||
| 2169 | + if entries.is_empty() { | ||
| 2170 | + return Err(not_found().into()); | ||
| 2171 | + } | ||
| 2172 | + if total > MAX_ZIP_BYTES { | ||
| 2173 | + return notice_redirect(&href, "too-big").into_response(cx); | ||
| 2174 | + } | ||
| 2175 | + let mut files = Vec::with_capacity(entries.len()); | ||
| 2176 | + for (path, artifact) in entries { | ||
| 2177 | + let Some(read) = state | ||
| 2178 | + .blobs | ||
| 2179 | + .read(&crate::ci::artifact_key(&artifact.id)) | ||
| 2180 | + .await? | ||
| 2181 | + else { | ||
| 2182 | + tracing::error!(artifact_id = %artifact.id, "ci: artifact row without a blob"); | ||
| 2183 | + continue; | ||
| 2184 | + }; | ||
| 2185 | + let chunks: Vec<bytes::Bytes> = read | ||
| 2186 | + .stream | ||
| 2187 | + .try_collect() | ||
| 2188 | + .await | ||
| 2189 | + .map_err(forge_core::Error::Io)?; | ||
| 2190 | + files.push((path, chunks.concat())); | ||
| 2191 | + } | ||
| 2192 | + let zipped = tokio::task::spawn_blocking(move || build_zip(files)) | ||
| 2193 | + .await | ||
| 2194 | + .map_err(|e| forge_core::Error::Io(std::io::Error::other(e)))? | ||
| 2195 | + .map_err(forge_core::Error::Io)?; | ||
| 2196 | + let mut res = Response::new(topcoat::router::Body::from(zipped)); | ||
| 2197 | + let headers = res.headers_mut(); | ||
| 2198 | + headers.insert( | ||
| 2199 | + http::header::CONTENT_TYPE, | ||
| 2200 | + HeaderValue::from_static("application/zip"), | ||
| 2201 | + ); | ||
| 2202 | + let file = format!("{}-run-{}-artifacts.zip", ctx.repo.name, run.number); | ||
| 2203 | + if let Ok(value) = HeaderValue::from_str(&format!( | ||
| 2204 | + "attachment; filename=\"{}\"", | ||
| 2205 | + file.chars() | ||
| 2206 | + .map(|c| if c.is_ascii_graphic() && c != '"' && c != '\\' { | ||
| 2207 | + c | ||
| 2208 | + } else { | ||
| 2209 | + '_' | ||
| 2210 | + }) | ||
| 2211 | + .collect::<String>() | ||
| 2212 | + )) { | ||
| 2213 | + headers.insert(http::header::CONTENT_DISPOSITION, value); | ||
| 2214 | + } | ||
| 2215 | + headers.insert( | ||
| 2216 | + http::header::HeaderName::from_static("x-content-type-options"), | ||
| 2217 | + HeaderValue::from_static("nosniff"), | ||
| 2218 | + ); | ||
| 2219 | + headers.insert( | ||
| 2220 | + http::header::HeaderName::from_static("cache-control"), | ||
| 2221 | + HeaderValue::from_static("private, no-cache"), | ||
| 2222 | + ); | ||
| 2223 | + Ok(res) | ||
| 2224 | +} | ||
| 2225 | + | ||
| 1974 | #[cfg(test)] | 2226 | #[cfg(test)] |
| 1975 | mod tests { | 2227 | mod tests { |
| 1976 | use super::*; | 2228 | use super::*; |
| 1977 | 2229 | ||
| 2230 | + #[test] | ||
| 2231 | + fn zip_paths_keep_one_folder_per_job() { | ||
| 2232 | + assert_eq!(zip_path("build", "app.tar"), "build/app.tar"); | ||
| 2233 | + assert_eq!(zip_path("a/b", "..\\x"), "a_b/.._x"); | ||
| 2234 | + } | ||
| 2235 | + | ||
| 2236 | + #[test] | ||
| 2237 | + fn the_zip_holds_each_file_under_its_path() { | ||
| 2238 | + use std::io::{Cursor, Read}; | ||
| 2239 | + let bytes = build_zip(vec![ | ||
| 2240 | + ("build/a.txt".into(), b"hello".to_vec()), | ||
| 2241 | + ("test/b.txt".into(), b"world".to_vec()), | ||
| 2242 | + ]) | ||
| 2243 | + .unwrap(); | ||
| 2244 | + let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); | ||
| 2245 | + assert_eq!(archive.len(), 2); | ||
| 2246 | + let mut text = String::new(); | ||
| 2247 | + archive | ||
| 2248 | + .by_name("test/b.txt") | ||
| 2249 | + .unwrap() | ||
| 2250 | + .read_to_string(&mut text) | ||
| 2251 | + .unwrap(); | ||
| 2252 | + assert_eq!(text, "world"); | ||
| 2253 | + } | ||
| 2254 | + | ||
| 1978 | /// A job timing with the given times, on runner `vps-1`. | 2255 | /// A job timing with the given times, on runner `vps-1`. |
| 1979 | fn timing( | 2256 | fn timing( |
| 1980 | name: &str, | 2257 | name: &str, |
crates/forge-web/src/pages/ci_tests.rsmodified+245 -0
| @@ -1394,6 +1394,251 @@ async fn running_runs_carry_ticker_attributes_and_finished_ones_do_not() { | |||
| 1394 | ); | 1394 | ); |
| 1395 | } | 1395 | } |
| 1396 | 1396 | ||
| 1397 | +#[tokio::test] | ||
| 1398 | +async fn rerun_failed_and_rerun_job_start_partial_runs() { | ||
| 1399 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 1400 | + let fx = fixture(dir.path()).await; | ||
| 1401 | + let run = run_with(&fx, &["build", "lint"], false).await; | ||
| 1402 | + let run_url = format!("{RUN_BASE}/runs/{}", run.number); | ||
| 1403 | + let writer = cookie_for("bob-token"); | ||
| 1404 | + | ||
| 1405 | + // A live run offers neither control and refuses the request. | ||
| 1406 | + let page = get(&fx.app, &run_url, Some(&writer)).await.text(); | ||
| 1407 | + assert!(!page.contains("Re-run failed jobs")); | ||
| 1408 | + let early = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await; | ||
| 1409 | + assert!( | ||
| 1410 | + early | ||
| 1411 | + .location() | ||
| 1412 | + .unwrap_or_default() | ||
| 1413 | + .ends_with("?notice=not-done") | ||
| 1414 | + ); | ||
| 1415 | + | ||
| 1416 | + let cancelled = post(&fx.app, &format!("{run_url}/cancel"), &writer, &[]).await; | ||
| 1417 | + assert_eq!(cancelled.status, 303); | ||
| 1418 | + let page = get(&fx.app, &run_url, Some(&writer)).await.text(); | ||
| 1419 | + assert!(page.contains("Re-run failed jobs"), "cancelled jobs count"); | ||
| 1420 | + let reader = get(&fx.app, &run_url, Some(&cookie_for("dave-token"))).await; | ||
| 1421 | + assert!(!reader.text().contains("Re-run failed jobs")); | ||
| 1422 | + let refused = post( | ||
| 1423 | + &fx.app, | ||
| 1424 | + &format!("{run_url}/rerun-failed"), | ||
| 1425 | + &cookie_for("dave-token"), | ||
| 1426 | + &[], | ||
| 1427 | + ) | ||
| 1428 | + .await; | ||
| 1429 | + assert_eq!(refused.status, 403); | ||
| 1430 | + | ||
| 1431 | + let again = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await; | ||
| 1432 | + assert_eq!( | ||
| 1433 | + again.location().as_deref(), | ||
| 1434 | + Some("/tahinli/proj/ci/runs/2?notice=rerun") | ||
| 1435 | + ); | ||
| 1436 | + let second = fx | ||
| 1437 | + .store | ||
| 1438 | + .run_by_number(&fx.repo.id, 2) | ||
| 1439 | + .await | ||
| 1440 | + .unwrap() | ||
| 1441 | + .unwrap(); | ||
| 1442 | + assert_eq!(fx.store.jobs_for_run(&second.id).await.unwrap().len(), 2); | ||
| 1443 | + | ||
| 1444 | + // One job: it must have finished, and the request needs Write. | ||
| 1445 | + let job = job_of(&fx, &run).await; | ||
| 1446 | + let single = post( | ||
| 1447 | + &fx.app, | ||
| 1448 | + &format!("/tahinli/proj/ci/jobs/{}/rerun", job.id), | ||
| 1449 | + &writer, | ||
| 1450 | + &[], | ||
| 1451 | + ) | ||
| 1452 | + .await; | ||
| 1453 | + assert_eq!( | ||
| 1454 | + single.location().as_deref(), | ||
| 1455 | + Some("/tahinli/proj/ci/runs/3?notice=rerun") | ||
| 1456 | + ); | ||
| 1457 | + let third = fx | ||
| 1458 | + .store | ||
| 1459 | + .run_by_number(&fx.repo.id, 3) | ||
| 1460 | + .await | ||
| 1461 | + .unwrap() | ||
| 1462 | + .unwrap(); | ||
| 1463 | + assert_eq!(fx.store.jobs_for_run(&third.id).await.unwrap().len(), 1); | ||
| 1464 | + let live = job_of(&fx, &third).await; | ||
| 1465 | + let early = post( | ||
| 1466 | + &fx.app, | ||
| 1467 | + &format!("/tahinli/proj/ci/jobs/{}/rerun", live.id), | ||
| 1468 | + &writer, | ||
| 1469 | + &[], | ||
| 1470 | + ) | ||
| 1471 | + .await; | ||
| 1472 | + assert!( | ||
| 1473 | + early | ||
| 1474 | + .location() | ||
| 1475 | + .unwrap_or_default() | ||
| 1476 | + .ends_with("?notice=not-done") | ||
| 1477 | + ); | ||
| 1478 | + let refused = post( | ||
| 1479 | + &fx.app, | ||
| 1480 | + &format!("/tahinli/proj/ci/jobs/{}/rerun", job.id), | ||
| 1481 | + &cookie_for("dave-token"), | ||
| 1482 | + &[], | ||
| 1483 | + ) | ||
| 1484 | + .await; | ||
| 1485 | + assert_eq!(refused.status, 403); | ||
| 1486 | + let job_page = get( | ||
| 1487 | + &fx.app, | ||
| 1488 | + &format!("/tahinli/proj/ci/jobs/{}", job.id), | ||
| 1489 | + Some(&writer), | ||
| 1490 | + ) | ||
| 1491 | + .await | ||
| 1492 | + .text(); | ||
| 1493 | + assert!(job_page.contains("Re-run this job")); | ||
| 1494 | +} | ||
| 1495 | + | ||
| 1496 | +#[tokio::test] | ||
| 1497 | +async fn a_run_with_no_failed_jobs_has_nothing_to_rerun() { | ||
| 1498 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 1499 | + let fx = fixture(dir.path()).await; | ||
| 1500 | + let run = run_with(&fx, &["build"], false).await; | ||
| 1501 | + finish_job(&fx).await; | ||
| 1502 | + let run_url = format!("{RUN_BASE}/runs/{}", run.number); | ||
| 1503 | + let writer = cookie_for("bob-token"); | ||
| 1504 | + let page = get(&fx.app, &run_url, Some(&writer)).await.text(); | ||
| 1505 | + assert!(!page.contains("Re-run failed jobs")); | ||
| 1506 | + let none = post(&fx.app, &format!("{run_url}/rerun-failed"), &writer, &[]).await; | ||
| 1507 | + assert!( | ||
| 1508 | + none.location() | ||
| 1509 | + .unwrap_or_default() | ||
| 1510 | + .ends_with("?notice=no-failed") | ||
| 1511 | + ); | ||
| 1512 | +} | ||
| 1513 | + | ||
| 1514 | +#[tokio::test] | ||
| 1515 | +async fn run_artifacts_list_and_zip() { | ||
| 1516 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 1517 | + let fx = fixture(dir.path()).await; | ||
| 1518 | + let run = run_with(&fx, &["build", "test"], false).await; | ||
| 1519 | + let jobs = fx.store.jobs_for_run(&run.id).await.unwrap(); | ||
| 1520 | + for (job, name, payload) in [ | ||
| 1521 | + (&jobs[0], "report.txt", &b"alpha"[..]), | ||
| 1522 | + (&jobs[1], "out.bin", &b"beta"[..]), | ||
| 1523 | + ] { | ||
| 1524 | + let artifact = fx | ||
| 1525 | + .store | ||
| 1526 | + .add_artifact(&job.id, name, payload.len() as i64, SHA) | ||
| 1527 | + .await | ||
| 1528 | + .expect("artifact row"); | ||
| 1529 | + let mut writer = fx | ||
| 1530 | + .blobs | ||
| 1531 | + .begin(&artifact_key(&artifact.id), 1024) | ||
| 1532 | + .await | ||
| 1533 | + .expect("begin"); | ||
| 1534 | + writer.push(payload).await.expect("push"); | ||
| 1535 | + writer.finish().await.expect("finish"); | ||
| 1536 | + } | ||
| 1537 | + let reader = cookie_for("dave-token"); | ||
| 1538 | + let run_url = format!("{RUN_BASE}/runs/{}", run.number); | ||
| 1539 | + let page = get(&fx.app, &run_url, Some(&reader)).await.text(); | ||
| 1540 | + assert!(page.contains("Download all (.zip)")); | ||
| 1541 | + assert!(page.contains("artifacts.zip")); | ||
| 1542 | + assert!(page.contains("report.txt") && page.contains("out.bin")); | ||
| 1543 | + | ||
| 1544 | + let res = get(&fx.app, &format!("{run_url}/artifacts.zip"), Some(&reader)).await; | ||
| 1545 | + assert_eq!(res.status, 200); | ||
| 1546 | + assert_eq!( | ||
| 1547 | + res.headers | ||
| 1548 | + .get("content-type") | ||
| 1549 | + .and_then(|v| v.to_str().ok()), | ||
| 1550 | + Some("application/zip") | ||
| 1551 | + ); | ||
| 1552 | + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(res.body.clone())).expect("zip"); | ||
| 1553 | + assert_eq!(archive.len(), 2); | ||
| 1554 | + let mut text = String::new(); | ||
| 1555 | + std::io::Read::read_to_string( | ||
| 1556 | + &mut archive.by_name("build/report.txt").expect("entry"), | ||
| 1557 | + &mut text, | ||
| 1558 | + ) | ||
| 1559 | + .expect("read"); | ||
| 1560 | + assert_eq!(text, "alpha"); | ||
| 1561 | + | ||
| 1562 | + let outsider = get( | ||
| 1563 | + &fx.app, | ||
| 1564 | + &format!("{run_url}/artifacts.zip"), | ||
| 1565 | + Some(&cookie_for("carol-token")), | ||
| 1566 | + ) | ||
| 1567 | + .await; | ||
| 1568 | + assert_eq!(outsider.status, 404, "a private repo stays private"); | ||
| 1569 | + let empty = run_with(&fx, &["lint"], false).await; | ||
| 1570 | + let none = get( | ||
| 1571 | + &fx.app, | ||
| 1572 | + &format!("{RUN_BASE}/runs/{}/artifacts.zip", empty.number), | ||
| 1573 | + Some(&reader), | ||
| 1574 | + ) | ||
| 1575 | + .await; | ||
| 1576 | + assert_eq!(none.status, 404); | ||
| 1577 | +} | ||
| 1578 | + | ||
| 1579 | +#[tokio::test] | ||
| 1580 | +async fn config_warnings_show_on_the_run_page() { | ||
| 1581 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 1582 | + let fx = fixture(dir.path()).await; | ||
| 1583 | + let run = run_with(&fx, &["build"], false).await; | ||
| 1584 | + let run_url = format!("{RUN_BASE}/runs/{}", run.number); | ||
| 1585 | + let cookie = cookie_for("dave-token"); | ||
| 1586 | + assert!( | ||
| 1587 | + !get(&fx.app, &run_url, Some(&cookie)) | ||
| 1588 | + .await | ||
| 1589 | + .text() | ||
| 1590 | + .contains("ci-warnings") | ||
| 1591 | + ); | ||
| 1592 | + fx.store | ||
| 1593 | + .set_run_warnings( | ||
| 1594 | + &run.id, | ||
| 1595 | + &[ | ||
| 1596 | + "unknown key `on.schedule` ignored: this forge may be older than your ci.toml" | ||
| 1597 | + .to_owned(), | ||
| 1598 | + ], | ||
| 1599 | + ) | ||
| 1600 | + .await | ||
| 1601 | + .expect("warnings"); | ||
| 1602 | + let page = get(&fx.app, &run_url, Some(&cookie)).await.text(); | ||
| 1603 | + assert!(page.contains("ci-warnings")); | ||
| 1604 | + assert!(page.contains("on.schedule")); | ||
| 1605 | + assert!(page.contains("Config warnings")); | ||
| 1606 | +} | ||
| 1607 | + | ||
| 1608 | +#[tokio::test] | ||
| 1609 | +async fn job_page_log_carries_the_first_line_number_of_a_cut_log() { | ||
| 1610 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 1611 | + let fx = fixture(dir.path()).await; | ||
| 1612 | + let run = run_with(&fx, &["build"], false).await; | ||
| 1613 | + let job = job_of(&fx, &run).await; | ||
| 1614 | + let path = log_path(&fx.data_dir, &job.id); | ||
| 1615 | + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); | ||
| 1616 | + let mut file = std::fs::File::create(&path).unwrap(); | ||
| 1617 | + // 11000 lines of 100 bytes cut the 512 KiB tail somewhere past line 5000. | ||
| 1618 | + for n in 0..11_000 { | ||
| 1619 | + writeln!(file, "{n:0>98}").unwrap(); | ||
| 1620 | + } | ||
| 1621 | + drop(file); | ||
| 1622 | + let page = get( | ||
| 1623 | + &fx.app, | ||
| 1624 | + &format!("/tahinli/proj/ci/jobs/{}", job.id), | ||
| 1625 | + Some(&cookie_for("dave-token")), | ||
| 1626 | + ) | ||
| 1627 | + .await | ||
| 1628 | + .text(); | ||
| 1629 | + let marker = "data-first=\""; | ||
| 1630 | + let at = page.find(marker).expect("data-first") + marker.len(); | ||
| 1631 | + let first: u64 = page[at..].split('"').next().unwrap().parse().unwrap(); | ||
| 1632 | + assert!(first > 5000, "first line {first}"); | ||
| 1633 | + let after = &page[at..]; | ||
| 1634 | + let text = &after[after.find('>').unwrap() + 1..]; | ||
| 1635 | + let expected = format!("{:0>98}", first - 1); | ||
| 1636 | + assert!( | ||
| 1637 | + text.starts_with(&expected), | ||
| 1638 | + "the tail starts at its own line number" | ||
| 1639 | + ); | ||
| 1640 | +} | ||
| 1641 | + | ||
| 1397 | /// The run page previews the last log line of every running job in its row, and a failed job's row | 1642 | /// The run page previews the last log line of every running job in its row, and a failed job's row |
| 1398 | /// starts expanded. | 1643 | /// starts expanded. |
| 1399 | #[tokio::test] | 1644 | #[tokio::test] |
docs/ci.mdmodified+42 -1
| @@ -16,7 +16,9 @@ supported as an option (`executor = "podman"`). | |||
| 16 | 16 | ||
| 17 | The file is limited to 64 KiB. Parsing is forward-compatible: an unknown key at any level (top level, `[on]`, | 17 | The file is limited to 64 KiB. Parsing is forward-compatible: an unknown key at any level (top level, `[on]`, |
| 18 | `[jobs.<name>]`, `[release]`) is ignored, not rejected, so a `ci.toml` that uses a newer feature still runs on an | 18 | `[jobs.<name>]`, `[release]`) is ignored, not rejected, so a `ci.toml` that uses a newer feature still runs on an |
| 19 | -older forge. The run's jobs get a `[forge] warning: unknown key ...` line at the start of their logs. Known keys | 19 | +older forge. The run page shows the ignored keys in a warning banner, and the run's jobs get a |
| 20 | +`[forge] warning: unknown key ...` line at the start of their logs. For example `on.schedule` is not supported | ||
| 21 | +and shows up this way. Known keys | ||
| 20 | keep full validation: their types, globs, limits and other checks still make the file an error. | 22 | keep full validation: their types, globs, limits and other checks still make the file an error. |
| 21 | A file with a parse error still creates a run, in state `error`, with the message shown on the run | 23 | A file with a parse error still creates a run, in state `error`, with the message shown on the run |
| 22 | page and a `ci/config` status set to `error`. | 24 | page and a `ci/config` status set to `error`. |
| @@ -35,6 +37,7 @@ page and a `ci/config` status set to `error`. | |||
| 35 | | `tags` | array of string | `[]` | Tag globs. A push of a matching `refs/tags/*` starts a run. | | 37 | | `tags` | array of string | `[]` | Tag globs. A push of a matching `refs/tags/*` starts a run. | |
| 36 | | `pull_request` | bool | `false` | Start a run when a pull request is opened, updated or reopened. The config is read at the **head** commit. | | 38 | | `pull_request` | bool | `false` | Start a run when a pull request is opened, updated or reopened. The config is read at the **head** commit. | |
| 37 | | `manual` | bool | `true` | Writers can start a run on an existing branch from the CI tab. | | 39 | | `manual` | bool | `true` | Writers can start a run on an existing branch from the CI tab. | |
| 40 | +| `cancel_superseded` | bool | `false` | A push to a branch cancels the queued and running runs for older commits on that branch (see [Superseded runs](#superseded-runs)). | | ||
| 38 | 41 | ||
| 39 | ### `[jobs.<name>]` | 42 | ### `[jobs.<name>]` |
| 40 | 43 | ||
| @@ -112,6 +115,44 @@ blocked jobs become `cancelled`, and jobs that are already running are told to s | |||
| 112 | heartbeat, so the runner aborts them and they end `cancelled`. The run ends `failure`, so no release | 115 | heartbeat, so the runner aborts them and they end `cancelled`. The run ends `failure`, so no release |
| 113 | is published and no self-update happens. A long `build` does not keep compiling after `test` fails. | 116 | is published and no self-update happens. A long `build` does not keep compiling after `test` fails. |
| 114 | 117 | ||
| 118 | +### Superseded runs | ||
| 119 | + | ||
| 120 | +With `[on] cancel_superseded = true`, a push to a branch cancels the runs that are still queued or running for | ||
| 121 | +older commits of the **same branch** when its own run is created. Queued and blocked jobs become `cancelled` | ||
| 122 | +at once and running jobs are told to stop through their heartbeat, as with the run's Cancel button. Only runs | ||
| 123 | +that were started by a push are cancelled: manual, tag and pull request runs are left alone, and so are runs | ||
| 124 | +that have already finished. The key is read from the new commit's `ci.toml`, and it is off by default. | ||
| 125 | + | ||
| 126 | +### Re-running | ||
| 127 | + | ||
| 128 | +A finished run has three re-run controls on its page (writers only): | ||
| 129 | + | ||
| 130 | +- **Re-run** creates a new run with every job of the original run. | ||
| 131 | +- **Re-run failed jobs** creates a new run with only the jobs that ended `failure`, `error` or `cancelled`, plus every | ||
| 132 | + job that depends on them, directly or not. Jobs that succeeded are not run again. A `needs` entry that points at a | ||
| 133 | + job that is not in the new run is dropped, since that job already succeeded. | ||
| 134 | +- **Re-run this job** (on the job page, and on each job row of the run page) creates a new run with that finished | ||
| 135 | + job and the jobs that depend on it. | ||
| 136 | + | ||
| 137 | +A re-run always uses the **original specs**: the same commit, ref, trigger and job definitions as stored when the | ||
| 138 | +original run was created. It does not read `ci.toml` again, so an edit to the file does not change a re-run. The | ||
| 139 | +config warnings of the original run are carried over. To pick up a changed `ci.toml`, push a commit or start a | ||
| 140 | +manual run. | ||
| 141 | + | ||
| 142 | +### Artifacts | ||
| 143 | + | ||
| 144 | +The run page lists the artifacts of all its jobs, each with a download link, and **Download all (.zip)** which | ||
| 145 | +serves every artifact in one zip with a folder per job (`<job>/<artifact>`). Anyone who can read the repo can | ||
| 146 | +download them. A run whose artifacts add up to more than 256 MiB offers the single downloads only. | ||
| 147 | + | ||
| 148 | +### Job logs | ||
| 149 | + | ||
| 150 | +The job page renders the log with ANSI colours (the sixteen named colours follow the theme, so they read in light | ||
| 151 | +and dark), numbered lines with `#L123` anchors, and a search box (Enter and Shift+Enter move between matches). | ||
| 152 | +A line that is exactly `::group::name` starts a collapsible section and `::endgroup::` ends it. The markers | ||
| 153 | +themselves are not shown. Streaming keeps working while the job runs. The page shows the last 512 KiB; the | ||
| 154 | +full log is at `log.txt`. | ||
| 155 | + | ||
| 115 | ### Releases | 156 | ### Releases |
| 116 | 157 | ||
| 117 | A `[release]` table publishes a release from a tag run. It needs at least one glob in `[on] tags`. | 158 | A `[release]` table publishes a release from a tag run. It needs at least one glob in `[on] tags`. |
style/main.scssmodified+269 -0
| @@ -3958,6 +3958,275 @@ span.reaction { | |||
| 3958 | padding-left: 20px; | 3958 | padding-left: 20px; |
| 3959 | } | 3959 | } |
| 3960 | 3960 | ||
| 3961 | +// A small button for the run page's row actions and the log toolbar. | ||
| 3962 | +.button.ci-mini, | ||
| 3963 | +button.ci-mini { | ||
| 3964 | + height: 28px; | ||
| 3965 | + padding: 0 10px; | ||
| 3966 | + font-size: 0.8125rem; | ||
| 3967 | +} | ||
| 3968 | + | ||
| 3969 | +// The config keys this forge ignored, above the timeline. | ||
| 3970 | +.ci-warnings { | ||
| 3971 | + margin: 8px 0 12px; | ||
| 3972 | + padding: 10px 12px; | ||
| 3973 | + border: 1px solid var(--warning); | ||
| 3974 | + border-radius: var(--radius-md); | ||
| 3975 | + background: color-mix(in srgb, var(--warning) 10%, transparent); | ||
| 3976 | + | ||
| 3977 | + p { | ||
| 3978 | + margin: 0; | ||
| 3979 | + } | ||
| 3980 | + | ||
| 3981 | + ul { | ||
| 3982 | + margin: 6px 0 0; | ||
| 3983 | + padding-left: 18px; | ||
| 3984 | + font-size: 0.8125rem; | ||
| 3985 | + overflow-wrap: anywhere; | ||
| 3986 | + } | ||
| 3987 | +} | ||
| 3988 | + | ||
| 3989 | +.ci-warnings-title { | ||
| 3990 | + font-weight: 600; | ||
| 3991 | + color: var(--warning); | ||
| 3992 | +} | ||
| 3993 | + | ||
| 3994 | +// The run's artifacts: a heading with "download all", then one row per file. | ||
| 3995 | +.ci-art-head { | ||
| 3996 | + display: flex; | ||
| 3997 | + flex-wrap: wrap; | ||
| 3998 | + align-items: center; | ||
| 3999 | + justify-content: space-between; | ||
| 4000 | + gap: 8px 12px; | ||
| 4001 | + margin: 20px 0 8px; | ||
| 4002 | +} | ||
| 4003 | + | ||
| 4004 | +.ci-art-title { | ||
| 4005 | + margin: 0; | ||
| 4006 | + font-size: 0.75rem; | ||
| 4007 | + font-weight: 600; | ||
| 4008 | + letter-spacing: 0.06em; | ||
| 4009 | + text-transform: uppercase; | ||
| 4010 | + color: var(--muted); | ||
| 4011 | +} | ||
| 4012 | + | ||
| 4013 | +.ci-art-list { | ||
| 4014 | + margin: 0; | ||
| 4015 | + padding: 0; | ||
| 4016 | + list-style: none; | ||
| 4017 | + border-top: 1px solid var(--border); | ||
| 4018 | + | ||
| 4019 | + li { | ||
| 4020 | + display: grid; | ||
| 4021 | + grid-template-columns: minmax(0, 1fr) auto auto; | ||
| 4022 | + gap: 12px; | ||
| 4023 | + align-items: center; | ||
| 4024 | + padding: 8px 6px; | ||
| 4025 | + border-bottom: 1px solid var(--border); | ||
| 4026 | + font-size: 0.875rem; | ||
| 4027 | + } | ||
| 4028 | +} | ||
| 4029 | + | ||
| 4030 | +.ci-art-name { | ||
| 4031 | + min-width: 0; | ||
| 4032 | + overflow: hidden; | ||
| 4033 | + text-overflow: ellipsis; | ||
| 4034 | + white-space: nowrap; | ||
| 4035 | + font-family: var(--mono); | ||
| 4036 | + font-size: 0.8125rem; | ||
| 4037 | +} | ||
| 4038 | + | ||
| 4039 | +// A job row: the link takes the width, the re-run button sits at its right. | ||
| 4040 | +.ci-job-item { | ||
| 4041 | + display: flex; | ||
| 4042 | + align-items: center; | ||
| 4043 | + gap: 8px; | ||
| 4044 | + | ||
| 4045 | + .ci-job-line { | ||
| 4046 | + flex: 1; | ||
| 4047 | + min-width: 0; | ||
| 4048 | + } | ||
| 4049 | +} | ||
| 4050 | + | ||
| 4051 | +.ci-job-rerun { | ||
| 4052 | + flex: none; | ||
| 4053 | +} | ||
| 4054 | + | ||
| 4055 | +// The job log: search bar, then numbered lines. Colours come from the theme tokens, so they read in | ||
| 4056 | +// light and dark. A `.ll` is one line (`.ln` its number, `.lt` its text); a `details.lg` is a | ||
| 4057 | +// `::group::` section. | ||
| 4058 | +.ci-logbar { | ||
| 4059 | + display: flex; | ||
| 4060 | + flex-wrap: wrap; | ||
| 4061 | + align-items: center; | ||
| 4062 | + gap: 8px; | ||
| 4063 | + margin: 0 0 8px; | ||
| 4064 | +} | ||
| 4065 | + | ||
| 4066 | +.ci-logsearch { | ||
| 4067 | + flex: 1 1 180px; | ||
| 4068 | + max-width: 320px; | ||
| 4069 | + height: 28px; | ||
| 4070 | + min-width: 0; | ||
| 4071 | + padding: 0 10px; | ||
| 4072 | + font-size: 0.8125rem; | ||
| 4073 | +} | ||
| 4074 | + | ||
| 4075 | +.ci-logcount { | ||
| 4076 | + min-width: 5ch; | ||
| 4077 | + font-size: 0.8125rem; | ||
| 4078 | + font-family: var(--mono); | ||
| 4079 | + color: var(--muted); | ||
| 4080 | + | ||
| 4081 | + &.ci-none { | ||
| 4082 | + color: var(--danger); | ||
| 4083 | + } | ||
| 4084 | +} | ||
| 4085 | + | ||
| 4086 | +.ci-logfold { | ||
| 4087 | + display: inline-flex; | ||
| 4088 | + gap: 8px; | ||
| 4089 | + margin-left: auto; | ||
| 4090 | + | ||
| 4091 | + &[hidden] { | ||
| 4092 | + display: none; | ||
| 4093 | + } | ||
| 4094 | +} | ||
| 4095 | + | ||
| 4096 | +.ci-log { | ||
| 4097 | + font-family: var(--mono); | ||
| 4098 | + line-height: 1.5; | ||
| 4099 | + padding: 8px 0; | ||
| 4100 | + background: var(--code-bg); | ||
| 4101 | + border-radius: var(--radius-md); | ||
| 4102 | + | ||
| 4103 | + .ll { | ||
| 4104 | + display: flex; | ||
| 4105 | + padding-right: 12px; | ||
| 4106 | + | ||
| 4107 | + &:hover { | ||
| 4108 | + background: var(--surface-2); | ||
| 4109 | + } | ||
| 4110 | + | ||
| 4111 | + &:target, | ||
| 4112 | + &.ll-sel { | ||
| 4113 | + background: var(--row-target); | ||
| 4114 | + } | ||
| 4115 | + } | ||
| 4116 | + | ||
| 4117 | + .ln { | ||
| 4118 | + flex: none; | ||
| 4119 | + box-sizing: border-box; | ||
| 4120 | + width: 6ch; | ||
| 4121 | + padding-right: 12px; | ||
| 4122 | + text-align: right; | ||
| 4123 | + color: var(--muted); | ||
| 4124 | + text-decoration: none; | ||
| 4125 | + user-select: none; | ||
| 4126 | + | ||
| 4127 | + &::before { | ||
| 4128 | + content: attr(data-n); | ||
| 4129 | + } | ||
| 4130 | + | ||
| 4131 | + &:hover { | ||
| 4132 | + color: var(--text); | ||
| 4133 | + } | ||
| 4134 | + } | ||
| 4135 | + | ||
| 4136 | + .lt { | ||
| 4137 | + flex: 1; | ||
| 4138 | + min-width: 0; | ||
| 4139 | + white-space: pre-wrap; | ||
| 4140 | + word-break: break-word; | ||
| 4141 | + | ||
| 4142 | + &:empty::after { | ||
| 4143 | + content: "\200b"; | ||
| 4144 | + } | ||
| 4145 | + } | ||
| 4146 | + | ||
| 4147 | + details.lg > summary { | ||
| 4148 | + cursor: pointer; | ||
| 4149 | + font-weight: 600; | ||
| 4150 | + color: var(--text); | ||
| 4151 | + list-style: none; | ||
| 4152 | + | ||
| 4153 | + &::-webkit-details-marker { | ||
| 4154 | + display: none; | ||
| 4155 | + } | ||
| 4156 | + | ||
| 4157 | + .lt::before { | ||
| 4158 | + content: "\25BE\00a0"; | ||
| 4159 | + color: var(--muted); | ||
| 4160 | + } | ||
| 4161 | + } | ||
| 4162 | + | ||
| 4163 | + details.lg:not([open]) > summary .lt::before { | ||
| 4164 | + content: "\25B8\00a0"; | ||
| 4165 | + } | ||
| 4166 | + | ||
| 4167 | + mark.lm { | ||
| 4168 | + background: color-mix(in srgb, var(--warning) 35%, transparent); | ||
| 4169 | + color: inherit; | ||
| 4170 | + border-radius: 2px; | ||
| 4171 | + | ||
| 4172 | + &.lm-cur { | ||
| 4173 | + background: var(--warning); | ||
| 4174 | + color: var(--bg); | ||
| 4175 | + } | ||
| 4176 | + } | ||
| 4177 | + | ||
| 4178 | + // ANSI colours: the sixteen named ones map to the theme tokens. | ||
| 4179 | + .a-b { | ||
| 4180 | + font-weight: 700; | ||
| 4181 | + } | ||
| 4182 | + | ||
| 4183 | + .a-d { | ||
| 4184 | + opacity: 0.7; | ||
| 4185 | + } | ||
| 4186 | + | ||
| 4187 | + .a-i { | ||
| 4188 | + font-style: italic; | ||
| 4189 | + } | ||
| 4190 | + | ||
| 4191 | + .a-u { | ||
| 4192 | + text-decoration: underline; | ||
| 4193 | + } | ||
| 4194 | + | ||
| 4195 | + .a-v { | ||
| 4196 | + background: var(--text); | ||
| 4197 | + color: var(--code-bg); | ||
| 4198 | + } | ||
| 4199 | +} | ||
| 4200 | + | ||
| 4201 | +$ansi-colours: ( | ||
| 4202 | + 0: var(--muted), | ||
| 4203 | + 1: var(--danger), | ||
| 4204 | + 2: var(--ok), | ||
| 4205 | + 3: var(--warn), | ||
| 4206 | + 4: var(--accent), | ||
| 4207 | + 5: var(--important), | ||
| 4208 | + 6: var(--tip), | ||
| 4209 | + 7: var(--text-2), | ||
| 4210 | +); | ||
| 4211 | + | ||
| 4212 | +@each $n, $c in $ansi-colours { | ||
| 4213 | + .ci-log .a-fg-#{$n} { | ||
| 4214 | + color: $c; | ||
| 4215 | + } | ||
| 4216 | + | ||
| 4217 | + .ci-log .a-bg-#{$n} { | ||
| 4218 | + background: color-mix(in srgb, #{$c} 30%, transparent); | ||
| 4219 | + } | ||
| 4220 | + | ||
| 4221 | + .ci-log .a-fg-#{$n + 8} { | ||
| 4222 | + color: color-mix(in srgb, #{$c} 70%, var(--text)); | ||
| 4223 | + } | ||
| 4224 | + | ||
| 4225 | + .ci-log .a-bg-#{$n + 8} { | ||
| 4226 | + background: color-mix(in srgb, #{$c} 45%, transparent); | ||
| 4227 | + } | ||
| 4228 | +} | ||
| 4229 | + | ||
| 3961 | // Admin runners table: name and labels take the slack, the rest size to their content, and the | 4230 | // Admin runners table: name and labels take the slack, the rest size to their content, and the |
| 3962 | // actions sit flush right. State reuses the `.ci-state` pill; a disabled runner is muted. | 4231 | // actions sit flush right. State reuses the `.ci-state` pill; a disabled runner is muted. |
| 3963 | .table.runners { | 4232 | .table.runners { |