From 05cd9ba52f48cf9402aa0494c63de02716473e84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 21 Oct 2026 22:16:44 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20merge=20queue=20so=20the=20?= =?UTF-8?q?protected=20branch=20only=20receives=20tested=20commits?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/forge-ci/src/config.rs | 11 + .../migrations/0061_merge_queue.sql | 30 + crates/forge-core/src/lib.rs | 1 + crates/forge-core/src/merge_queue.rs | 89 +++ crates/forge-core/src/protection.rs | 8 + crates/forge-core/src/store/merge_queue.rs | 272 +++++++ crates/forge-core/src/store/migrate.rs | 1 + crates/forge-core/src/store/mod.rs | 14 +- crates/forge-git/src/pulls.rs | 24 + crates/forge-web/src/api/statuses.rs | 1 + crates/forge-web/src/automerge.rs | 4 + crates/forge-web/src/ci/live.rs | 12 + crates/forge-web/src/ci/mod.rs | 2 + crates/forge-web/src/ci/schedule.rs | 44 ++ crates/forge-web/src/i18n/merge_queue.rs | 214 +++++ crates/forge-web/src/i18n/mod.rs | 1 + crates/forge-web/src/main.rs | 1 + crates/forge-web/src/merge_queue.rs | 437 +++++++++++ crates/forge-web/src/pages/issue_parts.rs | 3 + crates/forge-web/src/pages/merge_queue.rs | 436 ++++++++++ crates/forge-web/src/pages/mod.rs | 1 + crates/forge-web/src/pages/pull_view.rs | 90 ++- crates/forge-web/src/pages/pulls_list.rs | 3 + crates/forge-web/src/pages/pulls_merge.rs | 87 +- crates/forge-web/src/pages/repo_settings.rs | 17 + crates/forge-web/src/pulls_sync.rs | 1 + crates/forge-web/tests/merge_queue_e2e.rs | 742 ++++++++++++++++++ docs/ci.md | 1 + docs/merge-queue.md | 90 +++ 29 files changed, 2605 insertions(+), 32 deletions(-) create mode 100644 crates/forge-core/migrations/0061_merge_queue.sql create mode 100644 crates/forge-core/src/merge_queue.rs create mode 100644 crates/forge-core/src/store/merge_queue.rs create mode 100644 crates/forge-web/src/i18n/merge_queue.rs create mode 100644 crates/forge-web/src/merge_queue.rs create mode 100644 crates/forge-web/src/pages/merge_queue.rs create mode 100644 crates/forge-web/tests/merge_queue_e2e.rs create mode 100644 docs/merge-queue.md diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index 0530480..fd3c580 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -153,6 +153,9 @@ pub struct Triggers { /// Defaults to `true`. A push to a branch cancels the queued and running runs of /// older commits on that branch. pub cancel_superseded: bool, + /// Runs the workflow on each merge queue candidate. Without it, a candidate runs the `push` + /// jobs of its target branch (see `docs/merge-queue.md`). + pub merge_queue: bool, /// 5-field cron expressions in UTC, e.g. `"0 3 * * *"`. The server queues a run of the default /// branch head at each match. pub schedule: Vec, @@ -166,6 +169,7 @@ impl Default for Triggers { pull_request: false, manual: true, cancel_superseded: true, + merge_queue: false, schedule: Vec::new(), } } @@ -295,6 +299,10 @@ pub enum Event<'a> { Manual, /// A `[on] schedule` tick. Schedule, + /// A merge queue candidate for `branch`, the target branch. + MergeQueue { + branch: &'a str, + }, } /// Parses and validates a `ci.toml` document. @@ -330,6 +338,9 @@ impl CiConfig { Event::PullRequest => self.on.pull_request, Event::Manual => self.on.manual, Event::Schedule => !self.on.schedule.is_empty(), + Event::MergeQueue { branch } => { + self.on.merge_queue || matches_any(&self.on.push, branch) + } } } diff --git a/crates/forge-core/migrations/0061_merge_queue.sql b/crates/forge-core/migrations/0061_merge_queue.sql new file mode 100644 index 0000000..1a50cc2 --- /dev/null +++ b/crates/forge-core/migrations/0061_merge_queue.sql @@ -0,0 +1,30 @@ +-- Merge queue. A protected branch with `require_merge_queue` only moves to commits that CI tested: +-- each queued pull request is merged onto the current target tip in a temporary ref, that commit +-- is tested, and the target moves to it only if it has not moved since. +ALTER TABLE branch_protections ADD COLUMN require_merge_queue INTEGER NOT NULL DEFAULT 0; + +-- One row per pull request that entered the queue. `state` is queued, testing, merging, failed or +-- removed; the last two are finished rows (`finished_at` set) kept for the queue history. +-- `base_oid` is the target tip the candidate was built on, `tested_oid` the candidate commit, and +-- `run_id` the CI run that tests it. `reason` says why a finished row was removed. +CREATE TABLE merge_queue ( + id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE, + branch TEXT NOT NULL, + issue_id TEXT NOT NULL REFERENCES issues(id) ON DELETE CASCADE, + pull_number INTEGER NOT NULL, + merge_style TEXT NOT NULL, + state TEXT NOT NULL, + seq INTEGER NOT NULL, + enqueued_by TEXT NOT NULL REFERENCES users(id), + enqueued_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + finished_at TEXT NULL, + reason TEXT NULL, + base_oid TEXT NULL, + tested_oid TEXT NULL, + test_ref TEXT NULL, + run_id TEXT NULL +); +CREATE INDEX merge_queue_branch ON merge_queue (repo_id, branch, finished_at, seq); +CREATE INDEX merge_queue_issue ON merge_queue (issue_id, finished_at); diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index ac9b1bf..58b086c 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -13,6 +13,7 @@ pub mod issue_refs; pub mod issues; pub mod lfs_token; pub mod mail; +pub mod merge_queue; pub mod mirrors; pub mod model; pub mod names; diff --git a/crates/forge-core/src/merge_queue.rs b/crates/forge-core/src/merge_queue.rs new file mode 100644 index 0000000..5688d78 --- /dev/null +++ b/crates/forge-core/src/merge_queue.rs @@ -0,0 +1,89 @@ +//! The merge queue: pull requests waiting to be merged into a protected branch that requires the +//! queue. Each entry is `queued`, then `testing` (its candidate commit runs CI), then `merging` +//! (the target moves to the tested commit). An entry finishes as `failed` or `removed`. + +use crate::error::{Error, Result}; +use crate::pulls::MergeStyle; + +/// Where an entry is in the queue. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum QueueState { + Queued, + Testing, + Merging, + Failed, + Removed, +} + +impl QueueState { + pub fn as_str(self) -> &'static str { + match self { + QueueState::Queued => "queued", + QueueState::Testing => "testing", + QueueState::Merging => "merging", + QueueState::Failed => "failed", + QueueState::Removed => "removed", + } + } + + /// Whether the entry still waits for the queue (queued, testing or merging). + pub fn is_active(self) -> bool { + matches!( + self, + QueueState::Queued | QueueState::Testing | QueueState::Merging + ) + } +} + +impl std::str::FromStr for QueueState { + type Err = Error; + + fn from_str(s: &str) -> Result { + Ok(match s { + "queued" => QueueState::Queued, + "testing" => QueueState::Testing, + "merging" => QueueState::Merging, + "failed" => QueueState::Failed, + "removed" => QueueState::Removed, + other => { + return Err(Error::Database(format!( + "unknown merge queue state {other}" + ))); + } + }) + } +} + +/// One pull request in the queue. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QueueEntry { + pub id: String, + pub repo_id: String, + pub branch: String, + pub issue_id: String, + pub pull_number: i64, + pub merge_style: MergeStyle, + pub state: QueueState, + /// Enqueue order within the branch. Smaller entries go first. + pub seq: i64, + pub enqueued_by: String, + pub enqueued_at: String, + pub updated_at: String, + pub finished_at: Option, + /// Why a finished entry ended: `merged`, `removed`, `closed`, `head_changed`, `conflict` or + /// `tests_failed`. + pub reason: Option, + /// The target tip the candidate was built on. + pub base_oid: Option, + /// The candidate commit under test. + pub tested_oid: Option, + /// The temporary ref that names the candidate. + pub test_ref: Option, + /// The CI run that tests the candidate. + pub run_id: Option, +} + +/// The temporary ref that names a candidate of `branch` for pull request `number`. +pub fn test_ref_name(branch: &str, number: i64) -> String { + format!("refs/forge/merge-queue/{branch}/{number}") +} diff --git a/crates/forge-core/src/protection.rs b/crates/forge-core/src/protection.rs index f28e28d..3397968 100644 --- a/crates/forge-core/src/protection.rs +++ b/crates/forge-core/src/protection.rs @@ -23,6 +23,9 @@ pub struct BranchRule { /// Direct pushes to the branch are rejected for everyone but repo admins. Merges through /// pull requests are unaffected. pub restrict_push: bool, + /// Merges go through the merge queue: the merge box queues the pull request, and the queue + /// moves the branch only to commits CI tested. Direct merges are refused. + pub require_merge_queue: bool, /// Commit status contexts (CI job names such as `ci/test`, or any reported context) that must /// all be `success` on the pull request head before it can merge. pub required_checks: Vec, @@ -38,6 +41,7 @@ pub struct RuleFlags { pub block_on_changes_requested: bool, pub require_up_to_date: bool, pub restrict_push: bool, + pub require_merge_queue: bool, pub required_checks: Vec, } @@ -61,6 +65,7 @@ pub struct Protection { pub block_on_changes_requested: bool, pub require_up_to_date: bool, pub restrict_push: bool, + pub require_merge_queue: bool, pub required_checks: Vec, } @@ -235,6 +240,7 @@ pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> Pr block_on_changes_requested: rule.block_on_changes_requested, require_up_to_date: rule.require_up_to_date, restrict_push: rule.restrict_push, + require_merge_queue: rule.require_merge_queue, required_checks: rule.required_checks.clone(), }; } @@ -268,6 +274,7 @@ mod tests { block_on_changes_requested: false, require_up_to_date: false, restrict_push: false, + require_merge_queue: false, required_checks: Vec::new(), created_at: created.into(), } @@ -381,6 +388,7 @@ mod tests { block_on_changes_requested: true, require_up_to_date: true, restrict_push: true, + require_merge_queue: false, required_checks: Vec::new(), } ); diff --git a/crates/forge-core/src/store/merge_queue.rs b/crates/forge-core/src/store/merge_queue.rs new file mode 100644 index 0000000..b0a7377 --- /dev/null +++ b/crates/forge-core/src/store/merge_queue.rs @@ -0,0 +1,272 @@ +//! Merge queue rows. The engine that moves entries along lives in forge-web (`merge_queue`); every +//! transition here is a conditional write, so two events that race on one entry cannot both win. + +use turso::Value; + +use super::issues::finish; +use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id}; +use crate::error::{Error, Result}; +use crate::merge_queue::{QueueEntry, QueueState}; +use crate::pulls::MergeStyle; +use crate::time::now_stamp; + +const QUEUE_COLS: &str = "id, repo_id, branch, issue_id, pull_number, merge_style, state, seq, \ + enqueued_by, enqueued_at, updated_at, finished_at, reason, base_oid, tested_oid, test_ref, run_id"; + +/// Finished entries shown in the queue history. +const HISTORY_LIMIT: i64 = 30; + +impl Store { + /// Adds a pull request to the end of the branch queue. Fails with `Conflict` when the pull + /// request already waits in a queue. + pub async fn enqueue_pull( + &self, + repo_id: &str, + branch: &str, + issue_id: &str, + pull_number: i64, + style: MergeStyle, + user_id: &str, + ) -> Result { + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result = async { + let waiting = fetch_opt( + &tx, + "SELECT id FROM merge_queue WHERE issue_id = ?1 AND finished_at IS NULL LIMIT 1", + (issue_id.to_string(),), + |row| col_text(row, 0), + ) + .await?; + if waiting.is_some() { + return Err(Error::Conflict("pull request is already in the merge queue".into())); + } + let seq = fetch_opt( + &tx, + "SELECT COALESCE(MAX(seq), 0) + 1 FROM merge_queue WHERE repo_id = ?1 AND branch = ?2", + (repo_id.to_string(), branch.to_string()), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(1); + let id = new_id(); + let now = now_stamp(); + tx.execute( + "INSERT INTO merge_queue (id, repo_id, branch, issue_id, pull_number, merge_style, \ + state, seq, enqueued_by, enqueued_at, updated_at) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'queued', ?7, ?8, ?9, ?9)", + ( + id.clone(), + repo_id.to_string(), + branch.to_string(), + issue_id.to_string(), + pull_number, + style.as_str().to_string(), + seq, + user_id.to_string(), + now, + ), + ) + .await + .map_err(db_err)?; + fetch_opt( + &tx, + &format!("SELECT {QUEUE_COLS} FROM merge_queue WHERE id = ?1"), + (id,), + map_entry, + ) + .await? + .ok_or(Error::NotFound) + } + .await; + finish(tx, outcome).await + } + + /// The waiting entries of one branch, in queue order (the first is the head). + pub async fn queue_for_branch(&self, repo_id: &str, branch: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {QUEUE_COLS} FROM merge_queue WHERE repo_id = ?1 AND branch = ?2 \ + AND finished_at IS NULL ORDER BY seq" + ), + (repo_id.to_string(), branch.to_string()), + map_entry, + ) + .await + } + + /// The waiting entry of a pull request, if it waits in a queue. + pub async fn queue_entry_for_pull(&self, issue_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!( + "SELECT {QUEUE_COLS} FROM merge_queue WHERE issue_id = ?1 AND finished_at IS NULL \ + LIMIT 1" + ), + (issue_id.to_string(),), + map_entry, + ) + .await + } + + /// The waiting entries of a repo (all branches, queue order) followed by its most recent + /// finished entries. + pub async fn queue_overview(&self, repo_id: &str) -> Result> { + let conn = self.read_conn().await; + let mut out = fetch_all( + &conn, + &format!( + "SELECT {QUEUE_COLS} FROM merge_queue WHERE repo_id = ?1 AND finished_at IS NULL \ + ORDER BY branch, seq" + ), + (repo_id.to_string(),), + map_entry, + ) + .await?; + let history = fetch_all( + &conn, + &format!( + "SELECT {QUEUE_COLS} FROM merge_queue WHERE repo_id = ?1 AND finished_at IS NOT NULL \ + ORDER BY finished_at DESC, seq DESC LIMIT {HISTORY_LIMIT}" + ), + (repo_id.to_string(),), + map_entry, + ) + .await?; + out.extend(history); + Ok(out) + } + + /// The entries of `repo_id` in `testing` whose candidate is `oid`. + pub async fn queue_testing_on(&self, repo_id: &str, oid: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {QUEUE_COLS} FROM merge_queue WHERE repo_id = ?1 AND state = 'testing' \ + AND tested_oid = ?2" + ), + (repo_id.to_string(), oid.to_string()), + map_entry, + ) + .await + } + + /// Starts testing `base` plus the pull request as `tested` under `test_ref`. Works from + /// `queued` (first start) and `testing` (a rebuild). Returns false when the entry has moved on. + pub async fn queue_set_testing( + &self, + id: &str, + base: &str, + tested: &str, + test_ref: &str, + ) -> Result { + self.queue_update( + "UPDATE merge_queue SET state = 'testing', base_oid = ?2, tested_oid = ?3, test_ref = ?4, \ + run_id = NULL, updated_at = ?5 WHERE id = ?1 AND state IN ('queued', 'testing')", + vec![ + Value::Text(id.to_string()), + Value::Text(base.to_string()), + Value::Text(tested.to_string()), + Value::Text(test_ref.to_string()), + Value::Text(now_stamp()), + ], + ) + .await + } + + /// Records the CI run that tests the entry's candidate. + pub async fn queue_attach_run(&self, id: &str, run_id: &str) -> Result<()> { + self.queue_update( + "UPDATE merge_queue SET run_id = ?2, updated_at = ?3 WHERE id = ?1 AND finished_at IS NULL", + vec![ + Value::Text(id.to_string()), + Value::Text(run_id.to_string()), + Value::Text(now_stamp()), + ], + ) + .await?; + Ok(()) + } + + /// Moves a tested entry to `merging`. False when another event already took it. + pub async fn queue_set_merging(&self, id: &str) -> Result { + self.queue_update( + "UPDATE merge_queue SET state = 'merging', updated_at = ?2 WHERE id = ?1 AND state = 'testing'", + vec![Value::Text(id.to_string()), Value::Text(now_stamp())], + ) + .await + } + + /// Puts a `merging` entry back at the head of the queue, after the target moved under it. + pub async fn queue_set_queued(&self, id: &str) -> Result { + self.queue_update( + "UPDATE merge_queue SET state = 'queued', base_oid = NULL, tested_oid = NULL, test_ref = NULL, \ + run_id = NULL, updated_at = ?2 WHERE id = ?1 AND state IN ('testing', 'merging')", + vec![Value::Text(id.to_string()), Value::Text(now_stamp())], + ) + .await + } + + /// Ends a waiting entry as `failed` or `removed` with `reason`. False if it already finished. + pub async fn queue_finish(&self, id: &str, state: QueueState, reason: &str) -> Result { + let now = now_stamp(); + self.queue_update( + "UPDATE merge_queue SET state = ?2, reason = ?3, finished_at = ?4, updated_at = ?4 \ + WHERE id = ?1 AND finished_at IS NULL", + vec![ + Value::Text(id.to_string()), + Value::Text(state.as_str().to_string()), + Value::Text(reason.to_string()), + Value::Text(now), + ], + ) + .await + } + + /// One entry by id. + pub async fn queue_entry(&self, id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + &format!("SELECT {QUEUE_COLS} FROM merge_queue WHERE id = ?1"), + (id.to_string(),), + map_entry, + ) + .await + } + + async fn queue_update(&self, sql: &str, params: Vec) -> Result { + let conn = self.inner.conn.lock().await; + let changed = conn.execute(sql, params).await.map_err(db_err)?; + Ok(changed > 0) + } +} + +/// Reads `QUEUE_COLS`. +fn map_entry(row: &turso::Row) -> Result { + Ok(QueueEntry { + id: col_text(row, 0)?, + repo_id: col_text(row, 1)?, + branch: col_text(row, 2)?, + issue_id: col_text(row, 3)?, + pull_number: col_int(row, 4)?, + merge_style: col_text(row, 5)? + .parse::() + .map_err(|e| Error::Database(e.to_string()))?, + state: col_text(row, 6)?.parse::()?, + seq: col_int(row, 7)?, + enqueued_by: col_text(row, 8)?, + enqueued_at: col_text(row, 9)?, + updated_at: col_text(row, 10)?, + finished_at: col_opt_text(row, 11)?, + reason: col_opt_text(row, 12)?, + base_oid: col_opt_text(row, 13)?, + tested_oid: col_opt_text(row, 14)?, + test_ref: col_opt_text(row, 15)?, + run_id: col_opt_text(row, 16)?, + }) +} diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index b2e4f13..6e9803f 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -101,6 +101,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ (59, include_str!("../../migrations/0059_admin_alerts.sql")), (60, include_str!("../../migrations/0060_runner_memory.sql")), (61, include_str!("../../migrations/0061_web_push.sql")), + (61, include_str!("../../migrations/0061_merge_queue.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index d9ffe54..9fb32af 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -18,6 +18,7 @@ pub mod issues; pub mod labels; pub mod lfs; pub mod mail; +pub mod merge_queue; pub mod migrate; pub mod mirrors; pub mod notifications; @@ -1247,7 +1248,8 @@ impl Store { } const BRANCH_RULE_COLS: &str = "id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \ - required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks"; + required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks, \ + require_merge_queue"; // branch protection impl Store { @@ -1281,13 +1283,14 @@ impl Store { let conn = self.inner.conn.lock().await; conn.execute( "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \ - required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) \ + required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks, \ + require_merge_queue) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) \ ON CONFLICT(repo_id, pattern) DO UPDATE SET allow_force_push = excluded.allow_force_push, \ allow_deletion = excluded.allow_deletion, required_approvals = excluded.required_approvals, \ block_on_changes_requested = excluded.block_on_changes_requested, \ require_up_to_date = excluded.require_up_to_date, restrict_push = excluded.restrict_push, \ - required_checks = excluded.required_checks", + required_checks = excluded.required_checks, require_merge_queue = excluded.require_merge_queue", ( new_id(), repo_id.to_string(), @@ -1300,6 +1303,7 @@ impl Store { i64::from(flags.require_up_to_date), i64::from(flags.restrict_push), checks_json, + i64::from(flags.require_merge_queue), ), ) .await @@ -1348,6 +1352,7 @@ fn map_branch_rule(row: &Row) -> Result { restrict_push: col_bool(row, 9)?, required_checks: serde_json::from_str(&col_text(row, 10)?) .map_err(|e| Error::Database(format!("required_checks is not a JSON array: {e}")))?, + require_merge_queue: col_bool(row, 11)?, }) } @@ -2188,6 +2193,7 @@ mod tests { block_on_changes_requested: true, require_up_to_date: true, restrict_push: true, + require_merge_queue: true, required_checks: Vec::new(), }; let saved = store diff --git a/crates/forge-git/src/pulls.rs b/crates/forge-git/src/pulls.rs index 926ac39..054ce71 100644 --- a/crates/forge-git/src/pulls.rs +++ b/crates/forge-git/src/pulls.rs @@ -405,6 +405,30 @@ pub async fn update_ref_cas( Err(failed("update-ref", &out)) } +/// Points `refname` at `new`, whatever it pointed at before. Used for the temporary refs that name +/// a merge queue candidate; a rebuild replaces them. +pub async fn set_ref(env: &GitEnv, repo: &Path, refname: &str, new: &str) -> Result<()> { + // Only the merge queue's temporary namespace is writable here, besides the usual checks. + let queue_ok = refname + .strip_prefix("refs/forge/merge-queue/") + .is_some_and(valid_branch_rest); + if !queue_ok { + return Err(Error::InvalidInput(format!( + "invalid ref name: {refname:?}" + ))); + } + validate_oid(new)?; + let cmd = git(env, "update-ref") + .git_dir(repo) + .user_arg(refname)? + .user_arg(new)?; + let out = run_raw(cmd, None).await?; + if out.status.success() { + return Ok(()); + } + Err(failed("update-ref", &out)) +} + /// Deletes `refname` only if it still points at `old`. `git update-ref -d ` checks the /// old value itself, so a ref that moved, or one that is already gone, gives `Error::RefMoved` /// and is left alone. The zero id is not accepted as `old`: a deletion needs a real value to diff --git a/crates/forge-web/src/api/statuses.rs b/crates/forge-web/src/api/statuses.rs index 9fe1bf2..83a8300 100644 --- a/crates/forge-web/src/api/statuses.rs +++ b/crates/forge-web/src/api/statuses.rs @@ -108,6 +108,7 @@ async fn report_status(cx: &Cx, body: Body) -> topcoat::Result { Err(e) => return Ok(*api::internal(e)), }; crate::automerge::on_status(state, &repo.id, &sha).await; + crate::merge_queue::on_status(state, &repo, &sha).await; Ok(api::json(StatusCode::CREATED, &status_json(&saved))) } diff --git a/crates/forge-web/src/automerge.rs b/crates/forge-web/src/automerge.rs index 2690e3d..5832127 100644 --- a/crates/forge-web/src/automerge.rs +++ b/crates/forge-web/src/automerge.rs @@ -73,6 +73,10 @@ pub async fn evaluate(state: &AppState, repo: &Repo, pr: &PullRequest) -> forge_ if pr.draft || pr.head_repo_id.is_none() { return Ok(false); } + // A branch that requires the merge queue takes no direct merges, auto-merge included. + if crate::merge_queue::requires_queue(state, repo, &pr.base_branch).await? { + return Ok(false); + } if merge_gate(state, repo, pr).await?.blocked().is_some() { return Ok(false); } diff --git a/crates/forge-web/src/ci/live.rs b/crates/forge-web/src/ci/live.rs index 5e7268d..3b913d7 100644 --- a/crates/forge-web/src/ci/live.rs +++ b/crates/forge-web/src/ci/live.rs @@ -22,9 +22,21 @@ pub struct CiLive { runs: Signals, repos: Signals, runners: Signals, + queues: Signals, } impl CiLive { + /// Subscribes to changes of the merge queue of repo `repo_id`: an entry was added, moved or + /// finished. Same rules as [`CiLive::subscribe_job`]. + pub fn subscribe_queue(&self, repo_id: &str) -> watch::Receiver { + self.queues.subscribe(repo_id) + } + + /// Wakes the subscribers of the merge queue of repo `repo_id`. + pub fn bump_queue(&self, repo_id: &str) { + self.queues.bump(repo_id); + } + /// Subscribes to changes of job `job_id`. The receiver starts as seen, so a bump after this /// call wakes it. Subscribe before the state you read, so a change in between is not lost. pub fn subscribe_job(&self, job_id: &str) -> watch::Receiver { diff --git a/crates/forge-web/src/ci/mod.rs b/crates/forge-web/src/ci/mod.rs index 7e5611e..0b55ff7 100644 --- a/crates/forge-web/src/ci/mod.rs +++ b/crates/forge-web/src/ci/mod.rs @@ -112,6 +112,8 @@ pub(crate) async fn publish( return; } crate::automerge::on_status(state, &repo.id, &run.commit_oid).await; + // Boxed: a queue advance can start the next candidate's run, which publishes again. + Box::pin(crate::merge_queue::on_status(state, repo, &run.commit_oid)).await; } /// The person a CI status is recorded for: the run's actor, or the repo owner for a system run. diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web/src/ci/schedule.rs index 95f368b..6e5bc1d 100644 --- a/crates/forge-web/src/ci/schedule.rs +++ b/crates/forge-web/src/ci/schedule.rs @@ -288,6 +288,50 @@ pub(super) async fn scheduled_run( Ok(Some(run)) } +/// Starts the run that tests a merge queue candidate `commit` of `branch`, named by the temporary +/// ref `test_ref`. The workflow of the candidate decides: `[on] merge_queue`, or the `push` jobs of +/// `branch`. `Ok(None)` when no run is wanted (no workflow, or it does not run for the candidate). +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 Plan::Run { + jobs, + config_error, + warnings, + .. + } = 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, + }, + jobs, + config_error.as_deref(), + &warnings, + ) + .await?; + Ok(Some(run)) +} + /// Creates the run, sets the statuses of its jobs (and `ci/config` for an error run), and wakes /// the runner claims when a job is queued. async fn create( diff --git a/crates/forge-web/src/i18n/merge_queue.rs b/crates/forge-web/src/i18n/merge_queue.rs new file mode 100644 index 0000000..5986644 --- /dev/null +++ b/crates/forge-web/src/i18n/merge_queue.rs @@ -0,0 +1,214 @@ +//! Strings for the merge queue: the branch protection option, the pull request merge box and the +//! queue page. See `docs/merge-queue.md`. + +use super::Lang; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum K { + RequireMergeQueue, + RequireMergeQueueHint, + RuleMergeQueue, + AddToMergeQueue, + MergeQueueHint, + RemoveFromQueue, + MergeQueueTitle, + MergeQueueNav, + QueueWaiting, + QueueHistory, + QueueEmpty, + QueueNoBranch, + QueueColPosition, + QueueColPull, + QueueColBranch, + QueueColState, + QueueColBy, + QueueColQueued, + QueueColRun, + QueueColReason, + QueueNoRun, + StateQueued, + StateTesting, + StateMerging, + StateFailed, + StateRemoved, + ReasonMerged, + ReasonRemoved, + ReasonClosed, + ReasonHeadChanged, + ReasonConflict, + ReasonTestsFailed, + ReasonChecksFailed, + ReasonPermission, + ReasonBlocked, + ReasonNoBranch, + ErrQueueRequired, + ErrQueueAlready, +} + +/// Every key, for the coverage test. +#[cfg(test)] +pub const ALL: &[K] = &[ + K::RequireMergeQueue, + K::RequireMergeQueueHint, + K::RuleMergeQueue, + K::AddToMergeQueue, + K::MergeQueueHint, + K::RemoveFromQueue, + K::MergeQueueTitle, + K::MergeQueueNav, + K::QueueWaiting, + K::QueueHistory, + K::QueueEmpty, + K::QueueNoBranch, + K::QueueColPosition, + K::QueueColPull, + K::QueueColBranch, + K::QueueColState, + K::QueueColBy, + K::QueueColQueued, + K::QueueColRun, + K::QueueColReason, + K::QueueNoRun, + K::StateQueued, + K::StateTesting, + K::StateMerging, + K::StateFailed, + K::StateRemoved, + K::ReasonMerged, + K::ReasonRemoved, + K::ReasonClosed, + K::ReasonHeadChanged, + K::ReasonConflict, + K::ReasonTestsFailed, + K::ReasonChecksFailed, + K::ReasonPermission, + K::ReasonBlocked, + K::ReasonNoBranch, + K::ErrQueueRequired, + K::ErrQueueAlready, +]; + +pub fn t(lang: Lang, key: K) -> &'static str { + use K::*; + use Lang::{En, Tr}; + match (key, lang) { + (RequireMergeQueue, En) => "Require merge queue", + (RequireMergeQueue, Tr) => "Birleştirme sırası iste", + (RequireMergeQueueHint, En) => { + "Merges go through the merge queue. Each pull request is tested on top of the current branch tip, and the branch moves only to a tested commit." + } + (RequireMergeQueueHint, Tr) => { + "Birleştirmeler birleştirme sırasından geçer. Her çekme isteği güncel dal ucunun üstünde test edilir ve dal yalnızca test edilmiş bir commit'e ilerler." + } + (RuleMergeQueue, En) => "merge queue required", + (RuleMergeQueue, Tr) => "birleştirme sırası zorunlu", + (AddToMergeQueue, En) => "Add to merge queue", + (AddToMergeQueue, Tr) => "Birleştirme sırasına ekle", + (MergeQueueHint, En) => { + "This branch requires the merge queue. The pull request is tested on the current tip before it lands." + } + (MergeQueueHint, Tr) => { + "Bu dal birleştirme sırası gerektirir. Çekme isteği inmeden önce güncel uç üzerinde test edilir." + } + (RemoveFromQueue, En) => "Remove from queue", + (RemoveFromQueue, Tr) => "Sıradan çıkar", + (MergeQueueTitle, En) => "Merge queue", + (MergeQueueTitle, Tr) => "Birleştirme sırası", + (MergeQueueNav, En) => "Merge queue", + (MergeQueueNav, Tr) => "Birleştirme sırası", + (QueueWaiting, En) => "Waiting", + (QueueWaiting, Tr) => "Bekleyen", + (QueueHistory, En) => "History", + (QueueHistory, Tr) => "Geçmiş", + (QueueEmpty, En) => "Nothing is waiting in the merge queue.", + (QueueEmpty, Tr) => "Birleştirme sırasında bekleyen yok.", + (QueueNoBranch, En) => { + "No protected branch requires the merge queue. Turn it on in the branch protection settings." + } + (QueueNoBranch, Tr) => { + "Birleştirme sırası isteyen korumalı bir dal yok. Dal koruma ayarlarından açabilirsiniz." + } + (QueueColPosition, En) => "Position", + (QueueColPosition, Tr) => "Sıra", + (QueueColPull, En) => "Pull request", + (QueueColPull, Tr) => "Çekme isteği", + (QueueColBranch, En) => "Branch", + (QueueColBranch, Tr) => "Dal", + (QueueColState, En) => "State", + (QueueColState, Tr) => "Durum", + (QueueColBy, En) => "Queued by", + (QueueColBy, Tr) => "Ekleyen", + (QueueColQueued, En) => "Queued", + (QueueColQueued, Tr) => "Eklendi", + (QueueColRun, En) => "CI run", + (QueueColRun, Tr) => "CI çalıştırması", + (QueueColReason, En) => "Reason", + (QueueColReason, Tr) => "Neden", + (QueueNoRun, En) => "No run", + (QueueNoRun, Tr) => "Çalıştırma yok", + (StateQueued, En) => "Queued", + (StateQueued, Tr) => "Sırada", + (StateTesting, En) => "Testing", + (StateTesting, Tr) => "Test ediliyor", + (StateMerging, En) => "Merging", + (StateMerging, Tr) => "Birleştiriliyor", + (StateFailed, En) => "Failed", + (StateFailed, Tr) => "Başarısız", + (StateRemoved, En) => "Removed", + (StateRemoved, Tr) => "Çıkarıldı", + (ReasonMerged, En) => "merged", + (ReasonMerged, Tr) => "birleştirildi", + (ReasonRemoved, En) => "removed by a person", + (ReasonRemoved, Tr) => "biri tarafından çıkarıldı", + (ReasonClosed, En) => "closed", + (ReasonClosed, Tr) => "kapatıldı", + (ReasonHeadChanged, En) => "the head changed", + (ReasonHeadChanged, Tr) => "baş değişti", + (ReasonConflict, En) => "conflicts with the branch", + (ReasonConflict, Tr) => "dalla çakışıyor", + (ReasonTestsFailed, En) => "the test run failed", + (ReasonTestsFailed, Tr) => "test çalıştırması başarısız", + (ReasonChecksFailed, En) => "a required check failed", + (ReasonChecksFailed, Tr) => "zorunlu bir denetim başarısız", + (ReasonPermission, En) => "the person who queued it can no longer merge", + (ReasonPermission, Tr) => "sıraya ekleyen kişi artık birleştiremiyor", + (ReasonBlocked, En) => "a merge check no longer passes", + (ReasonBlocked, Tr) => "bir birleştirme denetimi artık geçmiyor", + (ReasonNoBranch, En) => "the branch is gone", + (ReasonNoBranch, Tr) => "dal artık yok", + (ErrQueueRequired, En) => { + "This branch requires the merge queue. Add the pull request to the queue instead." + } + (ErrQueueRequired, Tr) => { + "Bu dal birleştirme sırası gerektiriyor. Bunun yerine çekme isteğini sıraya ekleyin." + } + (ErrQueueAlready, En) => "This pull request is already in the merge queue.", + (ErrQueueAlready, Tr) => "Bu çekme isteği zaten birleştirme sırasında.", + } +} + +/// The position line of a pull request in the queue. +pub fn position_text(lang: Lang, position: usize) -> String { + match lang { + Lang::En => format!("Position {position} in the merge queue"), + Lang::Tr => format!("Birleştirme sırasında {position}. sırada"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_key_has_english_and_turkish() { + for key in ALL { + assert!(!t(Lang::En, *key).is_empty(), "{key:?} has no English"); + assert!(!t(Lang::Tr, *key).is_empty(), "{key:?} has no Turkish"); + } + } + + #[test] + fn position_line_counts_from_the_head() { + assert_eq!(position_text(Lang::En, 2), "Position 2 in the merge queue"); + } +} diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index b61427e..a17b56a 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -28,6 +28,7 @@ pub mod community; pub mod integrations; pub mod issues; pub mod link; +pub mod merge_queue; pub mod migrate; pub mod misc; pub mod orgs; diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index 62b5d34..7254119 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -35,6 +35,7 @@ mod lfs; mod lfs_pointer; mod live; mod mail; +mod merge_queue; mod mirrors; mod notify; mod notify_hub; diff --git a/crates/forge-web/src/merge_queue.rs b/crates/forge-web/src/merge_queue.rs new file mode 100644 index 0000000..3cb875d --- /dev/null +++ b/crates/forge-web/src/merge_queue.rs @@ -0,0 +1,437 @@ +//! 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); +} diff --git a/crates/forge-web/src/pages/issue_parts.rs b/crates/forge-web/src/pages/issue_parts.rs index ef4cfbd..9c174a7 100644 --- a/crates/forge-web/src/pages/issue_parts.rs +++ b/crates/forge-web/src/pages/issue_parts.rs @@ -1378,6 +1378,9 @@ pub(crate) async fn post_comment( ("reopened", Activity::Reopened) }; emit_item_action(state, &ctx.repo, &sender, pull, item.number, action).await; + if pull && action == "closed" { + crate::merge_queue::drop_pull(state, &ctx.repo, &item.id, "closed").await; + } if pull && action == "reopened" && let Some(pr) = state diff --git a/crates/forge-web/src/pages/merge_queue.rs b/crates/forge-web/src/pages/merge_queue.rs new file mode 100644 index 0000000..75a45bf --- /dev/null +++ b/crates/forge-web/src/pages/merge_queue.rs @@ -0,0 +1,436 @@ +//! The merge queue: the queue page of a repo and the pull request actions that join and leave it. +//! +//! - `GET /{owner}/{repo}/merge-queue` lists the waiting entries with their position, state, CI run +//! and a remove button, and `?show=history` the finished ones. It follows the queue live. +//! - `GET /{owner}/{repo}/merge-queue/events` is the `changed` stream of that page. +//! - `POST /{owner}/{repo}/pulls/{number}/merge-queue` adds a pull request to the queue. +//! - `POST /{owner}/{repo}/pulls/{number}/merge-queue/remove` takes it out again. +//! +//! The actions need Write, a valid CSRF token and an open pull request. They answer with a +//! redirect back to the pull request, carrying a refusal code when there is one. + +use std::collections::HashMap; + +use forge_core::merge_queue::{QueueEntry, QueueState}; +use forge_core::{Action, MergeStyle, PullRequest, authorize}; +use futures_util::{Stream, stream}; +use serde::Deserialize; +use tokio::sync::watch; +use topcoat::Result; +use topcoat::context::{Cx, app_context}; +use topcoat::router::content::Form; +use topcoat::router::content::sse::Event; +use topcoat::router::error::{bad_request, forbidden, not_found, see_other}; +use topcoat::router::response::Response; +use topcoat::router::{page, path_param, query_params, route}; +use topcoat::view::{View, component, view}; + +use crate::auth::require_csrf; +use crate::i18n::merge_queue::{self as g, K}; +use crate::i18n::{self, Lang}; +use crate::merge_queue as queue; +use crate::pages::ci_runs::{changed_event, events_response}; +use crate::pages::issue_parts::parse_number; +use crate::pages::pulls_merge::ERR_NOT_OPEN; +use crate::pages::repo::repo_head; +use crate::pages::repo_ctx::{RepoCtx, load_repo}; +use crate::state::AppState; +use crate::views::{repo_href, shell}; + +path_param!(owner); +path_param!(repo); +path_param!(number); + +#[derive(Deserialize)] +struct QueueForm { + #[serde(default)] + csrf: String, + #[serde(default)] + style: String, +} + +#[query_params(error = bad_request)] +struct QueueQuery { + show: Option, +} + +fn pull_href(ctx: &RepoCtx, number: i64) -> String { + repo_href( + &ctx.repo.owner_name, + &ctx.repo.name, + "pulls", + &number.to_string(), + ) +} + +fn queue_href(ctx: &RepoCtx) -> String { + repo_href(&ctx.repo.owner_name, &ctx.repo.name, "merge-queue", "") +} + +/// Back to the pull request, with a refusal code when there is one. +fn back_to_pull(href: &str, code: Option<&str>) -> Result { + let target = match code { + Some(code) => format!("{href}?merge_error={code}"), + None => href.to_owned(), + }; + Err(see_other(target).into()) +} + +async fn load_pull(cx: &Cx, ctx: &RepoCtx, number: i64) -> Result { + let state = app_context::(cx); + match state.store.pull_by_number(&ctx.repo.id, number).await? { + Some(pr) => Ok(pr), + None => Err(not_found().into()), + } +} + +#[route(POST "/{owner}/{repo}/pulls/{number}/merge-queue")] +async fn enqueue_post(cx: &Cx, Form(form): Form) -> Result { + let number = parse_number(path_param::(cx))?; + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let (user, _) = require_csrf(cx, &form.csrf).await?; + if ctx.repo.archived + || authorize( + Some(&user), + &ctx.repo, + ctx.role, + ctx.org_role, + Action::Write, + ) + .is_err() + { + return Err(forbidden().into()); + } + let state = app_context::(cx); + let pr = load_pull(cx, &ctx, number).await?; + let href = pull_href(&ctx, number); + if pr.merged_at.is_some() || pr.issue.state != forge_core::IssueState::Open { + return back_to_pull(&href, Some(ERR_NOT_OPEN)); + } + if !queue::requires_queue(state, &ctx.repo, &pr.base_branch).await? { + return back_to_pull(&href, None); + } + let style = if form.style.is_empty() { + MergeStyle::Merge + } else { + form.style + .parse::() + .map_err(|e| bad_request(e.to_string()))? + }; + match queue::enqueue(state, &ctx.repo, &pr, &user, style).await? { + Ok(_) => back_to_pull(&href, None), + Err(code) => back_to_pull(&href, Some(code)), + } +} + +#[route(POST "/{owner}/{repo}/pulls/{number}/merge-queue/remove")] +async fn remove_post(cx: &Cx, Form(form): Form) -> Result { + let number = parse_number(path_param::(cx))?; + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let (user, _) = require_csrf(cx, &form.csrf).await?; + if ctx.repo.archived + || authorize( + Some(&user), + &ctx.repo, + ctx.role, + ctx.org_role, + Action::Write, + ) + .is_err() + { + return Err(forbidden().into()); + } + let state = app_context::(cx); + let pr = load_pull(cx, &ctx, number).await?; + let href = pull_href(&ctx, number); + if let Some(entry) = state.store.queue_entry_for_pull(&pr.issue.id).await? { + queue::remove(state, &ctx.repo, &entry, "removed").await; + queue::advance(state, &ctx.repo, &entry.branch).await; + } + back_to_pull(&href, None) +} + +/// The queue page: waiting entries, or the history with `?show=history`. +#[page("/{owner}/{repo}/merge-queue")] +async fn queue_page(cx: &Cx) -> Result { + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u)); + let history = query_params::(cx)?.show.as_deref() == Some("history"); + let state = app_context::(cx); + let frame = crate::pages::issue_meta::RepoFrame::new(&ctx, state, "pulls").await?; + let entries = state.store.queue_overview(&ctx.repo.id).await?; + let rows = queue_rows(state, &ctx, lang, entries, history).await?; + let protected = state + .store + .list_branch_rules(&ctx.repo.id) + .await? + .iter() + .any(|rule| rule.require_merge_queue); + let title = g::t(lang, K::MergeQueueTitle).to_owned(); + let waiting_href = queue_href(&ctx); + let history_href = format!("{waiting_href}?show=history"); + let live = format!("{waiting_href}/events"); + let empty = rows.is_empty(); + Ok(view! { + shell(title: title.as_str(), viewer: ctx.viewer.as_ref(), + queue_body(lang: lang, head: frame.head, + waiting_href: waiting_href, history_href: history_href, history: history, + live: live, rows: rows, empty: empty, protected: protected, + csrf: frame.csrf.clone())) + }) +} + +/// One row of the queue table, with its strings resolved. +struct QueueRow { + position: String, + pull_title: String, + pull_href: String, + remove_action: String, + pull_number: i64, + branch: String, + state: &'static str, + state_class: &'static str, + by: String, + queued: String, + run_href: Option, + run_label: String, + reason: String, + remove: bool, +} + +/// `2026-10-21T19:11:22.700Z` as `2026-10-21 19:11` (UTC), for the queue table. +fn stamp_minute(stamp: &str) -> String { + match stamp.get(..16) { + Some(minute) => minute.replace('T', " "), + None => stamp.to_owned(), + } +} + +async fn queue_rows( + state: &AppState, + ctx: &RepoCtx, + lang: Lang, + entries: Vec, + history: bool, +) -> forge_core::Result> { + let mut ids: Vec = entries.iter().map(|e| e.enqueued_by.clone()).collect(); + ids.sort(); + ids.dedup(); + let names: HashMap)> = if ids.is_empty() { + HashMap::new() + } else { + state.store.usernames_by_ids(&ids).await? + }; + // Position counts the waiting entries of each branch from the head. + let mut position: HashMap = HashMap::new(); + let mut rows = Vec::new(); + for entry in entries { + let waiting = entry.finished_at.is_none(); + let pos = if waiting { + let next = position.entry(entry.branch.clone()).or_insert(0); + *next += 1; + *next + } else { + 0 + }; + if waiting == history { + continue; + } + let pull = state + .store + .pull_by_number(&ctx.repo.id, entry.pull_number) + .await?; + let pull_title = pull + .as_ref() + .map(|pr| pr.issue.title.clone()) + .unwrap_or_default(); + let run = match &entry.test_ref { + Some(test_ref) => state + .store + .latest_run_on_ref(&ctx.repo.id, test_ref) + .await? + .filter(|run| Some(&run.commit_oid) == entry.tested_oid.as_ref()), + None => None, + }; + let run_href = run.as_ref().map(|run| { + repo_href( + &ctx.repo.owner_name, + &ctx.repo.name, + "ci", + &format!("runs/{}", run.number), + ) + }); + let run_label = run + .as_ref() + .map(|run| format!("#{}", run.number)) + .unwrap_or_else(|| g::t(lang, K::QueueNoRun).to_owned()); + let by = names + .get(&entry.enqueued_by) + .map(|(display, _)| display.clone()) + .unwrap_or_default(); + rows.push(QueueRow { + position: if waiting { + pos.to_string() + } else { + String::new() + }, + pull_title, + pull_href: pull_href(ctx, entry.pull_number), + remove_action: format!("{}/remove", pull_href(ctx, entry.pull_number)), + pull_number: entry.pull_number, + branch: entry.branch.clone(), + state: state_label(lang, entry.state), + state_class: state_class(entry.state), + by, + queued: stamp_minute(&entry.enqueued_at), + run_href, + run_label, + reason: entry + .reason + .as_deref() + .map(|reason| reason_label(lang, reason)) + .unwrap_or_default(), + remove: waiting && ctx.can_write(), + }); + } + Ok(rows) +} + +fn state_label(lang: Lang, state: QueueState) -> &'static str { + g::t( + lang, + match state { + QueueState::Queued => K::StateQueued, + QueueState::Testing => K::StateTesting, + QueueState::Merging => K::StateMerging, + QueueState::Failed => K::StateFailed, + QueueState::Removed => K::StateRemoved, + }, + ) +} + +fn state_class(state: QueueState) -> &'static str { + match state { + QueueState::Queued => "queue-state queue-queued", + QueueState::Testing | QueueState::Merging => "queue-state queue-running", + QueueState::Failed => "queue-state queue-bad", + QueueState::Removed => "queue-state queue-muted", + } +} + +fn reason_label(lang: Lang, reason: &str) -> String { + let key = match reason { + "merged" => K::ReasonMerged, + "removed" => K::ReasonRemoved, + "closed" => K::ReasonClosed, + "head_changed" => K::ReasonHeadChanged, + "conflict" => K::ReasonConflict, + "tests_failed" => K::ReasonTestsFailed, + "checks_failed" => K::ReasonChecksFailed, + "permission" => K::ReasonPermission, + "blocked" => K::ReasonBlocked, + "no_branch" => K::ReasonNoBranch, + _ => return reason.to_owned(), + }; + g::t(lang, key).to_owned() +} + +/// The live `changed` stream of a repo's queue. Subscribed before the response is sent, so a change +/// after that point is sent. +#[route(GET "/{owner}/{repo}/merge-queue/events")] +async fn queue_events(cx: &Cx) -> Result { + let ctx = load_repo(cx, path_param::(cx), path_param::(cx)).await?; + let state = app_context::(cx); + let wake = state.ci_live.subscribe_queue(&ctx.repo.id); + events_response(cx, queue_changes(wake)) +} + +fn queue_changes(wake: watch::Receiver) -> impl Stream> + Send + 'static { + stream::unfold(wake, |mut wake| async move { + wake.changed().await.ok()?; + Some((changed_event("queue".to_owned()), wake)) + }) +} + +#[component] +async fn queue_body( + lang: Lang, + head: crate::pages::repo_ctx::RepoHead, + waiting_href: String, + history_href: String, + history: bool, + live: String, + rows: Vec, + empty: bool, + protected: bool, + csrf: String, +) -> Result { + let remove_label = g::t(lang, K::RemoveFromQueue); + let hint = g::t(lang, K::MergeQueueHint); + Ok(view! { + repo_head(head: head) +
+ + if !protected { +
(g::t(lang, K::QueueNoBranch))
+ } + if empty { +

(g::t(lang, K::QueueEmpty))

+ } else { +
+ + + + + + + + + + + + + + + + for row in rows.iter() { + + + + + + + + + + + + } + +
(g::t(lang, K::QueueColPosition))(g::t(lang, K::QueueColPull))(g::t(lang, K::QueueColBranch))(g::t(lang, K::QueueColState))(g::t(lang, K::QueueColBy))(g::t(lang, K::QueueColQueued))(g::t(lang, K::QueueColRun))(g::t(lang, K::QueueColReason))
(row.position.as_str())"#"(row.pull_number)" "(row.pull_title.as_str())(row.branch.as_str())(row.state)(row.by.as_str())(row.queued.as_str()) + if let Some(href) = row.run_href.as_ref() { + (row.run_label.as_str()) + } else { + (row.run_label.as_str()) + } + (row.reason.as_str()) + if row.remove { +
+ + +
+ } +
+
+ } +

(hint)

+
+ }) +} + +fn tab_class(on: bool) -> &'static str { + if on { "issue-tab on" } else { "issue-tab" } +} diff --git a/crates/forge-web/src/pages/mod.rs b/crates/forge-web/src/pages/mod.rs index 560238a..969d653 100644 --- a/crates/forge-web/src/pages/mod.rs +++ b/crates/forge-web/src/pages/mod.rs @@ -61,6 +61,7 @@ pub mod labels_css; pub mod labels_page; pub mod login; pub mod media; +pub mod merge_queue; pub mod milestones_page; pub mod new_repo; pub mod not_found_page; diff --git a/crates/forge-web/src/pages/pull_view.rs b/crates/forge-web/src/pages/pull_view.rs index 231a762..2d63e16 100644 --- a/crates/forge-web/src/pages/pull_view.rs +++ b/crates/forge-web/src/pages/pull_view.rs @@ -36,7 +36,7 @@ use crate::pages::pulls_merge::{ ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED, ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING, ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, ERR_NOT_UP_TO_DATE, - ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, merge_gate, + ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, merge_gate, }; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, load_repo}; @@ -297,6 +297,10 @@ struct FlowView { auto_on: Option<(String, String)>, /// Auto-merge can be enabled: the action. auto_enable: Option, + /// The pull request waits in the merge queue: its position line and the remove action. + queue_position: Option<(String, String)>, + /// The pull request can join the merge queue: the action. + queue_add: Option, } /// The mergeability status and, for writers on a clean branch, the merge form. `tone` is one of @@ -329,7 +333,14 @@ async fn merge_box( draft_toggle, auto_on, auto_enable, + queue_position, + queue_add, } = flow; + let queue_add_label = + crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::AddToMergeQueue); + let queue_remove_label = + crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::RemoveFromQueue); + let queue_hint = crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::MergeQueueHint); let reload_text = g::t(lang, K::ReloadToCheck); let style_legend = g::t(lang, K::MergeStyleLegend); let style_merge = g::t(lang, K::StyleMergeCommit); @@ -391,6 +402,25 @@ async fn merge_box(
} + if let Some((text, action)) = queue_position { +
+ +

(text.as_str())

+ +
+ } + if let Some(action) = queue_add { +
+ +

(queue_hint)

+ + +
+ } if let Some((text, action)) = auto_on {
@@ -643,11 +673,23 @@ async fn pull_conversation( } else { None }; - let blocked = gate - .as_ref() - .and_then(|gate| gate.blocked()) - .and_then(|code| merge_error_text(lang, code)) - .map(str::to_owned); + // A branch that requires the merge queue tests the pull request on the current tip, so an + // outdated head does not block it. + let queue_required = + crate::merge_queue::requires_queue(state, &ctx.repo, &pr.base_branch).await?; + let queue_blocker = gate.as_ref().and_then(|gate| { + gate.blockers() + .into_iter() + .find(|code| !(queue_required && *code == ERR_NOT_UP_TO_DATE)) + }); + let blocked = if queue_required { + queue_blocker.and_then(|code| merge_error_text(lang, code)) + } else { + gate.as_ref() + .and_then(|gate| gate.blocked()) + .and_then(|code| merge_error_text(lang, code)) + } + .map(str::to_owned); let approvals = gate .as_ref() .filter(|gate| gate.rule.required_approvals > 0) @@ -695,7 +737,35 @@ async fn pull_conversation( let auto_waiting = gate .as_ref() .is_some_and(|gate| !gate.blockers().is_empty() && gate.waiting_only()); + let queue_entry = match (open, queue_required) { + (true, true) => state.store.queue_entry_for_pull(&pr.issue.id).await?, + _ => None, + }; + let queue_position = match queue_entry.as_ref() { + Some(entry) => state + .store + .queue_for_branch(&ctx.repo.id, &entry.branch) + .await? + .iter() + .position(|waiting| waiting.id == entry.id) + .map(|index| index + 1), + None => None, + }; + let queue_can_add = open + && can_write + && queue_required + && queue_entry.is_none() + && pr.mergeable != Mergeable::Conflict + && pr.head_repo_id.is_some() + && blocked.is_none(); let flow = FlowView { + queue_position: queue_position.filter(|_| can_write).map(|position| { + ( + crate::i18n::merge_queue::position_text(lang, position), + format!("{href}/merge-queue/remove"), + ) + }), + queue_add: queue_can_add.then(|| format!("{href}/merge-queue")), csrf: csrf.clone(), draft_toggle: (open && !archived @@ -722,6 +792,7 @@ async fn pull_conversation( }), auto_enable: (open && can_write + && !queue_required && pr.auto_merge.is_none() && auto_waiting && pr.mergeable != Mergeable::Conflict @@ -730,6 +801,7 @@ async fn pull_conversation( }; let merge_form = if open && can_write + && !queue_required && pr.mergeable == Mergeable::Clean && pr.head_repo_id.is_some() && blocked.is_none() @@ -862,6 +934,12 @@ fn merge_error_text(lang: Lang, code: &str) -> Option<&'static str> { ERR_NEEDS_CHECKS => g::t(lang, K::ErrNeedsChecks), ERR_REBASE_CONFLICT => g::t(lang, K::ErrRebaseConflict), ERR_AUTO_MERGE_BLOCKED => g::t(lang, K::ErrAutoMergeBlocked), + ERR_QUEUE_REQUIRED => { + crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::ErrQueueRequired) + } + ERR_QUEUE_ALREADY => { + crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::ErrQueueAlready) + } _ => return None, }) } diff --git a/crates/forge-web/src/pages/pulls_list.rs b/crates/forge-web/src/pages/pulls_list.rs index f48ed9b..692aa9d 100644 --- a/crates/forge-web/src/pages/pulls_list.rs +++ b/crates/forge-web/src/pages/pulls_list.rs @@ -12,6 +12,7 @@ use topcoat::context::{Cx, app_context}; use topcoat::router::{page, path_param, query_params}; use topcoat::view::{View, view}; +use crate::i18n::merge_queue as mq; use crate::i18n::pulls::{self as g, K}; use crate::i18n::{self, Lang}; use crate::pages::issues_list::{ @@ -246,6 +247,7 @@ async fn pulls_list_page(cx: &Cx) -> Result { let can_create = ctx.viewer.is_some() && !ctx.repo.archived; let compare_href = repo_href(&owner_name, &repo_name, "compare", ""); + let queue_href = repo_href(&owner_name, &repo_name, "merge-queue", ""); let labels_href = repo_href(&owner_name, &repo_name, "labels.css", ""); let title = g::list_title(lang, &owner_name, &repo_name); let empty_text = if open_count + closed_count == 0 { @@ -269,6 +271,7 @@ async fn pulls_list_page(cx: &Cx) -> Result { (all_text.as_str())
+ (mq::t(lang, mq::K::MergeQueueTitle)) if can_create { (g::t(lang, K::NewPullRequest)) } diff --git a/crates/forge-web/src/pages/pulls_merge.rs b/crates/forge-web/src/pages/pulls_merge.rs index ddf572e..94ecbc6 100644 --- a/crates/forge-web/src/pages/pulls_merge.rs +++ b/crates/forge-web/src/pages/pulls_merge.rs @@ -68,6 +68,8 @@ pub const ERR_DRAFT: &str = "draft"; pub const ERR_NEEDS_CHECKS: &str = "needs_checks"; pub const ERR_REBASE_CONFLICT: &str = "rebase_conflict"; pub const ERR_AUTO_MERGE_BLOCKED: &str = "auto_merge_blocked"; +pub const ERR_QUEUE_REQUIRED: &str = "queue_required"; +pub const ERR_QUEUE_ALREADY: &str = "queue_already"; const REBASE_CONFLICT_MSG: &str = "Rebase failed: a commit does not apply cleanly on the base branch. Resolve the conflicts or use another merge style."; const CONFLICTS_MSG: &str = "This branch has conflicts that must be resolved"; @@ -140,6 +142,9 @@ async fn merge_post(cx: &Cx, Form(form): Form) -> Result { if let Some(code) = merge_gate(state, &ctx.repo, &pr).await?.blocked() { return back_to_pull(&pull_href, code); } + if crate::merge_queue::requires_queue(state, &ctx.repo, &pr.base_branch).await? { + return back_to_pull(&pull_href, ERR_QUEUE_REQUIRED); + } let style = if form.style.is_empty() { MergeStyle::Merge } else { @@ -387,11 +392,45 @@ pub async fn perform_merge( } }, }; + let new = match merge_commit(state, repo, pr, viewer, style, message, &base_tip).await? { + Ok(new) => new, + Err(refusal) => return Ok(refusal), + }; + + match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await { + Ok(()) => {} + Err(forge_git::error::Error::RefMoved(_)) => { + return Ok(refused(StatusCode::CONFLICT, MOVED_MSG)); + } + Err(e) => return Err(e.into()), + } + + finish_merge(state, repo, pr, viewer, &refname, &base_tip, &new).await; + Ok(MergeOutcome::Merged { commit: new }) +} + +/// The commit that merging `pr` into `base_tip` makes in `style`, committed as `committer`. No ref +/// moves. A refusal the caller can act on comes back as the inner `Err`. Fast-forward returns the +/// head itself. +pub async fn merge_commit( + state: &AppState, + repo: &forge_core::Repo, + pr: &PullRequest, + committer: &User, + style: MergeStyle, + message: Option<&str>, + base_tip: &str, +) -> forge_core::Result> { + let base_path = repo_path(&state.git.data_dir, &repo.id)?; + let base_tip = base_tip.to_owned(); + let viewer = committer; let head = pr.head_oid.as_str(); let tree = match check_merge(&state.git, &base_path, &base_tip, head).await? { MergeCheck::Clean { tree } => tree, - MergeCheck::Conflict { .. } => return Ok(refused(StatusCode::CONFLICT, CONFLICTS_MSG)), - MergeCheck::UpToDate => return Ok(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG)), + MergeCheck::Conflict { .. } => { + return Ok(Err(refused(StatusCode::CONFLICT, CONFLICTS_MSG))); + } + MergeCheck::UpToDate => return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))), }; let now = now_unix(); @@ -403,7 +442,7 @@ pub async fn perform_merge( let new = match style { MergeStyle::FastForward => { if !is_ancestor(&state.git, &base_path, &base_tip, head).await? { - return Ok(refused(StatusCode::CONFLICT, FF_MSG)); + return Ok(Err(refused(StatusCode::CONFLICT, FF_MSG))); } head.to_owned() } @@ -411,10 +450,10 @@ pub async fn perform_merge( match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? { RebaseResult::Clean { tip, count } if count > 0 => tip, RebaseResult::Clean { .. } => { - return Ok(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG)); + return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))); } RebaseResult::Conflict { .. } => { - return Ok(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG)); + return Ok(Err(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG))); } } } @@ -464,22 +503,22 @@ pub async fn perform_merge( .await? } }; + Ok(Ok(new)) +} - match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await { - Ok(()) => {} - Err(forge_git::error::Error::RefMoved(_)) => { - return Ok(refused(StatusCode::CONFLICT, MOVED_MSG)); - } - Err(e) => return Err(e.into()), - } - - // The ref has moved, so the merge happened. Post-merge steps that fail are logged, not - // reported: the viewer's merge is already in place. - match state - .store - .mark_merged(&pr.issue.id, &viewer.id, &new) - .await - { +/// The work after a merge moved `refname` from `base_tip` to `new`: the pull request is marked +/// merged, its events and notifications go out, and the ref update runs its post-update work. +/// Failures here are logged, not reported: the merge is already in place. +pub async fn finish_merge( + state: &AppState, + repo: &forge_core::Repo, + pr: &PullRequest, + viewer: &User, + refname: &str, + base_tip: &str, + new: &str, +) { + match state.store.mark_merged(&pr.issue.id, &viewer.id, new).await { Ok(()) => { let sender = Sender::of(viewer); emit_item_action(state, repo, &sender, true, pr.issue.number, "merged").await; @@ -490,10 +529,14 @@ pub async fn perform_merge( } } trigger_maintenance(&state.git, &repo.id); - if let Err(e) = after_ref_update(state, repo, &viewer.id, &refname, &base_tip, &new).await { + // Boxed: the queue lands through this path, and the post-update work can reach the queue again. + if let Err(e) = Box::pin(after_ref_update( + state, repo, &viewer.id, refname, base_tip, new, + )) + .await + { tracing::error!(error = %e, repo_id = %repo.id, ref_name = %refname, "merge: post-update failed"); } - Ok(MergeOutcome::Merged { commit: new }) } /// The address written into a commit for `user`: their email, or a noreply address on this diff --git a/crates/forge-web/src/pages/repo_settings.rs b/crates/forge-web/src/pages/repo_settings.rs index 333ce08..d8ab69e 100644 --- a/crates/forge-web/src/pages/repo_settings.rs +++ b/crates/forge-web/src/pages/repo_settings.rs @@ -30,6 +30,7 @@ use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::{require_csrf, require_user}; +use crate::i18n::merge_queue as mq; use crate::i18n::repo_admin::{self as g, K}; use crate::i18n::{self, Lang}; use crate::pages::discussion_settings::discussions_card; @@ -127,6 +128,8 @@ struct BranchForm { require_up_to_date: Option, #[serde(default)] restrict_push: Option, + #[serde(default)] + require_merge_queue: Option, /// Required check contexts, separated by commas or new lines. #[serde(default)] required_checks: String, @@ -439,6 +442,7 @@ fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result String { if rule.restrict_push { parts.push(g::t(lang, K::RuleRestrictPush).to_owned()); } + if rule.require_merge_queue { + parts.push(mq::t(lang, mq::K::RuleMergeQueue).to_owned()); + } if !rule.required_checks.is_empty() { parts.push(g::checks_count(lang, rule.required_checks.len())); } @@ -530,6 +537,7 @@ async fn branch_rule_form( block_on_changes_requested: bool, require_up_to_date: bool, restrict_push: bool, + require_merge_queue: bool, required_checks: String, contexts: Vec, error: Option, @@ -570,6 +578,11 @@ async fn branch_rule_form( (g::t(lang, K::RestrictPush)) + +

(mq::t(lang, mq::K::RequireMergeQueueHint))