//! The merge queue of a protected branch with `require_merge_queue` set. //! //! A pull request joins the queue of its base branch from its merge box. When it reaches the head //! of the queue, the queue builds a candidate: the current target tip merged with the pull request //! head, in the merge style the user chose, with no working tree. The candidate is named by the //! temporary ref `refs/forge/merge-queue/{branch}/{number}`, and a CI run tests that ref. When the //! run succeeds and the required checks are green on the candidate, the target moves from the tip //! the candidate was built on to the candidate, as one compare-and-swap. If the target moved in //! the meantime, the candidate is built again and tested again. A failing run removes the pull //! request from the queue and comments on it. //! //! Nothing polls. Each step is a reaction: an enqueue, a commit status on a candidate, a head //! change or close of a queued pull request, or a finished entry that lets the next one start. 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::{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::merge_queue_run; use crate::notify::{self, Activity}; use crate::pages::pulls_merge::{ ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE, ERR_QUEUE_ALREADY, MergeOutcome, finish_merge, merge_commit, merge_gate, }; use crate::state::AppState; /// Whether the protection of `branch` routes merges through the queue. Direct merges are refused /// then. 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) } /// Adds `pr` to the queue of its base branch as `user`, who merges it with `style`. Returns the /// refusal code when the pull request is not ready: the merge checks of the pull request apply /// (approvals, changes requested, required checks on its head, conflicts). An outdated head does /// not refuse, since the candidate is built on the current tip. 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_changed(state, &repo.id); advance(state, repo, &pr.base_branch).await; Ok(Ok(entry)) } Err(forge_core::Error::Conflict(_)) => Ok(Err(ERR_QUEUE_ALREADY)), Err(e) => Err(e), } } /// Takes a waiting entry out of the queue, with `reason`. The caller starts the queue again with /// `advance`. A candidate that is already testing keeps its CI run; its result is then ignored. pub async fn remove(state: &AppState, repo: &Repo, entry: &QueueEntry, reason: &str) { match state .store .queue_finish(&entry.id, QueueState::Removed, reason) .await { Ok(true) => notify_changed(state, &repo.id), Ok(false) => {} Err(e) => { tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed"); } } } /// A pull request's head moved or it was closed: if it waits in a queue, it leaves the queue and /// the queue moves on. 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"); } } } /// A commit status was written for `sha`. Each candidate testing at `sha` is evaluated again. 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"); } } } } /// Starts the head of the branch queue for as long as nothing is testing or merging. Failures /// are logged; the queue keeps its state, so the next event retries. 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(()); } } } /// Why `pr` cannot be tested now, if it cannot. 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")) } /// Builds the candidate of the head entry on the current target tip, points the test ref at it /// and starts its CI run. `Ok(false)` when the entry was failed (it could not be built) or moved /// on meanwhile. 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(MergeOutcome::Refused { message, .. }) => { let text = format!("could not build the merge with the target branch: {message}."); fail(state, repo, entry, pr, "conflict", &text).await?; return Ok(false); } Err(MergeOutcome::Merged { .. }) => 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_changed(state, &repo.id); // A run is created here only when the workflow runs for this candidate. Its statuses may // arrive before this returns; `evaluate` finds the run through its ref and commit. merge_queue_run( state, repo, &test_ref, &entry.branch, &tested, &user.id, pr.issue.number, ) .await?; Ok(true) } /// Looks at the candidate of a testing entry. Returns `Ok(false)` while it waits for CI or for /// its required checks, and `Ok(true)` when the entry finished (merged or failed), or went back /// to the head of the queue to be built again. 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 waiting = false; 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); } _ => waiting = true, } } if waiting { return Ok(false); } } land(state, repo, &entry, &pr).await } /// Moves the target from the tip the candidate was built on to the candidate. Returns `Ok(true)` /// when the entry is finished or back in the queue, `Ok(false)` when another event owns it. 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 { finish_removed(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() { finish_removed(state, repo, entry, "permission").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(_)) => { // The target moved since the candidate was built: build it again on the new tip. state.store.queue_set_queued(&entry.id).await?; notify_changed(state, &repo.id); return Ok(true); } Err(e) => { state.store.queue_set_queued(&entry.id).await?; notify_changed(state, &repo.id); return Err(e.into()); } } finish_merge(state, repo, pr, &user, &refname, &base, &tested).await; finish_removed(state, repo, entry, "merged").await?; Ok(true) } /// Ends a merging entry as removed with `reason`. async fn finish_removed( state: &AppState, repo: &Repo, entry: &QueueEntry, reason: &str, ) -> forge_core::Result<()> { state .store .queue_finish(&entry.id, QueueState::Removed, reason) .await?; notify_changed(state, &repo.id); Ok(()) } /// Ends an entry as failed and comments on its pull request, mentioning the person who queued it. 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_changed(state, &repo.id); 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(_) => { 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(()) } /// Wakes the queue pages of `repo_id`. pub fn notify_changed(state: &AppState, repo_id: &str) { state.ci_live.bump_queue(repo_id); }