| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use forge_ci::config::{CiConfig, Event, parse_config}; |
| 8 | use forge_core::authz::{Action, authorize}; |
| 9 | use forge_core::ci::{CiRun, NewJob}; |
| 10 | use forge_core::store::commit_status::StatusState; |
| 11 | use forge_core::{PullRequest, Repo}; |
| 12 | use forge_git::browse::{peel_to_commit, read_blob, resolve_commit}; |
| 13 | use tokio::io::AsyncWriteExt; |
| 14 | |
| 15 | use super::api::fit_to_cap; |
| 16 | use super::{log_path, publish, sync_run_statuses}; |
| 17 | use crate::internal::is_zero_oid; |
| 18 | use crate::state::AppState; |
| 19 | |
| 20 | |
| 21 | pub const CONFIG_PATH: &str = ".forge/ci.toml"; |
| 22 | |
| 23 | const MAX_CONFIG_BYTES: usize = 64 * 1024; |
| 24 | |
| 25 | const MAX_WARNING_LINES: usize = 20; |
| 26 | const MIB: u64 = 1024 * 1024; |
| 27 | |
| 28 | |
| 29 | type PlannedJob = (String, String, Vec<String>); |
| 30 | |
| 31 | |
| 32 | pub(super) enum Loaded { |
| 33 | Missing, |
| 34 | Invalid(String), |
| 35 | Valid(CiConfig), |
| 36 | } |
| 37 | |
| 38 | |
| 39 | enum Plan { |
| 40 | |
| 41 | Missing, |
| 42 | |
| 43 | NotTriggered, |
| 44 | |
| 45 | |
| 46 | Run { |
| 47 | jobs: Vec<PlannedJob>, |
| 48 | config_error: Option<String>, |
| 49 | warnings: Vec<String>, |
| 50 | |
| 51 | cancel_superseded: bool, |
| 52 | }, |
| 53 | } |
| 54 | |
| 55 | |
| 56 | struct Request<'a> { |
| 57 | repo: &'a Repo, |
| 58 | trigger: &'static str, |
| 59 | git_ref: &'a str, |
| 60 | commit: &'a str, |
| 61 | pull_number: Option<i64>, |
| 62 | actor_id: &'a str, |
| 63 | needs_approval: bool, |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | pub async fn on_ref_update( |
| 70 | state: &AppState, |
| 71 | repo: &Repo, |
| 72 | actor_id: &str, |
| 73 | refname: &str, |
| 74 | new_oid: &str, |
| 75 | ) { |
| 76 | if !state.live().ci.enabled || is_zero_oid(new_oid) { |
| 77 | return; |
| 78 | } |
| 79 | let (trigger, event) = if let Some(branch) = refname.strip_prefix("refs/heads/") { |
| 80 | ("push", Event::Push { branch }) |
| 81 | } else if let Some(tag) = refname.strip_prefix("refs/tags/") { |
| 82 | ("tag", Event::Tag { tag }) |
| 83 | } else { |
| 84 | return; |
| 85 | }; |
| 86 | let result = async { |
| 87 | |
| 88 | |
| 89 | let Some(commit) = peeled_commit(state, &repo.id, new_oid).await else { |
| 90 | return forge_core::Result::Ok(()); |
| 91 | }; |
| 92 | let new_oid = commit.as_str(); |
| 93 | let loaded = load(state, &repo.id, new_oid).await; |
| 94 | if let Plan::Run { |
| 95 | jobs, |
| 96 | config_error, |
| 97 | warnings, |
| 98 | cancel_superseded, |
| 99 | } = plan_for(loaded, &event)? |
| 100 | { |
| 101 | let run = create( |
| 102 | state, |
| 103 | Request { |
| 104 | repo, |
| 105 | trigger, |
| 106 | git_ref: refname, |
| 107 | commit: new_oid, |
| 108 | pull_number: None, |
| 109 | actor_id, |
| 110 | needs_approval: false, |
| 111 | }, |
| 112 | jobs, |
| 113 | config_error.as_deref(), |
| 114 | &warnings, |
| 115 | ) |
| 116 | .await?; |
| 117 | if cancel_superseded && trigger == "push" { |
| 118 | cancel_superseded_runs(state, &run).await?; |
| 119 | } |
| 120 | } |
| 121 | forge_core::Result::Ok(()) |
| 122 | } |
| 123 | .await; |
| 124 | if let Err(e) = result { |
| 125 | tracing::error!(error = %e, repo_id = %repo.id, refname, "ci: scheduling a push failed"); |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | pub async fn on_pull_event(state: &AppState, repo: &Repo, pull: &PullRequest, actor_id: &str) { |
| 133 | if !state.live().ci.enabled { |
| 134 | return; |
| 135 | } |
| 136 | if let Err(e) = pull_run(state, repo, pull, actor_id).await { |
| 137 | tracing::error!(error = %e, repo_id = %repo.id, number = pull.issue.number, "ci: scheduling a pull request failed"); |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | async fn pull_run( |
| 142 | state: &AppState, |
| 143 | repo: &Repo, |
| 144 | pull: &PullRequest, |
| 145 | actor_id: &str, |
| 146 | ) -> forge_core::Result<()> { |
| 147 | let loaded = load(state, &repo.id, &pull.head_oid).await; |
| 148 | let Plan::Run { |
| 149 | jobs, |
| 150 | config_error, |
| 151 | warnings, |
| 152 | .. |
| 153 | } = plan_for(loaded, &Event::PullRequest)? |
| 154 | else { |
| 155 | return Ok(()); |
| 156 | }; |
| 157 | let needs_approval = needs_approval(state, repo, pull).await?; |
| 158 | let git_ref = format!("refs/pull/{}/head", pull.issue.number); |
| 159 | create( |
| 160 | state, |
| 161 | Request { |
| 162 | repo, |
| 163 | trigger: "pull_request", |
| 164 | git_ref: &git_ref, |
| 165 | commit: &pull.head_oid, |
| 166 | pull_number: Some(pull.issue.number), |
| 167 | actor_id, |
| 168 | needs_approval, |
| 169 | }, |
| 170 | jobs, |
| 171 | config_error.as_deref(), |
| 172 | &warnings, |
| 173 | ) |
| 174 | .await?; |
| 175 | Ok(()) |
| 176 | } |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | pub async fn manual_run( |
| 182 | state: &AppState, |
| 183 | repo: &Repo, |
| 184 | branch: &str, |
| 185 | actor_id: &str, |
| 186 | ) -> forge_core::Result<CiRun> { |
| 187 | if !state.live().ci.enabled { |
| 188 | return Err(forge_core::Error::Invalid( |
| 189 | "CI is disabled on this instance".into(), |
| 190 | )); |
| 191 | } |
| 192 | let git_ref = format!("refs/heads/{branch}"); |
| 193 | let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, &repo.id) |
| 194 | .map_err(|e| forge_core::Error::Git(e.to_string()))?; |
| 195 | |
| 196 | let short = branch.to_owned(); |
| 197 | let Some(commit) = blocking(move || resolve_commit(&repo_dir, &short)).await? else { |
| 198 | return Err(forge_core::Error::NotFound); |
| 199 | }; |
| 200 | let loaded = load(state, &repo.id, &commit).await; |
| 201 | match plan_for(loaded, &Event::Manual)? { |
| 202 | Plan::Run { |
| 203 | jobs, |
| 204 | config_error, |
| 205 | warnings, |
| 206 | .. |
| 207 | } => { |
| 208 | create( |
| 209 | state, |
| 210 | Request { |
| 211 | repo, |
| 212 | trigger: "manual", |
| 213 | git_ref: &git_ref, |
| 214 | commit: &commit, |
| 215 | pull_number: None, |
| 216 | actor_id, |
| 217 | needs_approval: false, |
| 218 | }, |
| 219 | jobs, |
| 220 | config_error.as_deref(), |
| 221 | &warnings, |
| 222 | ) |
| 223 | .await |
| 224 | } |
| 225 | Plan::NotTriggered => Err(forge_core::Error::Invalid( |
| 226 | "manual runs are not enabled in .forge/ci.toml".into(), |
| 227 | )), |
| 228 | Plan::Missing => Err(forge_core::Error::Invalid( |
| 229 | "this branch has no .forge/ci.toml".into(), |
| 230 | )), |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | |
| 235 | |
| 236 | pub(super) async fn default_head_config(state: &AppState, repo: &Repo) -> Option<(String, Loaded)> { |
| 237 | let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).ok()?; |
| 238 | let short = repo.default_branch.clone(); |
| 239 | let commit = match blocking(move || resolve_commit(&repo_dir, &short)).await { |
| 240 | Ok(commit) => commit?, |
| 241 | Err(e) => { |
| 242 | tracing::error!(error = %e, repo_id = %repo.id, "ci: resolving the default branch failed"); |
| 243 | return None; |
| 244 | } |
| 245 | }; |
| 246 | let loaded = load(state, &repo.id, &commit).await; |
| 247 | Some((commit, loaded)) |
| 248 | } |
| 249 | |
| 250 | |
| 251 | |
| 252 | pub async fn schedules_of(state: &AppState, repo: &Repo) -> Vec<String> { |
| 253 | match default_head_config(state, repo).await { |
| 254 | Some((_, Loaded::Valid(cfg))) => cfg.on.schedule, |
| 255 | _ => Vec::new(), |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | |
| 260 | |
| 261 | pub(super) async fn scheduled_run( |
| 262 | state: &AppState, |
| 263 | repo: &Repo, |
| 264 | commit: &str, |
| 265 | loaded: Loaded, |
| 266 | ) -> forge_core::Result<Option<CiRun>> { |
| 267 | let Plan::Run { |
| 268 | jobs, |
| 269 | config_error, |
| 270 | warnings, |
| 271 | .. |
| 272 | } = plan_for(loaded, &Event::Schedule)? |
| 273 | else { |
| 274 | return Ok(None); |
| 275 | }; |
| 276 | let git_ref = format!("refs/heads/{}", repo.default_branch); |
| 277 | let run = create( |
| 278 | state, |
| 279 | Request { |
| 280 | repo, |
| 281 | trigger: "schedule", |
| 282 | git_ref: &git_ref, |
| 283 | commit, |
| 284 | pull_number: None, |
| 285 | |
| 286 | actor_id: &repo.owner_id, |
| 287 | needs_approval: false, |
| 288 | }, |
| 289 | jobs, |
| 290 | config_error.as_deref(), |
| 291 | &warnings, |
| 292 | ) |
| 293 | .await?; |
| 294 | Ok(Some(run)) |
| 295 | } |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | pub async fn merge_queue_run( |
| 301 | state: &AppState, |
| 302 | repo: &Repo, |
| 303 | test_ref: &str, |
| 304 | branch: &str, |
| 305 | commit: &str, |
| 306 | actor_id: &str, |
| 307 | pull_number: i64, |
| 308 | ) -> forge_core::Result<Option<CiRun>> { |
| 309 | if !state.live().ci.enabled { |
| 310 | return Ok(None); |
| 311 | } |
| 312 | let loaded = load(state, &repo.id, commit).await; |
| 313 | let Plan::Run { |
| 314 | jobs, |
| 315 | config_error, |
| 316 | warnings, |
| 317 | .. |
| 318 | } = plan_for(loaded, &Event::MergeQueue { branch })? |
| 319 | else { |
| 320 | return Ok(None); |
| 321 | }; |
| 322 | let run = create( |
| 323 | state, |
| 324 | Request { |
| 325 | repo, |
| 326 | trigger: "merge_queue", |
| 327 | git_ref: test_ref, |
| 328 | commit, |
| 329 | pull_number: Some(pull_number), |
| 330 | actor_id, |
| 331 | needs_approval: false, |
| 332 | }, |
| 333 | jobs, |
| 334 | config_error.as_deref(), |
| 335 | &warnings, |
| 336 | ) |
| 337 | .await?; |
| 338 | Ok(Some(run)) |
| 339 | } |
| 340 | |
| 341 | |
| 342 | |
| 343 | async fn create( |
| 344 | state: &AppState, |
| 345 | req: Request<'_>, |
| 346 | jobs: Vec<PlannedJob>, |
| 347 | config_error: Option<&str>, |
| 348 | warnings: &[String], |
| 349 | ) -> forge_core::Result<CiRun> { |
| 350 | let new_jobs: Vec<NewJob<'_>> = jobs |
| 351 | .iter() |
| 352 | .map(|(name, spec_json, needs)| NewJob { |
| 353 | name, |
| 354 | spec_json, |
| 355 | needs: needs.as_slice(), |
| 356 | }) |
| 357 | .collect(); |
| 358 | let run = state |
| 359 | .store |
| 360 | .create_run( |
| 361 | &req.repo.id, |
| 362 | req.trigger, |
| 363 | req.git_ref, |
| 364 | req.commit, |
| 365 | req.pull_number, |
| 366 | req.actor_id, |
| 367 | req.needs_approval, |
| 368 | &new_jobs, |
| 369 | config_error, |
| 370 | ) |
| 371 | .await?; |
| 372 | state.ci_live.bump_repo(&run.repo_id); |
| 373 | state.store.set_run_warnings(&run.id, warnings).await?; |
| 374 | note_warnings(state, &run, warnings).await?; |
| 375 | if let Some(message) = config_error { |
| 376 | let url = format!( |
| 377 | "{}/{}/{}/ci/runs/{}", |
| 378 | state.config.base_url.trim_end_matches('/'), |
| 379 | req.repo.owner_name, |
| 380 | req.repo.name, |
| 381 | run.number |
| 382 | ); |
| 383 | publish( |
| 384 | state, |
| 385 | req.repo, |
| 386 | &run, |
| 387 | "ci/config", |
| 388 | StatusState::Error, |
| 389 | message, |
| 390 | &url, |
| 391 | ) |
| 392 | .await; |
| 393 | } |
| 394 | if sync_run_statuses(state, &run).await? { |
| 395 | state.ci_waker.notify_waiters(); |
| 396 | } |
| 397 | Ok(run) |
| 398 | } |
| 399 | |
| 400 | |
| 401 | |
| 402 | async fn cancel_superseded_runs(state: &AppState, run: &CiRun) -> forge_core::Result<()> { |
| 403 | let older = state |
| 404 | .store |
| 405 | .superseded_candidates(&run.repo_id, &run.git_ref, &run.commit_oid) |
| 406 | .await?; |
| 407 | for old in older.into_iter().filter(|old| old.number < run.number) { |
| 408 | let before = state.store.jobs_for_run(&old.id).await?; |
| 409 | state.store.request_cancel(&old.id).await?; |
| 410 | if let Err(e) = crate::ci::after_change(state, &old.id, &before).await { |
| 411 | tracing::error!(error = %e, run_id = %old.id, "ci: syncing a superseded run failed"); |
| 412 | } |
| 413 | } |
| 414 | Ok(()) |
| 415 | } |
| 416 | |
| 417 | |
| 418 | |
| 419 | |
| 420 | async fn note_warnings( |
| 421 | state: &AppState, |
| 422 | run: &CiRun, |
| 423 | warnings: &[String], |
| 424 | ) -> forge_core::Result<()> { |
| 425 | if warnings.is_empty() { |
| 426 | return Ok(()); |
| 427 | } |
| 428 | let mut text = String::new(); |
| 429 | for warning in warnings { |
| 430 | tracing::warn!(run_id = %run.id, repo_id = %run.repo_id, "ci: {warning}"); |
| 431 | } |
| 432 | for warning in warnings.iter().take(MAX_WARNING_LINES) { |
| 433 | text.push_str(&format!("[forge] warning: {warning}\n")); |
| 434 | } |
| 435 | let cap = state.live().ci.max_log_mb.saturating_mul(MIB); |
| 436 | for job in state.store.jobs_for_run(&run.id).await? { |
| 437 | let path = log_path(&state.config.data_dir, &job.id); |
| 438 | let current = match tokio::fs::metadata(&path).await { |
| 439 | Ok(meta) => meta.len(), |
| 440 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, |
| 441 | Err(e) => { |
| 442 | tracing::error!(error = %e, job_id = %job.id, "ci: reading the job log failed"); |
| 443 | continue; |
| 444 | } |
| 445 | }; |
| 446 | let bytes = fit_to_cap(current, cap, text.as_bytes()); |
| 447 | if bytes.is_empty() { |
| 448 | continue; |
| 449 | } |
| 450 | let written: std::io::Result<()> = async { |
| 451 | if let Some(parent) = path.parent() { |
| 452 | tokio::fs::create_dir_all(parent).await?; |
| 453 | } |
| 454 | let mut file = tokio::fs::OpenOptions::new() |
| 455 | .create(true) |
| 456 | .append(true) |
| 457 | .open(&path) |
| 458 | .await?; |
| 459 | file.write_all(&bytes).await?; |
| 460 | file.flush().await |
| 461 | } |
| 462 | .await; |
| 463 | if let Err(e) = written { |
| 464 | tracing::error!(error = %e, job_id = %job.id, "ci: writing the job log failed"); |
| 465 | continue; |
| 466 | } |
| 467 | if let Err(e) = state.store.add_log_bytes(&job.id, bytes.len() as i64).await { |
| 468 | tracing::error!(error = %e, job_id = %job.id, "ci: counting the job log bytes failed"); |
| 469 | continue; |
| 470 | } |
| 471 | state.ci_live.bump_job(&job.id); |
| 472 | } |
| 473 | Ok(()) |
| 474 | } |
| 475 | |
| 476 | |
| 477 | fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result<Plan> { |
| 478 | match loaded { |
| 479 | Loaded::Missing => Ok(Plan::Missing), |
| 480 | Loaded::Invalid(message) => Ok(Plan::Run { |
| 481 | jobs: Vec::new(), |
| 482 | config_error: Some(message), |
| 483 | warnings: Vec::new(), |
| 484 | cancel_superseded: false, |
| 485 | }), |
| 486 | Loaded::Valid(cfg) => { |
| 487 | if !cfg.triggered_by(event) { |
| 488 | return Ok(Plan::NotTriggered); |
| 489 | } |
| 490 | Ok(Plan::Run { |
| 491 | jobs: plan_jobs(&cfg)?, |
| 492 | config_error: None, |
| 493 | warnings: cfg.warnings.clone(), |
| 494 | cancel_superseded: cfg.on.cancel_superseded, |
| 495 | }) |
| 496 | } |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | |
| 501 | fn plan_jobs(cfg: &CiConfig) -> forge_core::Result<Vec<PlannedJob>> { |
| 502 | let mut jobs = Vec::new(); |
| 503 | for name in cfg.job_order() { |
| 504 | let Some(spec) = cfg.jobs.get(name) else { |
| 505 | continue; |
| 506 | }; |
| 507 | let spec_json = |
| 508 | serde_json::to_string(spec).map_err(|e| forge_core::Error::Invalid(e.to_string()))?; |
| 509 | jobs.push((name.to_owned(), spec_json, spec.needs.clone())); |
| 510 | } |
| 511 | Ok(jobs) |
| 512 | } |
| 513 | |
| 514 | |
| 515 | |
| 516 | |
| 517 | pub(super) async fn config_at(state: &AppState, repo_id: &str, commit: &str) -> Option<CiConfig> { |
| 518 | match load(state, repo_id, commit).await { |
| 519 | Loaded::Valid(config) => Some(config), |
| 520 | Loaded::Missing | Loaded::Invalid(_) => None, |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | |
| 525 | async fn peeled_commit(state: &AppState, repo_id: &str, oid: &str) -> Option<String> { |
| 526 | let dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) { |
| 527 | Ok(path) => path, |
| 528 | Err(e) => { |
| 529 | tracing::error!(error = %e, repo_id, "ci: bad repo path"); |
| 530 | return None; |
| 531 | } |
| 532 | }; |
| 533 | let rev = oid.to_owned(); |
| 534 | match blocking(move || peel_to_commit(&dir, &rev)).await { |
| 535 | Ok(Some(commit)) => Some(commit), |
| 536 | Ok(None) => None, |
| 537 | Err(e) => { |
| 538 | tracing::error!(error = %e, repo_id, oid, "ci: peeling the pushed ref failed"); |
| 539 | None |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded { |
| 545 | let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) { |
| 546 | Ok(path) => path, |
| 547 | Err(e) => { |
| 548 | tracing::error!(error = %e, repo_id, "ci: bad repo path"); |
| 549 | return Loaded::Invalid(format!("could not read {CONFIG_PATH}")); |
| 550 | } |
| 551 | }; |
| 552 | let (dir, rev) = (repo_dir, commit.to_owned()); |
| 553 | let blob = match blocking(move || read_blob(&dir, &rev, CONFIG_PATH, MAX_CONFIG_BYTES)).await { |
| 554 | Ok(blob) => blob, |
| 555 | Err(e) => { |
| 556 | tracing::error!(error = %e, repo_id, commit, "ci: reading the workflow failed"); |
| 557 | return Loaded::Invalid(format!("could not read {CONFIG_PATH}")); |
| 558 | } |
| 559 | }; |
| 560 | let Some(blob) = blob else { |
| 561 | return Loaded::Missing; |
| 562 | }; |
| 563 | if blob.truncated { |
| 564 | return Loaded::Invalid(format!("{CONFIG_PATH} is larger than 64 KiB")); |
| 565 | } |
| 566 | if blob.is_binary { |
| 567 | return Loaded::Invalid(format!("{CONFIG_PATH} is not text")); |
| 568 | } |
| 569 | let Ok(text) = String::from_utf8(blob.data) else { |
| 570 | return Loaded::Invalid(format!("{CONFIG_PATH} is not valid UTF-8")); |
| 571 | }; |
| 572 | match parse_config(&text) { |
| 573 | Ok(cfg) => Loaded::Valid(cfg), |
| 574 | Err(e) => Loaded::Invalid(e.to_string()), |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | |
| 579 | |
| 580 | pub async fn workflow_name(state: &AppState, repo_id: &str, commit: &str) -> Option<String> { |
| 581 | match load(state, repo_id, commit).await { |
| 582 | Loaded::Valid(cfg) => cfg |
| 583 | .name |
| 584 | .map(|name| name.trim().to_owned()) |
| 585 | .filter(|name| !name.is_empty()), |
| 586 | Loaded::Missing | Loaded::Invalid(_) => None, |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | |
| 591 | |
| 592 | async fn needs_approval( |
| 593 | state: &AppState, |
| 594 | repo: &Repo, |
| 595 | pull: &PullRequest, |
| 596 | ) -> forge_core::Result<bool> { |
| 597 | if pull.head_repo_id.as_deref() != Some(repo.id.as_str()) { |
| 598 | return Ok(true); |
| 599 | } |
| 600 | let Some(author) = state.store.user_by_id(&pull.issue.author_id).await? else { |
| 601 | return Ok(true); |
| 602 | }; |
| 603 | if author.is_org() { |
| 604 | return Ok(true); |
| 605 | } |
| 606 | let role = state.store.collaborator_role(&repo.id, &author.id).await?; |
| 607 | let org_role = state |
| 608 | .store |
| 609 | .org_repo_role(&repo.owner_id, &author.id, &repo.id) |
| 610 | .await?; |
| 611 | Ok(authorize(Some(&author), repo, role, org_role, Action::Write).is_err()) |
| 612 | } |
| 613 | |
| 614 | |
| 615 | async fn blocking<T, F>(work: F) -> forge_core::Result<T> |
| 616 | where |
| 617 | F: FnOnce() -> forge_git::Result<T> + Send + 'static, |
| 618 | T: Send + 'static, |
| 619 | { |
| 620 | match tokio::task::spawn_blocking(work).await { |
| 621 | Ok(Ok(value)) => Ok(value), |
| 622 | Ok(Err(e)) => Err(forge_core::Error::Git(e.to_string())), |
| 623 | Err(e) => Err(forge_core::Error::Git(format!("git task failed: {e}"))), |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | #[cfg(test)] |
| 628 | pub(super) mod tests { |
| 629 | use std::path::{Path, PathBuf}; |
| 630 | use std::time::Duration; |
| 631 | |
| 632 | use forge_core::ci::{CiJob, CiRunner, JobState, RunState}; |
| 633 | use forge_core::store::commit_status::{CommitStatus, StatusState}; |
| 634 | use forge_core::time::stamp_after; |
| 635 | use forge_core::{User, Visibility}; |
| 636 | use forge_git::repo::{init_bare, repo_path}; |
| 637 | use tempfile::TempDir; |
| 638 | |
| 639 | use super::*; |
| 640 | use crate::ci::log_path; |
| 641 | use crate::ci::reaper::{purge_once, reap_before}; |
| 642 | use crate::post_update::after_ref_update; |
| 643 | use crate::test_support::test_state; |
| 644 | |
| 645 | pub(in crate::ci) const ZERO: &str = "0000000000000000000000000000000000000000"; |
| 646 | |
| 647 | const CONFIG: &str = r#" |
| 648 | [on] |
| 649 | push = ["main"] |
| 650 | pull_request = true |
| 651 | |
| 652 | [jobs.build] |
| 653 | image = "alpine:3" |
| 654 | run = "make" |
| 655 | |
| 656 | [jobs.test] |
| 657 | image = "alpine:3" |
| 658 | run = "make test" |
| 659 | needs = ["build"] |
| 660 | "#; |
| 661 | |
| 662 | const CONFIG_GLOBS: &str = r#" |
| 663 | [on] |
| 664 | push = ["release/*"] |
| 665 | |
| 666 | [jobs.build] |
| 667 | image = "alpine:3" |
| 668 | run = "make" |
| 669 | "#; |
| 670 | |
| 671 | pub(in crate::ci) const CONFIG_TAGS: &str = r#" |
| 672 | [on] |
| 673 | push = [] |
| 674 | tags = ["v*"] |
| 675 | |
| 676 | [jobs.build] |
| 677 | image = "alpine:3" |
| 678 | run = "make" |
| 679 | "#; |
| 680 | |
| 681 | const CONFIG_ONE_JOB: &str = r#" |
| 682 | [on] |
| 683 | push = ["main"] |
| 684 | |
| 685 | [jobs.build] |
| 686 | image = "alpine:3" |
| 687 | run = "make" |
| 688 | "#; |
| 689 | |
| 690 | const CONFIG_NO_MANUAL: &str = r#" |
| 691 | [on] |
| 692 | push = ["main"] |
| 693 | manual = false |
| 694 | |
| 695 | [jobs.build] |
| 696 | image = "alpine:3" |
| 697 | run = "make" |
| 698 | "#; |
| 699 | |
| 700 | pub(in crate::ci) fn git(dir: &Path, args: &[&str]) -> String { |
| 701 | let out = std::process::Command::new("git") |
| 702 | .arg("-C") |
| 703 | .arg(dir) |
| 704 | .args(args) |
| 705 | .env("GIT_AUTHOR_NAME", "test") |
| 706 | .env("GIT_AUTHOR_EMAIL", "test@example.com") |
| 707 | .env("GIT_COMMITTER_NAME", "test") |
| 708 | .env("GIT_COMMITTER_EMAIL", "test@example.com") |
| 709 | .output() |
| 710 | .expect("git runs"); |
| 711 | assert!( |
| 712 | out.status.success(), |
| 713 | "git {args:?} failed: {}", |
| 714 | String::from_utf8_lossy(&out.stderr) |
| 715 | ); |
| 716 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 717 | } |
| 718 | |
| 719 | pub(in crate::ci) struct Fixture { |
| 720 | pub(in crate::ci) _tmp: TempDir, |
| 721 | pub(in crate::ci) state: AppState, |
| 722 | pub(in crate::ci) repo: Repo, |
| 723 | pub(in crate::ci) owner: User, |
| 724 | pub(in crate::ci) bare: PathBuf, |
| 725 | pub(in crate::ci) work: PathBuf, |
| 726 | } |
| 727 | |
| 728 | pub(in crate::ci) async fn fixture() -> Fixture { |
| 729 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 730 | let state = test_state(tmp.path()).await; |
| 731 | let owner = state |
| 732 | .store |
| 733 | .create_user("tahinli", None, "unused", false) |
| 734 | .await |
| 735 | .expect("user"); |
| 736 | let repo = state |
| 737 | .store |
| 738 | .create_repo(&owner.id, "proj", "", Visibility::Private, "main") |
| 739 | .await |
| 740 | .expect("repo"); |
| 741 | let bare = repo_path(&state.git.data_dir, &repo.id).expect("repo path"); |
| 742 | init_bare(&state.git, &bare, "main") |
| 743 | .await |
| 744 | .expect("init bare"); |
| 745 | let work = tmp.path().join("work"); |
| 746 | git(tmp.path(), &["init", "-b", "main", "work"]); |
| 747 | Fixture { |
| 748 | _tmp: tmp, |
| 749 | state, |
| 750 | repo, |
| 751 | owner, |
| 752 | bare, |
| 753 | work, |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | |
| 758 | pub(in crate::ci) fn commit(work: &Path, files: &[(&str, &str)]) -> String { |
| 759 | for (path, text) in files { |
| 760 | let full = work.join(path); |
| 761 | if let Some(parent) = full.parent() { |
| 762 | std::fs::create_dir_all(parent).expect("dirs"); |
| 763 | } |
| 764 | std::fs::write(&full, text).expect("write"); |
| 765 | git(work, &["add", path]); |
| 766 | } |
| 767 | git(work, &["commit", "--allow-empty", "-m", "change"]); |
| 768 | git(work, &["rev-parse", "HEAD"]) |
| 769 | } |
| 770 | |
| 771 | |
| 772 | pub(in crate::ci) fn land(fx: &Fixture, oid: &str, refname: &str) { |
| 773 | let work = fx.work.to_str().expect("utf8 path"); |
| 774 | git( |
| 775 | &fx.bare, |
| 776 | &["fetch", "--no-tags", work, &format!("+{oid}:{refname}")], |
| 777 | ); |
| 778 | } |
| 779 | |
| 780 | |
| 781 | pub(in crate::ci) async fn push(fx: &Fixture, files: &[(&str, &str)], refname: &str) -> String { |
| 782 | let oid = commit(&fx.work, files); |
| 783 | land(fx, &oid, refname); |
| 784 | after_ref_update(&fx.state, &fx.repo, &fx.owner.id, refname, ZERO, &oid) |
| 785 | .await |
| 786 | .expect("post update"); |
| 787 | oid |
| 788 | } |
| 789 | |
| 790 | fn status<'a>(statuses: &'a [CommitStatus], context: &str) -> Option<&'a CommitStatus> { |
| 791 | statuses.iter().find(|s| s.context == context) |
| 792 | } |
| 793 | |
| 794 | fn state_of(jobs: &[CiJob], name: &str) -> Option<JobState> { |
| 795 | jobs.iter().find(|j| j.name == name).map(|j| j.state) |
| 796 | } |
| 797 | |
| 798 | pub(in crate::ci) async fn runs_total(fx: &Fixture) -> u64 { |
| 799 | fx.state |
| 800 | .store |
| 801 | .list_runs(&fx.repo.id, 1, 50) |
| 802 | .await |
| 803 | .expect("list runs") |
| 804 | .1 |
| 805 | } |
| 806 | |
| 807 | async fn runner(fx: &Fixture) -> CiRunner { |
| 808 | let token = fx |
| 809 | .state |
| 810 | .store |
| 811 | .create_registration_token(&fx.owner.id, 24) |
| 812 | .await |
| 813 | .expect("token"); |
| 814 | let (runner, _secret) = fx |
| 815 | .state |
| 816 | .store |
| 817 | .register_runner(&token, "runner-1", &[]) |
| 818 | .await |
| 819 | .expect("register"); |
| 820 | runner |
| 821 | } |
| 822 | |
| 823 | #[tokio::test] |
| 824 | async fn push_with_config_creates_run_and_pending_statuses() { |
| 825 | let fx = fixture().await; |
| 826 | let oid = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/main").await; |
| 827 | |
| 828 | let run = fx |
| 829 | .state |
| 830 | .store |
| 831 | .run_by_number(&fx.repo.id, 1) |
| 832 | .await |
| 833 | .expect("query") |
| 834 | .expect("run exists"); |
| 835 | assert_eq!(run.trigger, "push"); |
| 836 | assert_eq!(run.git_ref, "refs/heads/main"); |
| 837 | assert_eq!(run.commit_oid, oid); |
| 838 | assert!(run.config_error.is_none()); |
| 839 | |
| 840 | let jobs = fx.state.store.jobs_for_run(&run.id).await.expect("jobs"); |
| 841 | assert_eq!(state_of(&jobs, "build"), Some(JobState::Queued)); |
| 842 | assert_eq!(state_of(&jobs, "test"), Some(JobState::Blocked)); |
| 843 | |
| 844 | let statuses = fx |
| 845 | .state |
| 846 | .store |
| 847 | .statuses_for(&fx.repo.id, &oid) |
| 848 | .await |
| 849 | .expect("statuses"); |
| 850 | let build = status(&statuses, "ci/build").expect("ci/build status"); |
| 851 | assert_eq!(build.state, StatusState::Pending); |
| 852 | let url = build.target_url.clone().unwrap_or_default(); |
| 853 | let job = jobs.iter().find(|j| j.name == "build").expect("build job"); |
| 854 | assert_eq!( |
| 855 | url, |
| 856 | format!("https://forge.test/tahinli/proj/ci/jobs/{}", job.id) |
| 857 | ); |
| 858 | let test = status(&statuses, "ci/test").expect("ci/test status"); |
| 859 | assert_eq!(test.state, StatusState::Pending); |
| 860 | } |
| 861 | |
| 862 | #[tokio::test] |
| 863 | async fn unknown_config_keys_still_run_and_warn_in_each_job_log() { |
| 864 | let fx = fixture().await; |
| 865 | let text = format!("{CONFIG_ONE_JOB}\n[future]\nx = 1\n"); |
| 866 | push(&fx, &[(CONFIG_PATH, text.as_str())], "refs/heads/main").await; |
| 867 | |
| 868 | let run = fx |
| 869 | .state |
| 870 | .store |
| 871 | .run_by_number(&fx.repo.id, 1) |
| 872 | .await |
| 873 | .expect("query") |
| 874 | .expect("run exists"); |
| 875 | assert!(run.config_error.is_none(), "unknown keys are not an error"); |
| 876 | let jobs = fx.state.store.jobs_for_run(&run.id).await.expect("jobs"); |
| 877 | assert_eq!(state_of(&jobs, "build"), Some(JobState::Queued)); |
| 878 | |
| 879 | for job in &jobs { |
| 880 | let log = std::fs::read_to_string(log_path(&fx.state.config.data_dir, &job.id)) |
| 881 | .expect("job log"); |
| 882 | assert!( |
| 883 | log.starts_with( |
| 884 | "[forge] warning: unknown key `future` ignored: this forge may be older than your ci.toml\n" |
| 885 | ), |
| 886 | "log was {log:?}" |
| 887 | ); |
| 888 | } |
| 889 | } |
| 890 | |
| 891 | #[tokio::test] |
| 892 | async fn no_file_means_no_run() { |
| 893 | let fx = fixture().await; |
| 894 | let oid = push(&fx, &[("README.md", "hello")], "refs/heads/main").await; |
| 895 | assert_eq!(runs_total(&fx).await, 0); |
| 896 | let statuses = fx |
| 897 | .state |
| 898 | .store |
| 899 | .statuses_for(&fx.repo.id, &oid) |
| 900 | .await |
| 901 | .expect("statuses"); |
| 902 | assert!(statuses.is_empty()); |
| 903 | } |
| 904 | |
| 905 | #[tokio::test] |
| 906 | async fn bad_file_gives_error_run_and_config_status() { |
| 907 | let fx = fixture().await; |
| 908 | let oid = push( |
| 909 | &fx, |
| 910 | &[(CONFIG_PATH, "[jobs.build\nimage = ")], |
| 911 | "refs/heads/main", |
| 912 | ) |
| 913 | .await; |
| 914 | let run = fx |
| 915 | .state |
| 916 | .store |
| 917 | .run_by_number(&fx.repo.id, 1) |
| 918 | .await |
| 919 | .expect("query") |
| 920 | .expect("run exists"); |
| 921 | assert_eq!(run.state, RunState::Error); |
| 922 | assert!(run.config_error.is_some()); |
| 923 | let jobs = fx.state.store.jobs_for_run(&run.id).await.expect("jobs"); |
| 924 | assert!(jobs.is_empty()); |
| 925 | |
| 926 | let statuses = fx |
| 927 | .state |
| 928 | .store |
| 929 | .statuses_for(&fx.repo.id, &oid) |
| 930 | .await |
| 931 | .expect("statuses"); |
| 932 | let config = status(&statuses, "ci/config").expect("ci/config status"); |
| 933 | assert_eq!(config.state, StatusState::Error); |
| 934 | assert!(!config.description.as_deref().unwrap_or("").is_empty()); |
| 935 | } |
| 936 | |
| 937 | |
| 938 | #[tokio::test] |
| 939 | async fn branch_and_tag_globs_select_runs() { |
| 940 | let fx = fixture().await; |
| 941 | |
| 942 | push(&fx, &[(CONFIG_PATH, CONFIG_GLOBS)], "refs/heads/main").await; |
| 943 | assert_eq!(runs_total(&fx).await, 0, "main is not in the globs"); |
| 944 | |
| 945 | push( |
| 946 | &fx, |
| 947 | &[(CONFIG_PATH, CONFIG_GLOBS)], |
| 948 | "refs/heads/release/1.0", |
| 949 | ) |
| 950 | .await; |
| 951 | assert_eq!(runs_total(&fx).await, 1); |
| 952 | let run = fx |
| 953 | .state |
| 954 | .store |
| 955 | .run_by_number(&fx.repo.id, 1) |
| 956 | .await |
| 957 | .expect("query") |
| 958 | .expect("run"); |
| 959 | assert_eq!(run.git_ref, "refs/heads/release/1.0"); |
| 960 | |
| 961 | |
| 962 | push(&fx, &[(CONFIG_PATH, CONFIG_TAGS)], "refs/tags/nightly").await; |
| 963 | assert_eq!(runs_total(&fx).await, 1, "nightly does not match v*"); |
| 964 | |
| 965 | push(&fx, &[(CONFIG_PATH, CONFIG_TAGS)], "refs/tags/v1.0").await; |
| 966 | assert_eq!(runs_total(&fx).await, 2); |
| 967 | let run = fx |
| 968 | .state |
| 969 | .store |
| 970 | .run_by_number(&fx.repo.id, 2) |
| 971 | .await |
| 972 | .expect("query") |
| 973 | .expect("run"); |
| 974 | assert_eq!(run.trigger, "tag"); |
| 975 | assert_eq!(run.git_ref, "refs/tags/v1.0"); |
| 976 | |
| 977 | |
| 978 | let head = commit(&fx.work, &[(CONFIG_PATH, CONFIG_TAGS)]); |
| 979 | git(&fx.work, &["tag", "-a", "v2.0", "-m", "v2.0"]); |
| 980 | let tag_obj = git(&fx.work, &["rev-parse", "v2.0"]); |
| 981 | assert_ne!(tag_obj, head); |
| 982 | land(&fx, &tag_obj, "refs/tags/v2.0"); |
| 983 | after_ref_update( |
| 984 | &fx.state, |
| 985 | &fx.repo, |
| 986 | &fx.owner.id, |
| 987 | "refs/tags/v2.0", |
| 988 | ZERO, |
| 989 | &tag_obj, |
| 990 | ) |
| 991 | .await |
| 992 | .expect("post update"); |
| 993 | assert_eq!(runs_total(&fx).await, 3); |
| 994 | let run = fx |
| 995 | .state |
| 996 | .store |
| 997 | .run_by_number(&fx.repo.id, 3) |
| 998 | .await |
| 999 | .expect("query") |
| 1000 | .expect("run"); |
| 1001 | assert_eq!(run.commit_oid, head); |
| 1002 | } |
| 1003 | |
| 1004 | |
| 1005 | |
| 1006 | async fn open_pull( |
| 1007 | fx: &Fixture, |
| 1008 | author_id: &str, |
| 1009 | head_repo_id: &str, |
| 1010 | branch: &str, |
| 1011 | head_oid: &str, |
| 1012 | ) -> PullRequest { |
| 1013 | let pr = fx |
| 1014 | .state |
| 1015 | .store |
| 1016 | .create_pull( |
| 1017 | &fx.repo.id, |
| 1018 | author_id, |
| 1019 | "Change", |
| 1020 | "", |
| 1021 | "main", |
| 1022 | head_repo_id, |
| 1023 | branch, |
| 1024 | head_oid, |
| 1025 | head_oid, |
| 1026 | ) |
| 1027 | .await |
| 1028 | .expect("create pull"); |
| 1029 | on_pull_event(&fx.state, &fx.repo, &pr, author_id).await; |
| 1030 | pr |
| 1031 | } |
| 1032 | |
| 1033 | |
| 1034 | |
| 1035 | |
| 1036 | #[tokio::test] |
| 1037 | async fn pull_requests_wait_for_approval_unless_the_author_writes_the_repo() { |
| 1038 | let fx = fixture().await; |
| 1039 | |
| 1040 | |
| 1041 | let fork_head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/feature-fork").await; |
| 1042 | let bob = fx |
| 1043 | .state |
| 1044 | .store |
| 1045 | .create_user("bob", None, "unused", false) |
| 1046 | .await |
| 1047 | .expect("user"); |
| 1048 | let fork = fx |
| 1049 | .state |
| 1050 | .store |
| 1051 | .create_repo(&bob.id, "proj", "", Visibility::Public, "main") |
| 1052 | .await |
| 1053 | .expect("fork"); |
| 1054 | let pr = open_pull(&fx, &fx.owner.id, &fork.id, "feature-fork", &fork_head).await; |
| 1055 | |
| 1056 | let run = fx |
| 1057 | .state |
| 1058 | .store |
| 1059 | .run_by_number(&fx.repo.id, 1) |
| 1060 | .await |
| 1061 | .expect("query") |
| 1062 | .expect("run"); |
| 1063 | assert_eq!(run.trigger, "pull_request"); |
| 1064 | assert_eq!(run.state, RunState::WaitingApproval, "fork"); |
| 1065 | assert_eq!(run.pull_number, Some(pr.issue.number)); |
| 1066 | |
| 1067 | let statuses = fx |
| 1068 | .state |
| 1069 | .store |
| 1070 | .statuses_for(&fx.repo.id, &fork_head) |
| 1071 | .await |
| 1072 | .expect("statuses"); |
| 1073 | let build = status(&statuses, "ci/build").expect("ci/build"); |
| 1074 | assert_eq!(build.state, StatusState::Pending); |
| 1075 | assert_eq!(build.description.as_deref(), Some("Waiting for approval")); |
| 1076 | |
| 1077 | |
| 1078 | let carol = fx |
| 1079 | .state |
| 1080 | .store |
| 1081 | .create_user("carol", None, "unused", false) |
| 1082 | .await |
| 1083 | .expect("user"); |
| 1084 | let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/feature-carol").await; |
| 1085 | open_pull(&fx, &carol.id, &fx.repo.id, "feature-carol", &head).await; |
| 1086 | let run = fx |
| 1087 | .state |
| 1088 | .store |
| 1089 | .run_by_number(&fx.repo.id, 2) |
| 1090 | .await |
| 1091 | .expect("query") |
| 1092 | .expect("run"); |
| 1093 | assert_eq!(run.state, RunState::WaitingApproval, "non-writer"); |
| 1094 | |
| 1095 | |
| 1096 | let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/feature-writer").await; |
| 1097 | open_pull(&fx, &fx.owner.id, &fx.repo.id, "feature-writer", &head).await; |
| 1098 | let run = fx |
| 1099 | .state |
| 1100 | .store |
| 1101 | .run_by_number(&fx.repo.id, 3) |
| 1102 | .await |
| 1103 | .expect("query") |
| 1104 | .expect("run"); |
| 1105 | assert_ne!(run.state, RunState::WaitingApproval, "writer"); |
| 1106 | } |
| 1107 | |
| 1108 | |
| 1109 | |
| 1110 | #[tokio::test] |
| 1111 | async fn manual_runs_use_the_branch_head_and_refuse_when_asked() { |
| 1112 | let fx = fixture().await; |
| 1113 | let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/main").await; |
| 1114 | let before = runs_total(&fx).await; |
| 1115 | let run = manual_run(&fx.state, &fx.repo, "main", &fx.owner.id) |
| 1116 | .await |
| 1117 | .expect("manual run"); |
| 1118 | assert_eq!(run.trigger, "manual"); |
| 1119 | assert_eq!(run.git_ref, "refs/heads/main"); |
| 1120 | assert_eq!(run.commit_oid, head); |
| 1121 | assert_eq!(runs_total(&fx).await, before + 1); |
| 1122 | |
| 1123 | push(&fx, &[(CONFIG_PATH, CONFIG_NO_MANUAL)], "refs/heads/quiet").await; |
| 1124 | let before = runs_total(&fx).await; |
| 1125 | assert!( |
| 1126 | manual_run(&fx.state, &fx.repo, "nope", &fx.owner.id) |
| 1127 | .await |
| 1128 | .is_err() |
| 1129 | ); |
| 1130 | let refused = manual_run(&fx.state, &fx.repo, "quiet", &fx.owner.id).await; |
| 1131 | assert!(matches!(refused, Err(forge_core::Error::Invalid(_)))); |
| 1132 | assert_eq!(runs_total(&fx).await, before); |
| 1133 | } |
| 1134 | |
| 1135 | #[tokio::test] |
| 1136 | async fn reaper_marks_lost_jobs_and_syncs_statuses() { |
| 1137 | let fx = fixture().await; |
| 1138 | let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/main").await; |
| 1139 | let runner = runner(&fx).await; |
| 1140 | let (job, _run, _token) = fx |
| 1141 | .state |
| 1142 | .store |
| 1143 | .claim_job(&runner) |
| 1144 | .await |
| 1145 | .expect("claim") |
| 1146 | .expect("a queued job"); |
| 1147 | assert_eq!(job.name, "build"); |
| 1148 | |
| 1149 | |
| 1150 | let reaped = reap_before(&fx.state, &stamp_after(Duration::from_secs(3600))).await; |
| 1151 | assert_eq!(reaped, 1); |
| 1152 | |
| 1153 | let job = fx |
| 1154 | .state |
| 1155 | .store |
| 1156 | .job_by_id(&job.id) |
| 1157 | .await |
| 1158 | .expect("query") |
| 1159 | .expect("job"); |
| 1160 | assert_eq!(job.state, JobState::Error); |
| 1161 | assert_eq!(job.message.as_deref(), Some("runner lost")); |
| 1162 | |
| 1163 | let statuses = fx |
| 1164 | .state |
| 1165 | .store |
| 1166 | .statuses_for(&fx.repo.id, &head) |
| 1167 | .await |
| 1168 | .expect("statuses"); |
| 1169 | let build = status(&statuses, "ci/build").expect("ci/build"); |
| 1170 | assert_eq!(build.state, StatusState::Error); |
| 1171 | } |
| 1172 | |
| 1173 | #[tokio::test] |
| 1174 | async fn purge_deletes_log_files() { |
| 1175 | let fx = fixture().await; |
| 1176 | push(&fx, &[(CONFIG_PATH, CONFIG_ONE_JOB)], "refs/heads/main").await; |
| 1177 | let runner = runner(&fx).await; |
| 1178 | let (job, _run, _token) = fx |
| 1179 | .state |
| 1180 | .store |
| 1181 | .claim_job(&runner) |
| 1182 | .await |
| 1183 | .expect("claim") |
| 1184 | .expect("a queued job"); |
| 1185 | |
| 1186 | fx.state |
| 1187 | .store |
| 1188 | .add_log_bytes(&job.id, 12) |
| 1189 | .await |
| 1190 | .expect("log bytes"); |
| 1191 | fx.state |
| 1192 | .store |
| 1193 | .finish_job(&job.id, JobState::Success, Some(0), None) |
| 1194 | .await |
| 1195 | .expect("finish"); |
| 1196 | |
| 1197 | let path = log_path(&fx.state.config.data_dir, &job.id); |
| 1198 | std::fs::create_dir_all(path.parent().expect("parent")).expect("log dir"); |
| 1199 | std::fs::write(&path, "build output\n").expect("write log"); |
| 1200 | |
| 1201 | |
| 1202 | let mut cfg = (*fx.state.config).clone(); |
| 1203 | cfg.ci.log_retention_days = 0; |
| 1204 | let mut state = fx.state.clone(); |
| 1205 | state.set_config(cfg); |
| 1206 | tokio::time::sleep(Duration::from_millis(1100)).await; |
| 1207 | |
| 1208 | let (logs, _artifacts) = purge_once(&state).await; |
| 1209 | assert_eq!(logs, 1); |
| 1210 | assert!(!path.exists(), "log file is deleted"); |
| 1211 | } |
| 1212 | |
| 1213 | const CONFIG_SUPERSEDE: &str = r#" |
| 1214 | [on] |
| 1215 | push = ["main"] |
| 1216 | cancel_superseded = true |
| 1217 | |
| 1218 | [jobs.build] |
| 1219 | image = "alpine:3" |
| 1220 | run = "make" |
| 1221 | "#; |
| 1222 | |
| 1223 | |
| 1224 | |
| 1225 | |
| 1226 | #[tokio::test] |
| 1227 | async fn a_newer_push_cancels_older_live_runs_unless_the_config_keeps_them() { |
| 1228 | let fx = fixture().await; |
| 1229 | |
| 1230 | let on = |config: &str, branch: &str| { |
| 1231 | config.replace("push = [\"main\"]", &format!("push = [\"{branch}\"]")) |
| 1232 | }; |
| 1233 | |
| 1234 | let cases: [(&str, String, bool, i64); 3] = [ |
| 1235 | ("default", on(CONFIG_ONE_JOB, "default"), true, 1), |
| 1236 | ("asked", on(CONFIG_SUPERSEDE, "asked"), true, 3), |
| 1237 | ( |
| 1238 | "kept", |
| 1239 | on( |
| 1240 | &CONFIG_SUPERSEDE |
| 1241 | .replace("cancel_superseded = true", "cancel_superseded = false"), |
| 1242 | "kept", |
| 1243 | ), |
| 1244 | false, |
| 1245 | 5, |
| 1246 | ), |
| 1247 | ]; |
| 1248 | for (branch, config, cancelled, first_number) in cases { |
| 1249 | let git_ref = format!("refs/heads/{branch}"); |
| 1250 | let case = format!("case {branch}"); |
| 1251 | push(&fx, &[(CONFIG_PATH, config.as_str())], &git_ref).await; |
| 1252 | push(&fx, &[("a.txt", "a")], &git_ref).await; |
| 1253 | let store = &fx.state.store; |
| 1254 | let first = store |
| 1255 | .run_by_number(&fx.repo.id, first_number) |
| 1256 | .await |
| 1257 | .unwrap() |
| 1258 | .unwrap(); |
| 1259 | let second = store |
| 1260 | .run_by_number(&fx.repo.id, first_number + 1) |
| 1261 | .await |
| 1262 | .unwrap() |
| 1263 | .unwrap(); |
| 1264 | let want = if cancelled { |
| 1265 | RunState::Cancelled |
| 1266 | } else { |
| 1267 | RunState::Queued |
| 1268 | }; |
| 1269 | assert_eq!(first.state, want, "{case}: the older run"); |
| 1270 | assert_eq!(second.state, RunState::Queued, "{case}: the newest run"); |
| 1271 | if cancelled { |
| 1272 | let jobs = store.jobs_for_run(&first.id).await.unwrap(); |
| 1273 | assert_eq!( |
| 1274 | state_of(&jobs, "build"), |
| 1275 | Some(JobState::Cancelled), |
| 1276 | "{case}" |
| 1277 | ); |
| 1278 | } |
| 1279 | } |
| 1280 | } |
| 1281 | |
| 1282 | #[tokio::test] |
| 1283 | async fn ignored_config_keys_are_stored_as_run_warnings() { |
| 1284 | let fx = fixture().await; |
| 1285 | let config = "[on]\npush = [\"main\"]\nwebhook = true\n\n[jobs.build]\nimage = \"alpine:3\"\nrun = \"make\"\n"; |
| 1286 | push(&fx, &[(CONFIG_PATH, config)], "refs/heads/main").await; |
| 1287 | let run = fx |
| 1288 | .state |
| 1289 | .store |
| 1290 | .run_by_number(&fx.repo.id, 1) |
| 1291 | .await |
| 1292 | .unwrap() |
| 1293 | .unwrap(); |
| 1294 | let warnings = fx.state.store.run_warnings(&run.id).await.unwrap(); |
| 1295 | assert_eq!(warnings.len(), 1); |
| 1296 | assert!(warnings[0].contains("`on.webhook`"), "{warnings:?}"); |
| 1297 | } |
| 1298 | } |