use forge_ci::config::{CiConfig, Event, MAX_CONFIG_BYTES, parse_config}; use forge_core::authz::{Action, authorize}; use forge_core::ci::{CiRun, NewJob, NewRun}; use forge_core::store::commit_status::StatusState; use forge_core::{PullRequest, Repo}; use forge_git::browse::{BlobData, peel_to_commit, read_blob, resolve_commit}; use tokio::io::AsyncWriteExt; use super::api::fit_to_cap; use super::{log_path, publish, sync_run_statuses}; use crate::internal::is_zero_oid; use crate::state::AppState; pub const CONFIG_PATH: &str = ".forge/ci.toml"; const MAX_WARNING_LINES: usize = 20; const MIB: u64 = 1024 * 1024; type PlannedJob = (String, String, Vec); pub(super) enum Loaded { Missing, Invalid(String), Valid(CiConfig), } struct Planned { jobs: Vec, config_error: Option, warnings: Vec, cancel_superseded: bool, } struct Request<'a> { repo: &'a Repo, trigger: &'static str, git_ref: &'a str, commit: &'a str, pull_number: Option, actor_id: &'a str, needs_approval: bool, } pub async fn on_ref_update( state: &AppState, repo: &Repo, actor_id: &str, refname: &str, new_oid: &str, ) { if !state.live().ci.enabled || is_zero_oid(new_oid) { return; } let (trigger, event) = if let Some(branch) = refname.strip_prefix("refs/heads/") { ("push", Event::Push { branch }) } else if let Some(tag) = refname.strip_prefix("refs/tags/") { ("tag", Event::Tag { tag }) } else { return; }; if let Err(e) = schedule_ref(state, repo, actor_id, trigger, refname, &event, new_oid).await { tracing::error!(error = %e, repo_id = %repo.id, refname, "ci: scheduling a push failed"); } } async fn schedule_ref( state: &AppState, repo: &Repo, actor_id: &str, trigger: &'static str, refname: &str, event: &Event<'_>, new_oid: &str, ) -> forge_core::Result<()> { let Some(commit) = peeled_commit(state, &repo.id, new_oid).await else { return Ok(()); }; let loaded = load(state, &repo.id, &commit).await; let Some(planned) = plan_for(loaded, event)? else { return Ok(()); }; let run = create( state, Request { repo, trigger, git_ref: refname, commit: &commit, pull_number: None, actor_id, needs_approval: false, }, &planned, ) .await?; if planned.cancel_superseded && trigger == "push" { cancel_superseded_runs(state, &run).await?; } Ok(()) } pub async fn on_pull_event(state: &AppState, repo: &Repo, pull: &PullRequest, actor_id: &str) { if !state.live().ci.enabled { return; } if let Err(e) = pull_run(state, repo, pull, actor_id).await { tracing::error!(error = %e, repo_id = %repo.id, number = pull.issue.number, "ci: scheduling a pull request failed"); } } async fn pull_run( state: &AppState, repo: &Repo, pull: &PullRequest, actor_id: &str, ) -> forge_core::Result<()> { let loaded = load(state, &repo.id, &pull.head_oid).await; let Some(planned) = plan_for(loaded, &Event::PullRequest)? else { return Ok(()); }; let needs_approval = needs_approval(state, repo, pull).await?; let git_ref = format!("refs/pull/{}/head", pull.issue.number); create( state, Request { repo, trigger: "pull_request", git_ref: &git_ref, commit: &pull.head_oid, pull_number: Some(pull.issue.number), actor_id, needs_approval, }, &planned, ) .await?; Ok(()) } pub async fn manual_run( state: &AppState, repo: &Repo, branch: &str, actor_id: &str, ) -> forge_core::Result { if !state.live().ci.enabled { return Err(forge_core::Error::Invalid( "CI is disabled on this instance".into(), )); } let git_ref = format!("refs/heads/{branch}"); let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, &repo.id) .map_err(|e| forge_core::Error::Git(e.to_string()))?; let short = branch.to_owned(); let Some(commit) = blocking(move || resolve_commit(&repo_dir, &short)).await? else { return Err(forge_core::Error::NotFound); }; let loaded = load(state, &repo.id, &commit).await; if matches!(loaded, Loaded::Missing) { return Err(forge_core::Error::Invalid( "this branch has no .forge/ci.toml".into(), )); } let Some(planned) = plan_for(loaded, &Event::Manual)? else { return Err(forge_core::Error::Invalid( "manual runs are not enabled in .forge/ci.toml".into(), )); }; create( state, Request { repo, trigger: "manual", git_ref: &git_ref, commit: &commit, pull_number: None, actor_id, needs_approval: false, }, &planned, ) .await } pub(super) async fn default_head_config(state: &AppState, repo: &Repo) -> Option<(String, Loaded)> { let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).ok()?; let short = repo.default_branch.clone(); let commit = match blocking(move || resolve_commit(&repo_dir, &short)).await { Ok(commit) => commit?, Err(e) => { tracing::error!(error = %e, repo_id = %repo.id, "ci: resolving the default branch failed"); return None; } }; let loaded = load(state, &repo.id, &commit).await; Some((commit, loaded)) } pub async fn schedules_of(state: &AppState, repo: &Repo) -> Vec { match default_head_config(state, repo).await { Some((_, Loaded::Valid(cfg))) => cfg.on.schedule, _ => Vec::new(), } } pub(super) async fn scheduled_run( state: &AppState, repo: &Repo, commit: &str, loaded: Loaded, ) -> forge_core::Result> { let Some(planned) = plan_for(loaded, &Event::Schedule)? else { return Ok(None); }; let git_ref = format!("refs/heads/{}", repo.default_branch); let run = create( state, Request { repo, trigger: "schedule", git_ref: &git_ref, commit, pull_number: None, actor_id: &repo.owner_id, needs_approval: false, }, &planned, ) .await?; Ok(Some(run)) } pub async fn merge_queue_run( state: &AppState, repo: &Repo, test_ref: &str, branch: &str, commit: &str, actor_id: &str, pull_number: i64, ) -> forge_core::Result> { if !state.live().ci.enabled { return Ok(None); } let loaded = load(state, &repo.id, commit).await; let Some(planned) = plan_for(loaded, &Event::MergeQueue { branch })? else { return Ok(None); }; let run = create( state, Request { repo, trigger: "merge_queue", git_ref: test_ref, commit, pull_number: Some(pull_number), actor_id, needs_approval: false, }, &planned, ) .await?; Ok(Some(run)) } async fn create( state: &AppState, req: Request<'_>, planned: &Planned, ) -> forge_core::Result { let config_error = planned.config_error.as_deref(); let warnings = planned.warnings.as_slice(); let new_jobs: Vec> = planned .jobs .iter() .map(|(name, spec_json, needs)| NewJob { name, spec_json, needs: needs.as_slice(), }) .collect(); let run = state .store .create_run( &NewRun { repo_id: &req.repo.id, trigger: req.trigger, git_ref: req.git_ref, commit_oid: req.commit, pull_number: req.pull_number, actor_id: req.actor_id, needs_approval: req.needs_approval, config_error, }, &new_jobs, ) .await?; state.ci_live.bump_repo(&run.repo_id); state.store.set_run_warnings(&run.id, warnings).await?; note_warnings(state, &run, warnings).await?; if let Some(message) = config_error { let url = format!( "{}/{}/{}/ci/runs/{}", state.config.base_url.trim_end_matches('/'), req.repo.owner_name, req.repo.name, run.number ); publish( state, req.repo, &run, "ci/config", StatusState::Error, message, &url, ) .await; } if sync_run_statuses(state, &run).await? { state.ci_waker.notify_waiters(); } Ok(run) } async fn cancel_superseded_runs(state: &AppState, run: &CiRun) -> forge_core::Result<()> { let older = state .store .superseded_candidates(&run.repo_id, &run.git_ref, &run.commit_oid) .await?; for old in older.into_iter().filter(|old| old.number < run.number) { let before = state.store.jobs_for_run(&old.id).await?; state.store.request_cancel(&old.id).await?; if let Err(e) = crate::ci::after_change(state, &old.id, &before).await { tracing::error!(error = %e, run_id = %old.id, "ci: syncing a superseded run failed"); } } Ok(()) } async fn note_warnings( state: &AppState, run: &CiRun, warnings: &[String], ) -> forge_core::Result<()> { if warnings.is_empty() { return Ok(()); } let mut text = String::new(); for warning in warnings { tracing::warn!(run_id = %run.id, repo_id = %run.repo_id, "ci: {warning}"); } for warning in warnings.iter().take(MAX_WARNING_LINES) { text.push_str(&format!("[forge] warning: {warning}\n")); } let cap = state.live().ci.max_log_mb.saturating_mul(MIB); for job in state.store.jobs_for_run(&run.id).await? { let path = log_path(&state.config.data_dir, &job.id); let current = match tokio::fs::metadata(&path).await { Ok(meta) => meta.len(), Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, Err(e) => { tracing::error!(error = %e, job_id = %job.id, "ci: reading the job log failed"); continue; } }; let bytes = fit_to_cap(current, cap, text.as_bytes()); if bytes.is_empty() { continue; } let written: std::io::Result<()> = async { if let Some(parent) = path.parent() { tokio::fs::create_dir_all(parent).await?; } let mut file = tokio::fs::OpenOptions::new() .create(true) .append(true) .open(&path) .await?; file.write_all(&bytes).await?; file.flush().await } .await; if let Err(e) = written { tracing::error!(error = %e, job_id = %job.id, "ci: writing the job log failed"); continue; } if let Err(e) = state.store.add_log_bytes(&job.id, bytes.len() as i64).await { tracing::error!(error = %e, job_id = %job.id, "ci: counting the job log bytes failed"); continue; } state.ci_live.bump_job(&job.id); } Ok(()) } fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result> { match loaded { Loaded::Missing => Ok(None), Loaded::Invalid(message) => Ok(Some(Planned { jobs: Vec::new(), config_error: Some(message), warnings: Vec::new(), cancel_superseded: false, })), Loaded::Valid(cfg) => { if !cfg.triggered_by(event) { return Ok(None); } Ok(Some(Planned { jobs: plan_jobs(&cfg)?, config_error: None, warnings: cfg.warnings.clone(), cancel_superseded: cfg.on.cancel_superseded, })) } } } fn plan_jobs(cfg: &CiConfig) -> forge_core::Result> { let mut jobs = Vec::new(); for name in cfg.job_order() { let Some(spec) = cfg.jobs.get(name) else { continue; }; let spec_json = serde_json::to_string(spec).map_err(|e| forge_core::Error::Invalid(e.to_string()))?; jobs.push((name.to_owned(), spec_json, spec.needs.clone())); } Ok(jobs) } pub async fn config_at(state: &AppState, repo_id: &str, commit: &str) -> Option { match load(state, repo_id, commit).await { Loaded::Valid(config) => Some(config), Loaded::Missing | Loaded::Invalid(_) => None, } } async fn peeled_commit(state: &AppState, repo_id: &str, oid: &str) -> Option { let dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) { Ok(path) => path, Err(e) => { tracing::error!(error = %e, repo_id, "ci: bad repo path"); return None; } }; let rev = oid.to_owned(); match blocking(move || peel_to_commit(&dir, &rev)).await { Ok(Some(commit)) => Some(commit), Ok(None) => None, Err(e) => { tracing::error!(error = %e, repo_id, oid, "ci: peeling the pushed ref failed"); None } } } async fn read_config( state: &AppState, repo_id: &str, commit: &str, ) -> forge_core::Result> { let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, repo_id) .map_err(|e| forge_core::Error::Git(e.to_string()))?; let (dir, rev) = (repo_dir, commit.to_owned()); blocking(move || read_blob(&dir, &rev, CONFIG_PATH, MAX_CONFIG_BYTES)).await } async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded { match read_config(state, repo_id, commit).await { Ok(blob) => loaded_from(blob), Err(e) => { tracing::error!(error = %e, repo_id, commit, "ci: reading the workflow failed"); Loaded::Invalid(format!("could not read {CONFIG_PATH}")) } } } fn loaded_from(blob: Option) -> Loaded { let Some(blob) = blob else { return Loaded::Missing; }; if blob.truncated { return Loaded::Invalid(format!("{CONFIG_PATH} is larger than 64 KiB")); } if blob.is_binary { return Loaded::Invalid(format!("{CONFIG_PATH} is not text")); } let Ok(text) = String::from_utf8(blob.data) else { return Loaded::Invalid(format!("{CONFIG_PATH} is not valid UTF-8")); }; match parse_config(&text) { Ok(cfg) => Loaded::Valid(cfg), Err(e) => Loaded::Invalid(e.to_string()), } } pub async fn workflow_name(state: &AppState, repo_id: &str, commit: &str) -> Option { match load(state, repo_id, commit).await { Loaded::Valid(cfg) => cfg .name .map(|name| name.trim().to_owned()) .filter(|name| !name.is_empty()), Loaded::Missing | Loaded::Invalid(_) => None, } } async fn needs_approval( state: &AppState, repo: &Repo, pull: &PullRequest, ) -> forge_core::Result { if pull.head_repo_id.as_deref() != Some(repo.id.as_str()) { return Ok(true); } let Some(author) = state.store.user_by_id(&pull.issue.author_id).await? else { return Ok(true); }; if author.is_org() { return Ok(true); } let role = state.store.collaborator_role(&repo.id, &author.id).await?; let org_role = state .store .org_repo_role(&repo.owner_id, &author.id, &repo.id) .await?; Ok(authorize(Some(&author), repo, role, org_role, Action::Write).is_err()) } async fn blocking(work: F) -> forge_core::Result where F: FnOnce() -> forge_git::Result + Send + 'static, T: Send + 'static, { match tokio::task::spawn_blocking(work).await { Ok(Ok(value)) => Ok(value), Ok(Err(e)) => Err(forge_core::Error::Git(e.to_string())), Err(e) => Err(forge_core::Error::Git(format!("git task failed: {e}"))), } } #[cfg(test)] pub(super) mod tests { use std::path::{Path, PathBuf}; use std::time::Duration; use forge_core::ci::{CiJob, CiRunner, JobState, RunState}; use forge_core::store::commit_status::{CommitStatus, StatusState}; use forge_core::time::stamp_after; use forge_core::{NewPull, User, Visibility}; use forge_git::repo::{init_bare, repo_path}; use tempfile::TempDir; use super::*; use crate::ci::log_path; use crate::ci::reaper::{purge_once, reap_before}; use crate::post_update::after_ref_update; use crate::test_support::test_state; pub(in crate::ci) const ZERO: &str = "0000000000000000000000000000000000000000"; const CONFIG: &str = r#" [on] push = ["main"] pull_request = true [jobs.build] image = "alpine:3" run = "make" [jobs.test] image = "alpine:3" run = "make test" needs = ["build"] "#; const CONFIG_GLOBS: &str = r#" [on] push = ["release/*"] [jobs.build] image = "alpine:3" run = "make" "#; pub(in crate::ci) const CONFIG_TAGS: &str = r#" [on] push = [] tags = ["v*"] [jobs.build] image = "alpine:3" run = "make" "#; const CONFIG_ONE_JOB: &str = r#" [on] push = ["main"] [jobs.build] image = "alpine:3" run = "make" "#; const CONFIG_NO_MANUAL: &str = r#" [on] push = ["main"] manual = false [jobs.build] image = "alpine:3" run = "make" "#; pub(in crate::ci) fn git(dir: &Path, args: &[&str]) -> String { let out = std::process::Command::new("git") .arg("-C") .arg(dir) .args(args) .env("GIT_AUTHOR_NAME", "test") .env("GIT_AUTHOR_EMAIL", "test@example.com") .env("GIT_COMMITTER_NAME", "test") .env("GIT_COMMITTER_EMAIL", "test@example.com") .output() .expect("git runs"); assert!( out.status.success(), "git {args:?} failed: {}", String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout).trim().to_string() } pub(in crate::ci) struct Fixture { pub(in crate::ci) _tmp: TempDir, pub(in crate::ci) state: AppState, pub(in crate::ci) repo: Repo, pub(in crate::ci) owner: User, pub(in crate::ci) bare: PathBuf, pub(in crate::ci) work: PathBuf, } pub(in crate::ci) async fn fixture() -> Fixture { let tmp = tempfile::tempdir().expect("tempdir"); let state = test_state(tmp.path()).await; let owner = state .store .create_user("tahinli", None, "unused", false) .await .expect("user"); let repo = state .store .create_repo(&owner.id, "proj", "", Visibility::Private, "main") .await .expect("repo"); let bare = repo_path(&state.git.data_dir, &repo.id).expect("repo path"); init_bare(&state.git, &bare, "main") .await .expect("init bare"); let work = tmp.path().join("work"); git(tmp.path(), &["init", "-b", "main", "work"]); Fixture { _tmp: tmp, state, repo, owner, bare, work, } } pub(in crate::ci) fn commit(work: &Path, files: &[(&str, &str)]) -> String { for (path, text) in files { let full = work.join(path); if let Some(parent) = full.parent() { std::fs::create_dir_all(parent).expect("dirs"); } std::fs::write(&full, text).expect("write"); git(work, &["add", path]); } git(work, &["commit", "--allow-empty", "-m", "change"]); git(work, &["rev-parse", "HEAD"]) } pub(in crate::ci) fn land(fx: &Fixture, oid: &str, refname: &str) { let work = fx.work.to_str().expect("utf8 path"); git( &fx.bare, &["fetch", "--no-tags", work, &format!("+{oid}:{refname}")], ); } pub(in crate::ci) async fn push(fx: &Fixture, files: &[(&str, &str)], refname: &str) -> String { let oid = commit(&fx.work, files); land(fx, &oid, refname); after_ref_update(&fx.state, &fx.repo, &fx.owner.id, refname, ZERO, &oid) .await .expect("post update"); oid } fn status<'a>(statuses: &'a [CommitStatus], context: &str) -> Option<&'a CommitStatus> { statuses.iter().find(|s| s.context == context) } fn state_of(jobs: &[CiJob], name: &str) -> Option { jobs.iter().find(|j| j.name == name).map(|j| j.state) } pub(in crate::ci) async fn runs_total(fx: &Fixture) -> u64 { fx.state .store .list_runs(&fx.repo.id, 1, 50) .await .expect("list runs") .1 } async fn runner(fx: &Fixture) -> CiRunner { let token = fx .state .store .create_registration_token(&fx.owner.id, 24) .await .expect("token"); let (runner, _secret) = fx .state .store .register_runner(&token, "runner-1", &[]) .await .expect("register"); runner } #[tokio::test] async fn push_with_config_creates_run_and_pending_statuses() { let fx = fixture().await; let oid = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/main").await; let run = fx .state .store .run_by_number(&fx.repo.id, 1) .await .expect("query") .expect("run exists"); assert_eq!(run.trigger, "push"); assert_eq!(run.git_ref, "refs/heads/main"); assert_eq!(run.commit_oid, oid); assert!(run.config_error.is_none()); let jobs = fx.state.store.jobs_for_run(&run.id).await.expect("jobs"); assert_eq!(state_of(&jobs, "build"), Some(JobState::Queued)); assert_eq!(state_of(&jobs, "test"), Some(JobState::Blocked)); let statuses = fx .state .store .statuses_for(&fx.repo.id, &oid) .await .expect("statuses"); let build = status(&statuses, "ci/build").expect("ci/build status"); assert_eq!(build.state, StatusState::Pending); let url = build.target_url.clone().unwrap_or_default(); let job = jobs.iter().find(|j| j.name == "build").expect("build job"); assert_eq!( url, format!("https://forge.test/tahinli/proj/ci/jobs/{}", job.id) ); let test = status(&statuses, "ci/test").expect("ci/test status"); assert_eq!(test.state, StatusState::Pending); } #[tokio::test] async fn unknown_config_keys_still_run_and_warn_in_each_job_log() { let fx = fixture().await; let text = format!("{CONFIG_ONE_JOB}\n[future]\nx = 1\n"); push(&fx, &[(CONFIG_PATH, text.as_str())], "refs/heads/main").await; let run = fx .state .store .run_by_number(&fx.repo.id, 1) .await .expect("query") .expect("run exists"); assert!(run.config_error.is_none(), "unknown keys are not an error"); let jobs = fx.state.store.jobs_for_run(&run.id).await.expect("jobs"); assert_eq!(state_of(&jobs, "build"), Some(JobState::Queued)); for job in &jobs { let log = std::fs::read_to_string(log_path(&fx.state.config.data_dir, &job.id)) .expect("job log"); assert!( log.starts_with( "[forge] warning: unknown key `future` ignored: this forge may be older than your ci.toml\n" ), "log was {log:?}" ); } } #[tokio::test] async fn no_file_means_no_run() { let fx = fixture().await; let oid = push(&fx, &[("README.md", "hello")], "refs/heads/main").await; assert_eq!(runs_total(&fx).await, 0); let statuses = fx .state .store .statuses_for(&fx.repo.id, &oid) .await .expect("statuses"); assert!(statuses.is_empty()); } #[tokio::test] async fn bad_file_gives_error_run_and_config_status() { let fx = fixture().await; let oid = push( &fx, &[(CONFIG_PATH, "[jobs.build\nimage = ")], "refs/heads/main", ) .await; let run = fx .state .store .run_by_number(&fx.repo.id, 1) .await .expect("query") .expect("run exists"); assert_eq!(run.state, RunState::Error); assert!(run.config_error.is_some()); let jobs = fx.state.store.jobs_for_run(&run.id).await.expect("jobs"); assert!(jobs.is_empty()); let statuses = fx .state .store .statuses_for(&fx.repo.id, &oid) .await .expect("statuses"); let config = status(&statuses, "ci/config").expect("ci/config status"); assert_eq!(config.state, StatusState::Error); assert!(!config.description.as_deref().unwrap_or("").is_empty()); } #[tokio::test] async fn branch_and_tag_globs_select_runs() { let fx = fixture().await; push(&fx, &[(CONFIG_PATH, CONFIG_GLOBS)], "refs/heads/main").await; assert_eq!(runs_total(&fx).await, 0, "main is not in the globs"); push( &fx, &[(CONFIG_PATH, CONFIG_GLOBS)], "refs/heads/release/1.0", ) .await; assert_eq!(runs_total(&fx).await, 1); let run = fx .state .store .run_by_number(&fx.repo.id, 1) .await .expect("query") .expect("run"); assert_eq!(run.git_ref, "refs/heads/release/1.0"); push(&fx, &[(CONFIG_PATH, CONFIG_TAGS)], "refs/tags/nightly").await; assert_eq!(runs_total(&fx).await, 1, "nightly does not match v*"); push(&fx, &[(CONFIG_PATH, CONFIG_TAGS)], "refs/tags/v1.0").await; assert_eq!(runs_total(&fx).await, 2); let run = fx .state .store .run_by_number(&fx.repo.id, 2) .await .expect("query") .expect("run"); assert_eq!(run.trigger, "tag"); assert_eq!(run.git_ref, "refs/tags/v1.0"); let head = commit(&fx.work, &[(CONFIG_PATH, CONFIG_TAGS)]); git(&fx.work, &["tag", "-a", "v2.0", "-m", "v2.0"]); let tag_obj = git(&fx.work, &["rev-parse", "v2.0"]); assert_ne!(tag_obj, head); land(&fx, &tag_obj, "refs/tags/v2.0"); after_ref_update( &fx.state, &fx.repo, &fx.owner.id, "refs/tags/v2.0", ZERO, &tag_obj, ) .await .expect("post update"); assert_eq!(runs_total(&fx).await, 3); let run = fx .state .store .run_by_number(&fx.repo.id, 3) .await .expect("query") .expect("run"); assert_eq!(run.commit_oid, head); } async fn open_pull( fx: &Fixture, author_id: &str, head_repo_id: &str, branch: &str, head_oid: &str, ) -> PullRequest { let pr = fx .state .store .create_pull(&NewPull { repo_id: &fx.repo.id, author_id, title: "Change", body: "", base_branch: "main", head_repo_id, head_branch: branch, head_oid, base_oid: head_oid, }) .await .expect("create pull"); on_pull_event(&fx.state, &fx.repo, &pr, author_id).await; pr } #[tokio::test] async fn pull_requests_wait_for_approval_unless_the_author_writes_the_repo() { let fx = fixture().await; let fork_head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/feature-fork").await; let bob = fx .state .store .create_user("bob", None, "unused", false) .await .expect("user"); let fork = fx .state .store .create_repo(&bob.id, "proj", "", Visibility::Public, "main") .await .expect("fork"); let pr = open_pull(&fx, &fx.owner.id, &fork.id, "feature-fork", &fork_head).await; let run = fx .state .store .run_by_number(&fx.repo.id, 1) .await .expect("query") .expect("run"); assert_eq!(run.trigger, "pull_request"); assert_eq!(run.state, RunState::WaitingApproval, "fork"); assert_eq!(run.pull_number, Some(pr.issue.number)); let statuses = fx .state .store .statuses_for(&fx.repo.id, &fork_head) .await .expect("statuses"); let build = status(&statuses, "ci/build").expect("ci/build"); assert_eq!(build.state, StatusState::Pending); assert_eq!(build.description.as_deref(), Some("Waiting for approval")); let carol = fx .state .store .create_user("carol", None, "unused", false) .await .expect("user"); let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/feature-carol").await; open_pull(&fx, &carol.id, &fx.repo.id, "feature-carol", &head).await; let run = fx .state .store .run_by_number(&fx.repo.id, 2) .await .expect("query") .expect("run"); assert_eq!(run.state, RunState::WaitingApproval, "non-writer"); let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/feature-writer").await; open_pull(&fx, &fx.owner.id, &fx.repo.id, "feature-writer", &head).await; let run = fx .state .store .run_by_number(&fx.repo.id, 3) .await .expect("query") .expect("run"); assert_ne!(run.state, RunState::WaitingApproval, "writer"); } #[tokio::test] async fn manual_runs_use_the_branch_head_and_refuse_when_asked() { let fx = fixture().await; let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/main").await; let before = runs_total(&fx).await; let run = manual_run(&fx.state, &fx.repo, "main", &fx.owner.id) .await .expect("manual run"); assert_eq!(run.trigger, "manual"); assert_eq!(run.git_ref, "refs/heads/main"); assert_eq!(run.commit_oid, head); assert_eq!(runs_total(&fx).await, before + 1); push(&fx, &[(CONFIG_PATH, CONFIG_NO_MANUAL)], "refs/heads/quiet").await; let before = runs_total(&fx).await; assert!( manual_run(&fx.state, &fx.repo, "nope", &fx.owner.id) .await .is_err() ); let refused = manual_run(&fx.state, &fx.repo, "quiet", &fx.owner.id).await; assert!(matches!(refused, Err(forge_core::Error::Invalid(_)))); assert_eq!(runs_total(&fx).await, before); } #[tokio::test] async fn reaper_marks_lost_jobs_and_syncs_statuses() { let fx = fixture().await; let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/main").await; let runner = runner(&fx).await; let (job, _run, _token) = fx .state .store .claim_job(&runner) .await .expect("claim") .expect("a queued job"); assert_eq!(job.name, "build"); let reaped = reap_before(&fx.state, &stamp_after(Duration::from_secs(3600))).await; assert_eq!(reaped, 1); let job = fx .state .store .job_by_id(&job.id) .await .expect("query") .expect("job"); assert_eq!(job.state, JobState::Error); assert_eq!(job.message.as_deref(), Some("runner lost")); let statuses = fx .state .store .statuses_for(&fx.repo.id, &head) .await .expect("statuses"); let build = status(&statuses, "ci/build").expect("ci/build"); assert_eq!(build.state, StatusState::Error); } #[tokio::test] async fn purge_deletes_log_files() { let fx = fixture().await; push(&fx, &[(CONFIG_PATH, CONFIG_ONE_JOB)], "refs/heads/main").await; let runner = runner(&fx).await; let (job, _run, _token) = fx .state .store .claim_job(&runner) .await .expect("claim") .expect("a queued job"); fx.state .store .add_log_bytes(&job.id, 12) .await .expect("log bytes"); fx.state .store .finish_job(&job.id, JobState::Success, Some(0), None) .await .expect("finish"); let path = log_path(&fx.state.config.data_dir, &job.id); std::fs::create_dir_all(path.parent().expect("parent")).expect("log dir"); std::fs::write(&path, "build output\n").expect("write log"); let mut cfg = (*fx.state.config).clone(); cfg.ci.log_retention_days = 0; let mut state = fx.state.clone(); state.set_config(cfg); tokio::time::sleep(Duration::from_millis(1100)).await; let (logs, _artifacts) = purge_once(&state).await; assert_eq!(logs, 1); assert!(!path.exists(), "log file is deleted"); } const CONFIG_SUPERSEDE: &str = r#" [on] push = ["main"] cancel_superseded = true [jobs.build] image = "alpine:3" run = "make" "#; #[tokio::test] async fn a_newer_push_cancels_older_live_runs_unless_the_config_keeps_them() { let fx = fixture().await; let on = |config: &str, branch: &str| { config.replace("push = [\"main\"]", &format!("push = [\"{branch}\"]")) }; let cases: [(&str, String, bool, i64); 3] = [ ("default", on(CONFIG_ONE_JOB, "default"), true, 1), ("asked", on(CONFIG_SUPERSEDE, "asked"), true, 3), ( "kept", on( &CONFIG_SUPERSEDE .replace("cancel_superseded = true", "cancel_superseded = false"), "kept", ), false, 5, ), ]; for (branch, config, cancelled, first_number) in cases { let git_ref = format!("refs/heads/{branch}"); let case = format!("case {branch}"); push(&fx, &[(CONFIG_PATH, config.as_str())], &git_ref).await; push(&fx, &[("a.txt", "a")], &git_ref).await; let store = &fx.state.store; let first = store .run_by_number(&fx.repo.id, first_number) .await .unwrap() .unwrap(); let second = store .run_by_number(&fx.repo.id, first_number + 1) .await .unwrap() .unwrap(); let want = if cancelled { RunState::Cancelled } else { RunState::Queued }; assert_eq!(first.state, want, "{case}: the older run"); assert_eq!(second.state, RunState::Queued, "{case}: the newest run"); if cancelled { let jobs = store.jobs_for_run(&first.id).await.unwrap(); assert_eq!( state_of(&jobs, "build"), Some(JobState::Cancelled), "{case}" ); } } } #[tokio::test] async fn ignored_config_keys_are_stored_as_run_warnings() { let fx = fixture().await; let config = "[on]\npush = [\"main\"]\nwebhook = true\n\n[jobs.build]\nimage = \"alpine:3\"\nrun = \"make\"\n"; push(&fx, &[(CONFIG_PATH, config)], "refs/heads/main").await; let run = fx .state .store .run_by_number(&fx.repo.id, 1) .await .unwrap() .unwrap(); let warnings = fx.state.store.run_warnings(&run.id).await.unwrap(); assert_eq!(warnings.len(), 1); assert!(warnings[0].contains("`on.webhook`"), "{warnings:?}"); } }