use std::time::Duration; use forge_ci::config::DEFAULT_TIMEOUT_MINUTES; use forge_core::merge_queue::{QueueEntry, QueueState, test_ref_name}; use forge_core::protection::effective; use forge_core::store::commit_status::StatusState; use forge_core::time::stamp_ago; use forge_core::{Action, IssueState, MergeStyle, Mergeable, PullRequest, Repo, User, authorize}; use forge_git::browse::default_branch_commit; use forge_git::pulls::{set_ref, update_ref_cas}; use forge_git::repo::repo_path; use crate::ci::schedule::{config_at, merge_queue_run}; use crate::merge::{ ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, finish_merge, merge_commit, merge_gate, }; use crate::notify::{self, Activity}; use crate::state::AppState; pub async fn requires_queue( state: &AppState, repo: &Repo, branch: &str, ) -> forge_core::Result { let rules = state.store.list_branch_rules(&repo.id).await?; Ok(effective(&rules, &repo.default_branch, branch).require_merge_queue) } pub async fn enqueue( state: &AppState, repo: &Repo, pr: &PullRequest, user: &User, style: MergeStyle, ) -> forge_core::Result> { let gate = merge_gate(state, repo, pr).await?; if let Some(code) = gate .blockers() .into_iter() .find(|code| *code != ERR_NOT_UP_TO_DATE) { return Ok(Err(code)); } if pr.mergeable == Mergeable::Conflict { return Ok(Err(ERR_CONFLICT)); } match state .store .enqueue_pull( &repo.id, &pr.base_branch, &pr.issue.id, pr.issue.number, style, &user.id, ) .await { Ok(entry) => { notify_entry(state, repo, &entry); advance(state, repo, &pr.base_branch).await; Ok(Ok(entry)) } Err(forge_core::Error::Conflict(_)) => Ok(Err(ERR_QUEUE_ALREADY)), Err(e) => Err(e), } } pub async fn remove(state: &AppState, repo: &Repo, entry: &QueueEntry, reason: &str) { if let Err(e) = remove_entry(state, repo, entry, reason).await { tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed"); } } async fn remove_entry( state: &AppState, repo: &Repo, entry: &QueueEntry, reason: &str, ) -> forge_core::Result<()> { if state .store .queue_finish(&entry.id, QueueState::Removed, reason) .await? { notify_entry(state, repo, entry); } Ok(()) } pub async fn drop_pull(state: &AppState, repo: &Repo, issue_id: &str, reason: &str) { match state.store.queue_entry_for_pull(issue_id).await { Ok(Some(entry)) => { remove(state, repo, &entry, reason).await; advance(state, repo, &entry.branch).await; } Ok(None) => {} Err(e) => { tracing::error!(error = %e, repo_id = %repo.id, "merge queue: looking up a pull request failed"); } } } pub async fn on_status(state: &AppState, repo: &Repo, sha: &str) { let entries = match state.store.queue_testing_on(&repo.id, sha).await { Ok(entries) => entries, Err(e) => { tracing::error!(error = %e, repo_id = %repo.id, "merge queue: listing candidates failed"); return; } }; for entry in entries { match evaluate(state, repo, &entry.id).await { Ok(true) => advance(state, repo, &entry.branch).await, Ok(false) => {} Err(e) => { tracing::error!(error = %e, repo_id = %repo.id, "merge queue: evaluating a candidate failed"); } } } } pub async fn advance(state: &AppState, repo: &Repo, branch: &str) { if let Err(e) = advance_inner(state, repo, branch).await { tracing::error!(error = %e, repo_id = %repo.id, branch, "merge queue: advancing failed"); } } async fn advance_inner(state: &AppState, repo: &Repo, branch: &str) -> forge_core::Result<()> { loop { let entries = state.store.queue_for_branch(&repo.id, branch).await?; if entries .iter() .any(|e| matches!(e.state, QueueState::Testing | QueueState::Merging)) { return Ok(()); } let Some(head) = entries.into_iter().next() else { return Ok(()); }; let Some(pr) = state .store .pull_by_number(&repo.id, head.pull_number) .await? else { remove(state, repo, &head, "removed").await; continue; }; if let Some(reason) = unready(state, repo, &pr).await? { remove(state, repo, &head, reason).await; continue; } if !start(state, repo, &pr, &head).await? { continue; } if !evaluate(state, repo, &head.id).await? { return Ok(()); } } } async fn unready( state: &AppState, repo: &Repo, pr: &PullRequest, ) -> forge_core::Result> { if pr.merged_at.is_some() || pr.issue.state != IssueState::Open { return Ok(Some("closed")); } if pr.head_repo_id.is_none() { return Ok(Some(ERR_HEAD_MISSING)); } if pr.draft { return Ok(Some(ERR_DRAFT)); } let gate = merge_gate(state, repo, pr).await?; let blocked = gate .blockers() .into_iter() .any(|code| !matches!(code, ERR_NEEDS_CHECKS | ERR_NOT_UP_TO_DATE)); Ok(blocked.then_some("blocked")) } async fn start( state: &AppState, repo: &Repo, pr: &PullRequest, entry: &QueueEntry, ) -> forge_core::Result { let base_path = repo_path(&state.git.data_dir, &repo.id)?; let Some(base_tip) = default_branch_commit(&base_path, &entry.branch)? else { remove(state, repo, entry, "no_branch").await; return Ok(false); }; let Some(user) = state.store.user_by_id(&entry.enqueued_by).await? else { remove(state, repo, entry, "removed").await; return Ok(false); }; let tested = match merge_commit(state, repo, pr, &user, entry.merge_style, None, &base_tip).await? { Ok(oid) => oid, Err(refusal) => { let text = format!( "could not build the merge with the target branch: {}.", refusal.message ); fail(state, repo, entry, pr, "conflict", &text).await?; return Ok(false); } }; let test_ref = test_ref_name(&entry.branch, entry.pull_number); set_ref(&state.git, &base_path, &test_ref, &tested).await?; if !state .store .queue_set_testing(&entry.id, &base_tip, &tested, &test_ref) .await? { return Ok(false); } notify_entry(state, repo, entry); merge_queue_run( state, repo, &test_ref, &entry.branch, &tested, &user.id, pr.issue.number, ) .await?; schedule_timeout(state, repo, &entry.id, &entry.branch, &tested); Ok(true) } pub fn spawn_resume(state: AppState) { tokio::spawn(async move { let entries = match state.store.queue_testing_all().await { Ok(entries) => entries, Err(e) => { tracing::error!(error = %e, "merge queue: listing testing entries failed"); return; } }; for entry in entries { let repo = match state.store.repo_by_id(&entry.repo_id).await { Ok(Some(repo)) => repo, Ok(None) => continue, Err(e) => { tracing::error!(error = %e, repo_id = %entry.repo_id, "merge queue: loading a repo failed"); continue; } }; let tested = entry.tested_oid.clone().unwrap_or_default(); schedule_timeout(&state, &repo, &entry.id, &entry.branch, &tested); } }); } fn schedule_timeout(state: &AppState, repo: &Repo, entry_id: &str, branch: &str, tested: &str) { let state = state.clone(); let repo = repo.clone(); let entry_id = entry_id.to_string(); let branch = branch.to_string(); let tested = tested.to_string(); tokio::spawn(async move { tokio::time::sleep(check_timeout(&state, &repo.id, &tested).await).await; match evaluate(&state, &repo, &entry_id).await { Ok(true) => advance(&state, &repo, &branch).await, Ok(false) => {} Err(e) => { tracing::error!(error = %e, repo_id = %repo.id, "merge queue: timeout check failed"); } } }); } pub async fn evaluate(state: &AppState, repo: &Repo, entry_id: &str) -> forge_core::Result { let Some(entry) = state.store.queue_entry(entry_id).await? else { return Ok(true); }; if entry.state != QueueState::Testing { return Ok(true); } let Some(pr) = state .store .pull_by_number(&repo.id, entry.pull_number) .await? else { remove(state, repo, &entry, "removed").await; return Ok(true); }; let tested = entry.tested_oid.clone().unwrap_or_default(); let test_ref = entry.test_ref.clone().unwrap_or_default(); let run = state .store .latest_run_on_ref(&repo.id, &test_ref) .await? .filter(|run| run.commit_oid == tested); if let Some(run) = &run { if !run.state.is_terminal() { return Ok(false); } if run.state != forge_core::ci::RunState::Success { let url = format!( "{}/{}/{}/ci/runs/{}", state.config.base_url.trim_end_matches('/'), repo.owner_name, repo.name, run.number ); let text = format!("the merge queue test run {url} did not pass."); fail(state, repo, &entry, &pr, "tests_failed", &text).await?; return Ok(true); } } let rules = state.store.list_branch_rules(&repo.id).await?; let rule = effective(&rules, &repo.default_branch, &entry.branch); if !rule.required_checks.is_empty() { let statuses = state.store.statuses_for(&repo.id, &tested).await?; let mut missing: Option<&String> = None; for context in &rule.required_checks { match statuses .iter() .find(|s| &s.context == context) .map(|s| s.state) { Some(StatusState::Success) => {} Some(StatusState::Failure | StatusState::Error) => { let text = format!("the required check {context} failed on the merge candidate."); fail(state, repo, &entry, &pr, "checks_failed", &text).await?; return Ok(true); } _ => { missing.get_or_insert(context); } } } if let Some(context) = missing { let timeout = check_timeout(state, &repo.id, &tested).await; if entry.updated_at <= stamp_ago(timeout) { let text = format!( "the required check {context} was not reported on the merge candidate in time." ); fail(state, repo, &entry, &pr, "checks_missing", &text).await?; return Ok(true); } return Ok(false); } } land(state, repo, &entry, &pr).await } async fn check_timeout(state: &AppState, repo_id: &str, commit: &str) -> Duration { let minutes = config_at(state, repo_id, commit) .await .and_then(|cfg| cfg.jobs.values().map(|job| job.timeout_minutes).max()) .unwrap_or(DEFAULT_TIMEOUT_MINUTES); Duration::from_secs(60 * u64::from(minutes)) } async fn land( state: &AppState, repo: &Repo, entry: &QueueEntry, pr: &PullRequest, ) -> forge_core::Result { if !state.store.queue_set_merging(&entry.id).await? { return Ok(false); } let tested = entry.tested_oid.clone().unwrap_or_default(); let base = entry.base_oid.clone().unwrap_or_default(); let Some(user) = state.store.user_by_id(&entry.enqueued_by).await? else { remove_entry(state, repo, entry, "removed").await?; return Ok(true); }; let collaborator = state.store.collaborator_role(&repo.id, &user.id).await?; let org = state .store .org_repo_role(&repo.owner_id, &user.id, &repo.id) .await?; if authorize(Some(&user), repo, collaborator, org, Action::Write).is_err() { remove_entry(state, repo, entry, "permission").await?; return Ok(true); } if let Some(reason) = unready(state, repo, pr).await? { remove_entry(state, repo, entry, reason).await?; return Ok(true); } let refname = format!("refs/heads/{}", entry.branch); let base_path = repo_path(&state.git.data_dir, &repo.id)?; match update_ref_cas(&state.git, &base_path, &refname, &tested, &base).await { Ok(()) => {} Err(forge_git::error::Error::RefMoved(_)) => { state.store.queue_set_queued(&entry.id).await?; notify_entry(state, repo, entry); return Ok(true); } Err(e) => { state.store.queue_set_queued(&entry.id).await?; notify_entry(state, repo, entry); return Err(e.into()); } } finish_merge(state, repo, pr, &user, &refname, &base, &tested).await; remove_entry(state, repo, entry, "merged").await?; Ok(true) } async fn fail( state: &AppState, repo: &Repo, entry: &QueueEntry, pr: &PullRequest, reason: &str, text: &str, ) -> forge_core::Result<()> { if !state .store .queue_finish(&entry.id, QueueState::Failed, reason) .await? { return Ok(()); } notify_entry(state, repo, entry); let who = match state.store.user_by_id(&entry.enqueued_by).await? { Some(user) => format!("@{}", user.username), None => String::new(), }; let body = format!("{who} The merge queue removed this pull request: {text}") .trim_start() .to_owned(); let ghost = state.store.ensure_ghost_user().await?; match state .store .add_comment(&pr.issue.id, &ghost.id, &body) .await { Ok(_) => { crate::live::bump_pull(state, &repo.id, &pr.issue.id); notify::dispatch( state, repo, &pr.issue, &ghost.id, Activity::Comment, Some(&body), ) .await; } Err(e) => { tracing::error!(error = %e, repo_id = %repo.id, "merge queue: commenting failed"); } } Ok(()) } fn notify_entry(state: &AppState, repo: &Repo, entry: &QueueEntry) { state.ci_live.bump_queue(&repo.id); crate::live::bump_pull(state, &repo.id, &entry.issue_id); }