forge
Explore
Log in

Don't you dare go Hollow

Merge queue so the protected branch only receives tested commits

Browse files at this commit

05cd9ba52f48cf9402aa0494c63de02716473e84Ahmet Kaan GümüşParent: 8ae0722
  • feat
    • merge queue so the protected branch only receives tested commits
Show full message
✨ feat: merge queue so the protected branch only receives tested commits
crates/forge-ci/src/config.rsmodified+11 -0
@@ -153,6 +153,9 @@ pub struct Triggers {
153 /// Defaults to `true`. A push to a branch cancels the queued and running runs of153 /// Defaults to `true`. A push to a branch cancels the queued and running runs of
154 /// older commits on that branch.154 /// older commits on that branch.
155 pub cancel_superseded: bool,155 pub cancel_superseded: bool,
156+ /// Runs the workflow on each merge queue candidate. Without it, a candidate runs the `push`
157+ /// jobs of its target branch (see `docs/merge-queue.md`).
158+ pub merge_queue: bool,
156 /// 5-field cron expressions in UTC, e.g. `"0 3 * * *"`. The server queues a run of the default159 /// 5-field cron expressions in UTC, e.g. `"0 3 * * *"`. The server queues a run of the default
157 /// branch head at each match.160 /// branch head at each match.
158 pub schedule: Vec<String>,161 pub schedule: Vec<String>,
@@ -166,6 +169,7 @@ impl Default for Triggers {
166 pull_request: false,169 pull_request: false,
167 manual: true,170 manual: true,
168 cancel_superseded: true,171 cancel_superseded: true,
172+ merge_queue: false,
169 schedule: Vec::new(),173 schedule: Vec::new(),
170 }174 }
171 }175 }
@@ -295,6 +299,10 @@ pub enum Event<'a> {
295 Manual,299 Manual,
296 /// A `[on] schedule` tick.300 /// A `[on] schedule` tick.
297 Schedule,301 Schedule,
302+ /// A merge queue candidate for `branch`, the target branch.
303+ MergeQueue {
304+ branch: &'a str,
305+ },
298 }306 }
299 307
300 /// Parses and validates a `ci.toml` document.308 /// Parses and validates a `ci.toml` document.
@@ -330,6 +338,9 @@ impl CiConfig {
330 Event::PullRequest => self.on.pull_request,338 Event::PullRequest => self.on.pull_request,
331 Event::Manual => self.on.manual,339 Event::Manual => self.on.manual,
332 Event::Schedule => !self.on.schedule.is_empty(),340 Event::Schedule => !self.on.schedule.is_empty(),
341+ Event::MergeQueue { branch } => {
342+ self.on.merge_queue || matches_any(&self.on.push, branch)
343+ }
333 }344 }
334 }345 }
335 346
crates/forge-core/migrations/0061_merge_queue.sqladded+30 -0
@@ -0,0 +1,30 @@
1+-- Merge queue. A protected branch with `require_merge_queue` only moves to commits that CI tested:
2+-- each queued pull request is merged onto the current target tip in a temporary ref, that commit
3+-- is tested, and the target moves to it only if it has not moved since.
4+ALTER TABLE branch_protections ADD COLUMN require_merge_queue INTEGER NOT NULL DEFAULT 0;
5+
6+-- One row per pull request that entered the queue. `state` is queued, testing, merging, failed or
7+-- removed; the last two are finished rows (`finished_at` set) kept for the queue history.
8+-- `base_oid` is the target tip the candidate was built on, `tested_oid` the candidate commit, and
9+-- `run_id` the CI run that tests it. `reason` says why a finished row was removed.
10+CREATE TABLE merge_queue (
11+ id TEXT PRIMARY KEY,
12+ repo_id TEXT NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
13+ branch TEXT NOT NULL,
14+ issue_id TEXT NOT NULL REFERENCES issues(id) ON DELETE CASCADE,
15+ pull_number INTEGER NOT NULL,
16+ merge_style TEXT NOT NULL,
17+ state TEXT NOT NULL,
18+ seq INTEGER NOT NULL,
19+ enqueued_by TEXT NOT NULL REFERENCES users(id),
20+ enqueued_at TEXT NOT NULL,
21+ updated_at TEXT NOT NULL,
22+ finished_at TEXT NULL,
23+ reason TEXT NULL,
24+ base_oid TEXT NULL,
25+ tested_oid TEXT NULL,
26+ test_ref TEXT NULL,
27+ run_id TEXT NULL
28+);
29+CREATE INDEX merge_queue_branch ON merge_queue (repo_id, branch, finished_at, seq);
30+CREATE INDEX merge_queue_issue ON merge_queue (issue_id, finished_at);
crates/forge-core/src/lib.rsmodified+1 -0
@@ -13,6 +13,7 @@ pub mod issue_refs;
13 pub mod issues;13 pub mod issues;
14 pub mod lfs_token;14 pub mod lfs_token;
15 pub mod mail;15 pub mod mail;
16+pub mod merge_queue;
16 pub mod mirrors;17 pub mod mirrors;
17 pub mod model;18 pub mod model;
18 pub mod names;19 pub mod names;
crates/forge-core/src/merge_queue.rsadded+89 -0
@@ -0,0 +1,89 @@
1+//! The merge queue: pull requests waiting to be merged into a protected branch that requires the
2+//! queue. Each entry is `queued`, then `testing` (its candidate commit runs CI), then `merging`
3+//! (the target moves to the tested commit). An entry finishes as `failed` or `removed`.
4+
5+use crate::error::{Error, Result};
6+use crate::pulls::MergeStyle;
7+
8+/// Where an entry is in the queue.
9+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10+pub enum QueueState {
11+ Queued,
12+ Testing,
13+ Merging,
14+ Failed,
15+ Removed,
16+}
17+
18+impl QueueState {
19+ pub fn as_str(self) -> &'static str {
20+ match self {
21+ QueueState::Queued => "queued",
22+ QueueState::Testing => "testing",
23+ QueueState::Merging => "merging",
24+ QueueState::Failed => "failed",
25+ QueueState::Removed => "removed",
26+ }
27+ }
28+
29+ /// Whether the entry still waits for the queue (queued, testing or merging).
30+ pub fn is_active(self) -> bool {
31+ matches!(
32+ self,
33+ QueueState::Queued | QueueState::Testing | QueueState::Merging
34+ )
35+ }
36+}
37+
38+impl std::str::FromStr for QueueState {
39+ type Err = Error;
40+
41+ fn from_str(s: &str) -> Result<Self> {
42+ Ok(match s {
43+ "queued" => QueueState::Queued,
44+ "testing" => QueueState::Testing,
45+ "merging" => QueueState::Merging,
46+ "failed" => QueueState::Failed,
47+ "removed" => QueueState::Removed,
48+ other => {
49+ return Err(Error::Database(format!(
50+ "unknown merge queue state {other}"
51+ )));
52+ }
53+ })
54+ }
55+}
56+
57+/// One pull request in the queue.
58+#[derive(Debug, Clone, PartialEq, Eq)]
59+pub struct QueueEntry {
60+ pub id: String,
61+ pub repo_id: String,
62+ pub branch: String,
63+ pub issue_id: String,
64+ pub pull_number: i64,
65+ pub merge_style: MergeStyle,
66+ pub state: QueueState,
67+ /// Enqueue order within the branch. Smaller entries go first.
68+ pub seq: i64,
69+ pub enqueued_by: String,
70+ pub enqueued_at: String,
71+ pub updated_at: String,
72+ pub finished_at: Option<String>,
73+ /// Why a finished entry ended: `merged`, `removed`, `closed`, `head_changed`, `conflict` or
74+ /// `tests_failed`.
75+ pub reason: Option<String>,
76+ /// The target tip the candidate was built on.
77+ pub base_oid: Option<String>,
78+ /// The candidate commit under test.
79+ pub tested_oid: Option<String>,
80+ /// The temporary ref that names the candidate.
81+ pub test_ref: Option<String>,
82+ /// The CI run that tests the candidate.
83+ pub run_id: Option<String>,
84+}
85+
86+/// The temporary ref that names a candidate of `branch` for pull request `number`.
87+pub fn test_ref_name(branch: &str, number: i64) -> String {
88+ format!("refs/forge/merge-queue/{branch}/{number}")
89+}
crates/forge-core/src/protection.rsmodified+8 -0
@@ -23,6 +23,9 @@ pub struct BranchRule {
23 /// Direct pushes to the branch are rejected for everyone but repo admins. Merges through23 /// Direct pushes to the branch are rejected for everyone but repo admins. Merges through
24 /// pull requests are unaffected.24 /// pull requests are unaffected.
25 pub restrict_push: bool,25 pub restrict_push: bool,
26+ /// Merges go through the merge queue: the merge box queues the pull request, and the queue
27+ /// moves the branch only to commits CI tested. Direct merges are refused.
28+ pub require_merge_queue: bool,
26 /// Commit status contexts (CI job names such as `ci/test`, or any reported context) that must29 /// Commit status contexts (CI job names such as `ci/test`, or any reported context) that must
27 /// all be `success` on the pull request head before it can merge.30 /// all be `success` on the pull request head before it can merge.
28 pub required_checks: Vec<String>,31 pub required_checks: Vec<String>,
@@ -38,6 +41,7 @@ pub struct RuleFlags {
38 pub block_on_changes_requested: bool,41 pub block_on_changes_requested: bool,
39 pub require_up_to_date: bool,42 pub require_up_to_date: bool,
40 pub restrict_push: bool,43 pub restrict_push: bool,
44+ pub require_merge_queue: bool,
41 pub required_checks: Vec<String>,45 pub required_checks: Vec<String>,
42 }46 }
43 47
@@ -61,6 +65,7 @@ pub struct Protection {
61 pub block_on_changes_requested: bool,65 pub block_on_changes_requested: bool,
62 pub require_up_to_date: bool,66 pub require_up_to_date: bool,
63 pub restrict_push: bool,67 pub restrict_push: bool,
68+ pub require_merge_queue: bool,
64 pub required_checks: Vec<String>,69 pub required_checks: Vec<String>,
65 }70 }
66 71
@@ -235,6 +240,7 @@ pub fn effective(rules: &[BranchRule], default_branch: &str, branch: &str) -> Pr
235 block_on_changes_requested: rule.block_on_changes_requested,240 block_on_changes_requested: rule.block_on_changes_requested,
236 require_up_to_date: rule.require_up_to_date,241 require_up_to_date: rule.require_up_to_date,
237 restrict_push: rule.restrict_push,242 restrict_push: rule.restrict_push,
243+ require_merge_queue: rule.require_merge_queue,
238 required_checks: rule.required_checks.clone(),244 required_checks: rule.required_checks.clone(),
239 };245 };
240 }246 }
@@ -268,6 +274,7 @@ mod tests {
268 block_on_changes_requested: false,274 block_on_changes_requested: false,
269 require_up_to_date: false,275 require_up_to_date: false,
270 restrict_push: false,276 restrict_push: false,
277+ require_merge_queue: false,
271 required_checks: Vec::new(),278 required_checks: Vec::new(),
272 created_at: created.into(),279 created_at: created.into(),
273 }280 }
@@ -381,6 +388,7 @@ mod tests {
381 block_on_changes_requested: true,388 block_on_changes_requested: true,
382 require_up_to_date: true,389 require_up_to_date: true,
383 restrict_push: true,390 restrict_push: true,
391+ require_merge_queue: false,
384 required_checks: Vec::new(),392 required_checks: Vec::new(),
385 }393 }
386 );394 );
crates/forge-core/src/store/merge_queue.rsadded+272 -0
@@ -0,0 +1,272 @@
1+//! Merge queue rows. The engine that moves entries along lives in forge-web (`merge_queue`); every
2+//! transition here is a conditional write, so two events that race on one entry cannot both win.
3+
4+use turso::Value;
5+
6+use super::issues::finish;
7+use super::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
8+use crate::error::{Error, Result};
9+use crate::merge_queue::{QueueEntry, QueueState};
10+use crate::pulls::MergeStyle;
11+use crate::time::now_stamp;
12+
13+const QUEUE_COLS: &str = "id, repo_id, branch, issue_id, pull_number, merge_style, state, seq, \
14+ enqueued_by, enqueued_at, updated_at, finished_at, reason, base_oid, tested_oid, test_ref, run_id";
15+
16+/// Finished entries shown in the queue history.
17+const HISTORY_LIMIT: i64 = 30;
18+
19+impl Store {
20+ /// Adds a pull request to the end of the branch queue. Fails with `Conflict` when the pull
21+ /// request already waits in a queue.
22+ pub async fn enqueue_pull(
23+ &self,
24+ repo_id: &str,
25+ branch: &str,
26+ issue_id: &str,
27+ pull_number: i64,
28+ style: MergeStyle,
29+ user_id: &str,
30+ ) -> Result<QueueEntry> {
31+ let conn = self.inner.conn.lock().await;
32+ let tx = conn.unchecked_transaction().await.map_err(db_err)?;
33+ let outcome: Result<QueueEntry> = async {
34+ let waiting = fetch_opt(
35+ &tx,
36+ "SELECT id FROM merge_queue WHERE issue_id = ?1 AND finished_at IS NULL LIMIT 1",
37+ (issue_id.to_string(),),
38+ |row| col_text(row, 0),
39+ )
40+ .await?;
41+ if waiting.is_some() {
42+ return Err(Error::Conflict("pull request is already in the merge queue".into()));
43+ }
44+ let seq = fetch_opt(
45+ &tx,
46+ "SELECT COALESCE(MAX(seq), 0) + 1 FROM merge_queue WHERE repo_id = ?1 AND branch = ?2",
47+ (repo_id.to_string(), branch.to_string()),
48+ |row| col_int(row, 0),
49+ )
50+ .await?
51+ .unwrap_or(1);
52+ let id = new_id();
53+ let now = now_stamp();
54+ tx.execute(
55+ "INSERT INTO merge_queue (id, repo_id, branch, issue_id, pull_number, merge_style, \
56+ state, seq, enqueued_by, enqueued_at, updated_at) \
57+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'queued', ?7, ?8, ?9, ?9)",
58+ (
59+ id.clone(),
60+ repo_id.to_string(),
61+ branch.to_string(),
62+ issue_id.to_string(),
63+ pull_number,
64+ style.as_str().to_string(),
65+ seq,
66+ user_id.to_string(),
67+ now,
68+ ),
69+ )
70+ .await
71+ .map_err(db_err)?;
72+ fetch_opt(
73+ &tx,
74+ &format!("SELECT {QUEUE_COLS} FROM merge_queue WHERE id = ?1"),
75+ (id,),
76+ map_entry,
77+ )
78+ .await?
79+ .ok_or(Error::NotFound)
80+ }
81+ .await;
82+ finish(tx, outcome).await
83+ }
84+
85+ /// The waiting entries of one branch, in queue order (the first is the head).
86+ pub async fn queue_for_branch(&self, repo_id: &str, branch: &str) -> Result<Vec<QueueEntry>> {
87+ let conn = self.read_conn().await;
88+ fetch_all(
89+ &conn,
90+ &format!(
91+ "SELECT {QUEUE_COLS} FROM merge_queue WHERE repo_id = ?1 AND branch = ?2 \
92+ AND finished_at IS NULL ORDER BY seq"
93+ ),
94+ (repo_id.to_string(), branch.to_string()),
95+ map_entry,
96+ )
97+ .await
98+ }
99+
100+ /// The waiting entry of a pull request, if it waits in a queue.
101+ pub async fn queue_entry_for_pull(&self, issue_id: &str) -> Result<Option<QueueEntry>> {
102+ let conn = self.read_conn().await;
103+ fetch_opt(
104+ &conn,
105+ &format!(
106+ "SELECT {QUEUE_COLS} FROM merge_queue WHERE issue_id = ?1 AND finished_at IS NULL \
107+ LIMIT 1"
108+ ),
109+ (issue_id.to_string(),),
110+ map_entry,
111+ )
112+ .await
113+ }
114+
115+ /// The waiting entries of a repo (all branches, queue order) followed by its most recent
116+ /// finished entries.
117+ pub async fn queue_overview(&self, repo_id: &str) -> Result<Vec<QueueEntry>> {
118+ let conn = self.read_conn().await;
119+ let mut out = fetch_all(
120+ &conn,
121+ &format!(
122+ "SELECT {QUEUE_COLS} FROM merge_queue WHERE repo_id = ?1 AND finished_at IS NULL \
123+ ORDER BY branch, seq"
124+ ),
125+ (repo_id.to_string(),),
126+ map_entry,
127+ )
128+ .await?;
129+ let history = fetch_all(
130+ &conn,
131+ &format!(
132+ "SELECT {QUEUE_COLS} FROM merge_queue WHERE repo_id = ?1 AND finished_at IS NOT NULL \
133+ ORDER BY finished_at DESC, seq DESC LIMIT {HISTORY_LIMIT}"
134+ ),
135+ (repo_id.to_string(),),
136+ map_entry,
137+ )
138+ .await?;
139+ out.extend(history);
140+ Ok(out)
141+ }
142+
143+ /// The entries of `repo_id` in `testing` whose candidate is `oid`.
144+ pub async fn queue_testing_on(&self, repo_id: &str, oid: &str) -> Result<Vec<QueueEntry>> {
145+ let conn = self.read_conn().await;
146+ fetch_all(
147+ &conn,
148+ &format!(
149+ "SELECT {QUEUE_COLS} FROM merge_queue WHERE repo_id = ?1 AND state = 'testing' \
150+ AND tested_oid = ?2"
151+ ),
152+ (repo_id.to_string(), oid.to_string()),
153+ map_entry,
154+ )
155+ .await
156+ }
157+
158+ /// Starts testing `base` plus the pull request as `tested` under `test_ref`. Works from
159+ /// `queued` (first start) and `testing` (a rebuild). Returns false when the entry has moved on.
160+ pub async fn queue_set_testing(
161+ &self,
162+ id: &str,
163+ base: &str,
164+ tested: &str,
165+ test_ref: &str,
166+ ) -> Result<bool> {
167+ self.queue_update(
168+ "UPDATE merge_queue SET state = 'testing', base_oid = ?2, tested_oid = ?3, test_ref = ?4, \
169+ run_id = NULL, updated_at = ?5 WHERE id = ?1 AND state IN ('queued', 'testing')",
170+ vec![
171+ Value::Text(id.to_string()),
172+ Value::Text(base.to_string()),
173+ Value::Text(tested.to_string()),
174+ Value::Text(test_ref.to_string()),
175+ Value::Text(now_stamp()),
176+ ],
177+ )
178+ .await
179+ }
180+
181+ /// Records the CI run that tests the entry's candidate.
182+ pub async fn queue_attach_run(&self, id: &str, run_id: &str) -> Result<()> {
183+ self.queue_update(
184+ "UPDATE merge_queue SET run_id = ?2, updated_at = ?3 WHERE id = ?1 AND finished_at IS NULL",
185+ vec![
186+ Value::Text(id.to_string()),
187+ Value::Text(run_id.to_string()),
188+ Value::Text(now_stamp()),
189+ ],
190+ )
191+ .await?;
192+ Ok(())
193+ }
194+
195+ /// Moves a tested entry to `merging`. False when another event already took it.
196+ pub async fn queue_set_merging(&self, id: &str) -> Result<bool> {
197+ self.queue_update(
198+ "UPDATE merge_queue SET state = 'merging', updated_at = ?2 WHERE id = ?1 AND state = 'testing'",
199+ vec![Value::Text(id.to_string()), Value::Text(now_stamp())],
200+ )
201+ .await
202+ }
203+
204+ /// Puts a `merging` entry back at the head of the queue, after the target moved under it.
205+ pub async fn queue_set_queued(&self, id: &str) -> Result<bool> {
206+ self.queue_update(
207+ "UPDATE merge_queue SET state = 'queued', base_oid = NULL, tested_oid = NULL, test_ref = NULL, \
208+ run_id = NULL, updated_at = ?2 WHERE id = ?1 AND state IN ('testing', 'merging')",
209+ vec![Value::Text(id.to_string()), Value::Text(now_stamp())],
210+ )
211+ .await
212+ }
213+
214+ /// Ends a waiting entry as `failed` or `removed` with `reason`. False if it already finished.
215+ pub async fn queue_finish(&self, id: &str, state: QueueState, reason: &str) -> Result<bool> {
216+ let now = now_stamp();
217+ self.queue_update(
218+ "UPDATE merge_queue SET state = ?2, reason = ?3, finished_at = ?4, updated_at = ?4 \
219+ WHERE id = ?1 AND finished_at IS NULL",
220+ vec![
221+ Value::Text(id.to_string()),
222+ Value::Text(state.as_str().to_string()),
223+ Value::Text(reason.to_string()),
224+ Value::Text(now),
225+ ],
226+ )
227+ .await
228+ }
229+
230+ /// One entry by id.
231+ pub async fn queue_entry(&self, id: &str) -> Result<Option<QueueEntry>> {
232+ let conn = self.read_conn().await;
233+ fetch_opt(
234+ &conn,
235+ &format!("SELECT {QUEUE_COLS} FROM merge_queue WHERE id = ?1"),
236+ (id.to_string(),),
237+ map_entry,
238+ )
239+ .await
240+ }
241+
242+ async fn queue_update(&self, sql: &str, params: Vec<Value>) -> Result<bool> {
243+ let conn = self.inner.conn.lock().await;
244+ let changed = conn.execute(sql, params).await.map_err(db_err)?;
245+ Ok(changed > 0)
246+ }
247+}
248+
249+/// Reads `QUEUE_COLS`.
250+fn map_entry(row: &turso::Row) -> Result<QueueEntry> {
251+ Ok(QueueEntry {
252+ id: col_text(row, 0)?,
253+ repo_id: col_text(row, 1)?,
254+ branch: col_text(row, 2)?,
255+ issue_id: col_text(row, 3)?,
256+ pull_number: col_int(row, 4)?,
257+ merge_style: col_text(row, 5)?
258+ .parse::<MergeStyle>()
259+ .map_err(|e| Error::Database(e.to_string()))?,
260+ state: col_text(row, 6)?.parse::<QueueState>()?,
261+ seq: col_int(row, 7)?,
262+ enqueued_by: col_text(row, 8)?,
263+ enqueued_at: col_text(row, 9)?,
264+ updated_at: col_text(row, 10)?,
265+ finished_at: col_opt_text(row, 11)?,
266+ reason: col_opt_text(row, 12)?,
267+ base_oid: col_opt_text(row, 13)?,
268+ tested_oid: col_opt_text(row, 14)?,
269+ test_ref: col_opt_text(row, 15)?,
270+ run_id: col_opt_text(row, 16)?,
271+ })
272+}
crates/forge-core/src/store/migrate.rsmodified+1 -0
@@ -101,6 +101,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[
101 (59, include_str!("../../migrations/0059_admin_alerts.sql")),101 (59, include_str!("../../migrations/0059_admin_alerts.sql")),
102 (60, include_str!("../../migrations/0060_runner_memory.sql")),102 (60, include_str!("../../migrations/0060_runner_memory.sql")),
103 (61, include_str!("../../migrations/0061_web_push.sql")),103 (61, include_str!("../../migrations/0061_web_push.sql")),
104+ (61, include_str!("../../migrations/0061_merge_queue.sql")),
104 ];105 ];
105 106
106 /// The highest migration version this binary knows about.107 /// The highest migration version this binary knows about.
crates/forge-core/src/store/mod.rsmodified+10 -4
@@ -18,6 +18,7 @@ pub mod issues;
18 pub mod labels;18 pub mod labels;
19 pub mod lfs;19 pub mod lfs;
20 pub mod mail;20 pub mod mail;
21+pub mod merge_queue;
21 pub mod migrate;22 pub mod migrate;
22 pub mod mirrors;23 pub mod mirrors;
23 pub mod notifications;24 pub mod notifications;
@@ -1247,7 +1248,8 @@ impl Store {
1247 }1248 }
1248 1249
1249 const BRANCH_RULE_COLS: &str = "id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \1250 const BRANCH_RULE_COLS: &str = "id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \
1250- required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks";1251+ required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks, \
1252+ require_merge_queue";
1251 1253
1252 // branch protection1254 // branch protection
1253 impl Store {1255 impl Store {
@@ -1281,13 +1283,14 @@ impl Store {
1281 let conn = self.inner.conn.lock().await;1283 let conn = self.inner.conn.lock().await;
1282 conn.execute(1284 conn.execute(
1283 "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \1285 "INSERT INTO branch_protections (id, repo_id, pattern, allow_force_push, allow_deletion, created_at, \
1284- required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks) \1286+ required_approvals, block_on_changes_requested, require_up_to_date, restrict_push, required_checks, \
1285- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11) \1287+ require_merge_queue) \
1288+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) \
1286 ON CONFLICT(repo_id, pattern) DO UPDATE SET allow_force_push = excluded.allow_force_push, \1289 ON CONFLICT(repo_id, pattern) DO UPDATE SET allow_force_push = excluded.allow_force_push, \
1287 allow_deletion = excluded.allow_deletion, required_approvals = excluded.required_approvals, \1290 allow_deletion = excluded.allow_deletion, required_approvals = excluded.required_approvals, \
1288 block_on_changes_requested = excluded.block_on_changes_requested, \1291 block_on_changes_requested = excluded.block_on_changes_requested, \
1289 require_up_to_date = excluded.require_up_to_date, restrict_push = excluded.restrict_push, \1292 require_up_to_date = excluded.require_up_to_date, restrict_push = excluded.restrict_push, \
1290- required_checks = excluded.required_checks",1293+ required_checks = excluded.required_checks, require_merge_queue = excluded.require_merge_queue",
1291 (1294 (
1292 new_id(),1295 new_id(),
1293 repo_id.to_string(),1296 repo_id.to_string(),
@@ -1300,6 +1303,7 @@ impl Store {
1300 i64::from(flags.require_up_to_date),1303 i64::from(flags.require_up_to_date),
1301 i64::from(flags.restrict_push),1304 i64::from(flags.restrict_push),
1302 checks_json,1305 checks_json,
1306+ i64::from(flags.require_merge_queue),
1303 ),1307 ),
1304 )1308 )
1305 .await1309 .await
@@ -1348,6 +1352,7 @@ fn map_branch_rule(row: &Row) -> Result<BranchRule> {
1348 restrict_push: col_bool(row, 9)?,1352 restrict_push: col_bool(row, 9)?,
1349 required_checks: serde_json::from_str(&col_text(row, 10)?)1353 required_checks: serde_json::from_str(&col_text(row, 10)?)
1350 .map_err(|e| Error::Database(format!("required_checks is not a JSON array: {e}")))?,1354 .map_err(|e| Error::Database(format!("required_checks is not a JSON array: {e}")))?,
1355+ require_merge_queue: col_bool(row, 11)?,
1351 })1356 })
1352 }1357 }
1353 1358
@@ -2188,6 +2193,7 @@ mod tests {
2188 block_on_changes_requested: true,2193 block_on_changes_requested: true,
2189 require_up_to_date: true,2194 require_up_to_date: true,
2190 restrict_push: true,2195 restrict_push: true,
2196+ require_merge_queue: true,
2191 required_checks: Vec::new(),2197 required_checks: Vec::new(),
2192 };2198 };
2193 let saved = store2199 let saved = store
crates/forge-git/src/pulls.rsmodified+24 -0
@@ -405,6 +405,30 @@ pub async fn update_ref_cas(
405 Err(failed("update-ref", &out))405 Err(failed("update-ref", &out))
406 }406 }
407 407
408+/// Points `refname` at `new`, whatever it pointed at before. Used for the temporary refs that name
409+/// a merge queue candidate; a rebuild replaces them.
410+pub async fn set_ref(env: &GitEnv, repo: &Path, refname: &str, new: &str) -> Result<()> {
411+ // Only the merge queue's temporary namespace is writable here, besides the usual checks.
412+ let queue_ok = refname
413+ .strip_prefix("refs/forge/merge-queue/")
414+ .is_some_and(valid_branch_rest);
415+ if !queue_ok {
416+ return Err(Error::InvalidInput(format!(
417+ "invalid ref name: {refname:?}"
418+ )));
419+ }
420+ validate_oid(new)?;
421+ let cmd = git(env, "update-ref")
422+ .git_dir(repo)
423+ .user_arg(refname)?
424+ .user_arg(new)?;
425+ let out = run_raw(cmd, None).await?;
426+ if out.status.success() {
427+ return Ok(());
428+ }
429+ Err(failed("update-ref", &out))
430+}
431+
408 /// Deletes `refname` only if it still points at `old`. `git update-ref -d <ref> <old>` checks the432 /// Deletes `refname` only if it still points at `old`. `git update-ref -d <ref> <old>` checks the
409 /// old value itself, so a ref that moved, or one that is already gone, gives `Error::RefMoved`433 /// old value itself, so a ref that moved, or one that is already gone, gives `Error::RefMoved`
410 /// and is left alone. The zero id is not accepted as `old`: a deletion needs a real value to434 /// and is left alone. The zero id is not accepted as `old`: a deletion needs a real value to
crates/forge-web/src/api/statuses.rsmodified+1 -0
@@ -108,6 +108,7 @@ async fn report_status(cx: &Cx, body: Body) -> topcoat::Result<Response> {
108 Err(e) => return Ok(*api::internal(e)),108 Err(e) => return Ok(*api::internal(e)),
109 };109 };
110 crate::automerge::on_status(state, &repo.id, &sha).await;110 crate::automerge::on_status(state, &repo.id, &sha).await;
111+ crate::merge_queue::on_status(state, &repo, &sha).await;
111 Ok(api::json(StatusCode::CREATED, &status_json(&saved)))112 Ok(api::json(StatusCode::CREATED, &status_json(&saved)))
112 }113 }
113 114
crates/forge-web/src/automerge.rsmodified+4 -0
@@ -73,6 +73,10 @@ pub async fn evaluate(state: &AppState, repo: &Repo, pr: &PullRequest) -> forge_
73 if pr.draft || pr.head_repo_id.is_none() {73 if pr.draft || pr.head_repo_id.is_none() {
74 return Ok(false);74 return Ok(false);
75 }75 }
76+ // A branch that requires the merge queue takes no direct merges, auto-merge included.
77+ if crate::merge_queue::requires_queue(state, repo, &pr.base_branch).await? {
78+ return Ok(false);
79+ }
76 if merge_gate(state, repo, pr).await?.blocked().is_some() {80 if merge_gate(state, repo, pr).await?.blocked().is_some() {
77 return Ok(false);81 return Ok(false);
78 }82 }
crates/forge-web/src/ci/live.rsmodified+12 -0
@@ -22,9 +22,21 @@ pub struct CiLive {
22 runs: Signals,22 runs: Signals,
23 repos: Signals,23 repos: Signals,
24 runners: Signals,24 runners: Signals,
25+ queues: Signals,
25 }26 }
26 27
27 impl CiLive {28 impl CiLive {
29+ /// Subscribes to changes of the merge queue of repo `repo_id`: an entry was added, moved or
30+ /// finished. Same rules as [`CiLive::subscribe_job`].
31+ pub fn subscribe_queue(&self, repo_id: &str) -> watch::Receiver<u64> {
32+ self.queues.subscribe(repo_id)
33+ }
34+
35+ /// Wakes the subscribers of the merge queue of repo `repo_id`.
36+ pub fn bump_queue(&self, repo_id: &str) {
37+ self.queues.bump(repo_id);
38+ }
39+
28 /// Subscribes to changes of job `job_id`. The receiver starts as seen, so a bump after this40 /// Subscribes to changes of job `job_id`. The receiver starts as seen, so a bump after this
29 /// call wakes it. Subscribe before the state you read, so a change in between is not lost.41 /// call wakes it. Subscribe before the state you read, so a change in between is not lost.
30 pub fn subscribe_job(&self, job_id: &str) -> watch::Receiver<u64> {42 pub fn subscribe_job(&self, job_id: &str) -> watch::Receiver<u64> {
crates/forge-web/src/ci/mod.rsmodified+2 -0
@@ -112,6 +112,8 @@ pub(crate) async fn publish(
112 return;112 return;
113 }113 }
114 crate::automerge::on_status(state, &repo.id, &run.commit_oid).await;114 crate::automerge::on_status(state, &repo.id, &run.commit_oid).await;
115+ // Boxed: a queue advance can start the next candidate's run, which publishes again.
116+ Box::pin(crate::merge_queue::on_status(state, repo, &run.commit_oid)).await;
115 }117 }
116 118
117 /// The person a CI status is recorded for: the run's actor, or the repo owner for a system run.119 /// The person a CI status is recorded for: the run's actor, or the repo owner for a system run.
crates/forge-web/src/ci/schedule.rsmodified+44 -0
@@ -288,6 +288,50 @@ pub(super) async fn scheduled_run(
288 Ok(Some(run))288 Ok(Some(run))
289 }289 }
290 290
291+/// Starts the run that tests a merge queue candidate `commit` of `branch`, named by the temporary
292+/// ref `test_ref`. The workflow of the candidate decides: `[on] merge_queue`, or the `push` jobs of
293+/// `branch`. `Ok(None)` when no run is wanted (no workflow, or it does not run for the candidate).
294+pub async fn merge_queue_run(
295+ state: &AppState,
296+ repo: &Repo,
297+ test_ref: &str,
298+ branch: &str,
299+ commit: &str,
300+ actor_id: &str,
301+ pull_number: i64,
302+) -> forge_core::Result<Option<CiRun>> {
303+ if !state.live().ci.enabled {
304+ return Ok(None);
305+ }
306+ let loaded = load(state, &repo.id, commit).await;
307+ let Plan::Run {
308+ jobs,
309+ config_error,
310+ warnings,
311+ ..
312+ } = plan_for(loaded, &Event::MergeQueue { branch })?
313+ else {
314+ return Ok(None);
315+ };
316+ let run = create(
317+ state,
318+ Request {
319+ repo,
320+ trigger: "merge_queue",
321+ git_ref: test_ref,
322+ commit,
323+ pull_number: Some(pull_number),
324+ actor_id,
325+ needs_approval: false,
326+ },
327+ jobs,
328+ config_error.as_deref(),
329+ &warnings,
330+ )
331+ .await?;
332+ Ok(Some(run))
333+}
334+
291 /// Creates the run, sets the statuses of its jobs (and `ci/config` for an error run), and wakes335 /// Creates the run, sets the statuses of its jobs (and `ci/config` for an error run), and wakes
292 /// the runner claims when a job is queued.336 /// the runner claims when a job is queued.
293 async fn create(337 async fn create(
crates/forge-web/src/i18n/merge_queue.rsadded+214 -0
@@ -0,0 +1,214 @@
1+//! Strings for the merge queue: the branch protection option, the pull request merge box and the
2+//! queue page. See `docs/merge-queue.md`.
3+
4+use super::Lang;
5+
6+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7+pub enum K {
8+ RequireMergeQueue,
9+ RequireMergeQueueHint,
10+ RuleMergeQueue,
11+ AddToMergeQueue,
12+ MergeQueueHint,
13+ RemoveFromQueue,
14+ MergeQueueTitle,
15+ MergeQueueNav,
16+ QueueWaiting,
17+ QueueHistory,
18+ QueueEmpty,
19+ QueueNoBranch,
20+ QueueColPosition,
21+ QueueColPull,
22+ QueueColBranch,
23+ QueueColState,
24+ QueueColBy,
25+ QueueColQueued,
26+ QueueColRun,
27+ QueueColReason,
28+ QueueNoRun,
29+ StateQueued,
30+ StateTesting,
31+ StateMerging,
32+ StateFailed,
33+ StateRemoved,
34+ ReasonMerged,
35+ ReasonRemoved,
36+ ReasonClosed,
37+ ReasonHeadChanged,
38+ ReasonConflict,
39+ ReasonTestsFailed,
40+ ReasonChecksFailed,
41+ ReasonPermission,
42+ ReasonBlocked,
43+ ReasonNoBranch,
44+ ErrQueueRequired,
45+ ErrQueueAlready,
46+}
47+
48+/// Every key, for the coverage test.
49+#[cfg(test)]
50+pub const ALL: &[K] = &[
51+ K::RequireMergeQueue,
52+ K::RequireMergeQueueHint,
53+ K::RuleMergeQueue,
54+ K::AddToMergeQueue,
55+ K::MergeQueueHint,
56+ K::RemoveFromQueue,
57+ K::MergeQueueTitle,
58+ K::MergeQueueNav,
59+ K::QueueWaiting,
60+ K::QueueHistory,
61+ K::QueueEmpty,
62+ K::QueueNoBranch,
63+ K::QueueColPosition,
64+ K::QueueColPull,
65+ K::QueueColBranch,
66+ K::QueueColState,
67+ K::QueueColBy,
68+ K::QueueColQueued,
69+ K::QueueColRun,
70+ K::QueueColReason,
71+ K::QueueNoRun,
72+ K::StateQueued,
73+ K::StateTesting,
74+ K::StateMerging,
75+ K::StateFailed,
76+ K::StateRemoved,
77+ K::ReasonMerged,
78+ K::ReasonRemoved,
79+ K::ReasonClosed,
80+ K::ReasonHeadChanged,
81+ K::ReasonConflict,
82+ K::ReasonTestsFailed,
83+ K::ReasonChecksFailed,
84+ K::ReasonPermission,
85+ K::ReasonBlocked,
86+ K::ReasonNoBranch,
87+ K::ErrQueueRequired,
88+ K::ErrQueueAlready,
89+];
90+
91+pub fn t(lang: Lang, key: K) -> &'static str {
92+ use K::*;
93+ use Lang::{En, Tr};
94+ match (key, lang) {
95+ (RequireMergeQueue, En) => "Require merge queue",
96+ (RequireMergeQueue, Tr) => "Birleştirme sırası iste",
97+ (RequireMergeQueueHint, En) => {
98+ "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."
99+ }
100+ (RequireMergeQueueHint, Tr) => {
101+ "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."
102+ }
103+ (RuleMergeQueue, En) => "merge queue required",
104+ (RuleMergeQueue, Tr) => "birleştirme sırası zorunlu",
105+ (AddToMergeQueue, En) => "Add to merge queue",
106+ (AddToMergeQueue, Tr) => "Birleştirme sırasına ekle",
107+ (MergeQueueHint, En) => {
108+ "This branch requires the merge queue. The pull request is tested on the current tip before it lands."
109+ }
110+ (MergeQueueHint, Tr) => {
111+ "Bu dal birleştirme sırası gerektirir. Çekme isteği inmeden önce güncel uç üzerinde test edilir."
112+ }
113+ (RemoveFromQueue, En) => "Remove from queue",
114+ (RemoveFromQueue, Tr) => "Sıradan çıkar",
115+ (MergeQueueTitle, En) => "Merge queue",
116+ (MergeQueueTitle, Tr) => "Birleştirme sırası",
117+ (MergeQueueNav, En) => "Merge queue",
118+ (MergeQueueNav, Tr) => "Birleştirme sırası",
119+ (QueueWaiting, En) => "Waiting",
120+ (QueueWaiting, Tr) => "Bekleyen",
121+ (QueueHistory, En) => "History",
122+ (QueueHistory, Tr) => "Geçmiş",
123+ (QueueEmpty, En) => "Nothing is waiting in the merge queue.",
124+ (QueueEmpty, Tr) => "Birleştirme sırasında bekleyen yok.",
125+ (QueueNoBranch, En) => {
126+ "No protected branch requires the merge queue. Turn it on in the branch protection settings."
127+ }
128+ (QueueNoBranch, Tr) => {
129+ "Birleştirme sırası isteyen korumalı bir dal yok. Dal koruma ayarlarından açabilirsiniz."
130+ }
131+ (QueueColPosition, En) => "Position",
132+ (QueueColPosition, Tr) => "Sıra",
133+ (QueueColPull, En) => "Pull request",
134+ (QueueColPull, Tr) => "Çekme isteği",
135+ (QueueColBranch, En) => "Branch",
136+ (QueueColBranch, Tr) => "Dal",
137+ (QueueColState, En) => "State",
138+ (QueueColState, Tr) => "Durum",
139+ (QueueColBy, En) => "Queued by",
140+ (QueueColBy, Tr) => "Ekleyen",
141+ (QueueColQueued, En) => "Queued",
142+ (QueueColQueued, Tr) => "Eklendi",
143+ (QueueColRun, En) => "CI run",
144+ (QueueColRun, Tr) => "CI çalıştırması",
145+ (QueueColReason, En) => "Reason",
146+ (QueueColReason, Tr) => "Neden",
147+ (QueueNoRun, En) => "No run",
148+ (QueueNoRun, Tr) => "Çalıştırma yok",
149+ (StateQueued, En) => "Queued",
150+ (StateQueued, Tr) => "Sırada",
151+ (StateTesting, En) => "Testing",
152+ (StateTesting, Tr) => "Test ediliyor",
153+ (StateMerging, En) => "Merging",
154+ (StateMerging, Tr) => "Birleştiriliyor",
155+ (StateFailed, En) => "Failed",
156+ (StateFailed, Tr) => "Başarısız",
157+ (StateRemoved, En) => "Removed",
158+ (StateRemoved, Tr) => "Çıkarıldı",
159+ (ReasonMerged, En) => "merged",
160+ (ReasonMerged, Tr) => "birleştirildi",
161+ (ReasonRemoved, En) => "removed by a person",
162+ (ReasonRemoved, Tr) => "biri tarafından çıkarıldı",
163+ (ReasonClosed, En) => "closed",
164+ (ReasonClosed, Tr) => "kapatıldı",
165+ (ReasonHeadChanged, En) => "the head changed",
166+ (ReasonHeadChanged, Tr) => "baş değişti",
167+ (ReasonConflict, En) => "conflicts with the branch",
168+ (ReasonConflict, Tr) => "dalla çakışıyor",
169+ (ReasonTestsFailed, En) => "the test run failed",
170+ (ReasonTestsFailed, Tr) => "test çalıştırması başarısız",
171+ (ReasonChecksFailed, En) => "a required check failed",
172+ (ReasonChecksFailed, Tr) => "zorunlu bir denetim başarısız",
173+ (ReasonPermission, En) => "the person who queued it can no longer merge",
174+ (ReasonPermission, Tr) => "sıraya ekleyen kişi artık birleştiremiyor",
175+ (ReasonBlocked, En) => "a merge check no longer passes",
176+ (ReasonBlocked, Tr) => "bir birleştirme denetimi artık geçmiyor",
177+ (ReasonNoBranch, En) => "the branch is gone",
178+ (ReasonNoBranch, Tr) => "dal artık yok",
179+ (ErrQueueRequired, En) => {
180+ "This branch requires the merge queue. Add the pull request to the queue instead."
181+ }
182+ (ErrQueueRequired, Tr) => {
183+ "Bu dal birleştirme sırası gerektiriyor. Bunun yerine çekme isteğini sıraya ekleyin."
184+ }
185+ (ErrQueueAlready, En) => "This pull request is already in the merge queue.",
186+ (ErrQueueAlready, Tr) => "Bu çekme isteği zaten birleştirme sırasında.",
187+ }
188+}
189+
190+/// The position line of a pull request in the queue.
191+pub fn position_text(lang: Lang, position: usize) -> String {
192+ match lang {
193+ Lang::En => format!("Position {position} in the merge queue"),
194+ Lang::Tr => format!("Birleştirme sırasında {position}. sırada"),
195+ }
196+}
197+
198+#[cfg(test)]
199+mod tests {
200+ use super::*;
201+
202+ #[test]
203+ fn every_key_has_english_and_turkish() {
204+ for key in ALL {
205+ assert!(!t(Lang::En, *key).is_empty(), "{key:?} has no English");
206+ assert!(!t(Lang::Tr, *key).is_empty(), "{key:?} has no Turkish");
207+ }
208+ }
209+
210+ #[test]
211+ fn position_line_counts_from_the_head() {
212+ assert_eq!(position_text(Lang::En, 2), "Position 2 in the merge queue");
213+ }
214+}
crates/forge-web/src/i18n/mod.rsmodified+1 -0
@@ -28,6 +28,7 @@ pub mod community;
28 pub mod integrations;28 pub mod integrations;
29 pub mod issues;29 pub mod issues;
30 pub mod link;30 pub mod link;
31+pub mod merge_queue;
31 pub mod migrate;32 pub mod migrate;
32 pub mod misc;33 pub mod misc;
33 pub mod orgs;34 pub mod orgs;
crates/forge-web/src/main.rsmodified+1 -0
@@ -35,6 +35,7 @@ mod lfs;
35 mod lfs_pointer;35 mod lfs_pointer;
36 mod live;36 mod live;
37 mod mail;37 mod mail;
38+mod merge_queue;
38 mod mirrors;39 mod mirrors;
39 mod notify;40 mod notify;
40 mod notify_hub;41 mod notify_hub;
crates/forge-web/src/merge_queue.rsadded+437 -0
@@ -0,0 +1,437 @@
1+//! The merge queue of a protected branch with `require_merge_queue` set.
2+//!
3+//! A pull request joins the queue of its base branch from its merge box. When it reaches the head
4+//! of the queue, the queue builds a candidate: the current target tip merged with the pull request
5+//! head, in the merge style the user chose, with no working tree. The candidate is named by the
6+//! temporary ref `refs/forge/merge-queue/{branch}/{number}`, and a CI run tests that ref. When the
7+//! run succeeds and the required checks are green on the candidate, the target moves from the tip
8+//! the candidate was built on to the candidate, as one compare-and-swap. If the target moved in
9+//! the meantime, the candidate is built again and tested again. A failing run removes the pull
10+//! request from the queue and comments on it.
11+//!
12+//! Nothing polls. Each step is a reaction: an enqueue, a commit status on a candidate, a head
13+//! change or close of a queued pull request, or a finished entry that lets the next one start.
14+
15+use forge_core::merge_queue::{QueueEntry, QueueState, test_ref_name};
16+use forge_core::protection::effective;
17+use forge_core::store::commit_status::StatusState;
18+use forge_core::{Action, IssueState, MergeStyle, Mergeable, PullRequest, Repo, User, authorize};
19+use forge_git::browse::default_branch_commit;
20+use forge_git::pulls::{set_ref, update_ref_cas};
21+use forge_git::repo::repo_path;
22+
23+use crate::ci::schedule::merge_queue_run;
24+use crate::notify::{self, Activity};
25+use crate::pages::pulls_merge::{
26+ ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE,
27+ ERR_QUEUE_ALREADY, MergeOutcome, finish_merge, merge_commit, merge_gate,
28+};
29+use crate::state::AppState;
30+
31+/// Whether the protection of `branch` routes merges through the queue. Direct merges are refused
32+/// then.
33+pub async fn requires_queue(
34+ state: &AppState,
35+ repo: &Repo,
36+ branch: &str,
37+) -> forge_core::Result<bool> {
38+ let rules = state.store.list_branch_rules(&repo.id).await?;
39+ Ok(effective(&rules, &repo.default_branch, branch).require_merge_queue)
40+}
41+
42+/// Adds `pr` to the queue of its base branch as `user`, who merges it with `style`. Returns the
43+/// refusal code when the pull request is not ready: the merge checks of the pull request apply
44+/// (approvals, changes requested, required checks on its head, conflicts). An outdated head does
45+/// not refuse, since the candidate is built on the current tip.
46+pub async fn enqueue(
47+ state: &AppState,
48+ repo: &Repo,
49+ pr: &PullRequest,
50+ user: &User,
51+ style: MergeStyle,
52+) -> forge_core::Result<std::result::Result<QueueEntry, &'static str>> {
53+ let gate = merge_gate(state, repo, pr).await?;
54+ if let Some(code) = gate
55+ .blockers()
56+ .into_iter()
57+ .find(|code| *code != ERR_NOT_UP_TO_DATE)
58+ {
59+ return Ok(Err(code));
60+ }
61+ if pr.mergeable == Mergeable::Conflict {
62+ return Ok(Err(ERR_CONFLICT));
63+ }
64+ match state
65+ .store
66+ .enqueue_pull(
67+ &repo.id,
68+ &pr.base_branch,
69+ &pr.issue.id,
70+ pr.issue.number,
71+ style,
72+ &user.id,
73+ )
74+ .await
75+ {
76+ Ok(entry) => {
77+ notify_changed(state, &repo.id);
78+ advance(state, repo, &pr.base_branch).await;
79+ Ok(Ok(entry))
80+ }
81+ Err(forge_core::Error::Conflict(_)) => Ok(Err(ERR_QUEUE_ALREADY)),
82+ Err(e) => Err(e),
83+ }
84+}
85+
86+/// Takes a waiting entry out of the queue, with `reason`. The caller starts the queue again with
87+/// `advance`. A candidate that is already testing keeps its CI run; its result is then ignored.
88+pub async fn remove(state: &AppState, repo: &Repo, entry: &QueueEntry, reason: &str) {
89+ match state
90+ .store
91+ .queue_finish(&entry.id, QueueState::Removed, reason)
92+ .await
93+ {
94+ Ok(true) => notify_changed(state, &repo.id),
95+ Ok(false) => {}
96+ Err(e) => {
97+ tracing::error!(error = %e, repo_id = %repo.id, "merge queue: removing an entry failed");
98+ }
99+ }
100+}
101+
102+/// A pull request's head moved or it was closed: if it waits in a queue, it leaves the queue and
103+/// the queue moves on.
104+pub async fn drop_pull(state: &AppState, repo: &Repo, issue_id: &str, reason: &str) {
105+ match state.store.queue_entry_for_pull(issue_id).await {
106+ Ok(Some(entry)) => {
107+ remove(state, repo, &entry, reason).await;
108+ advance(state, repo, &entry.branch).await;
109+ }
110+ Ok(None) => {}
111+ Err(e) => {
112+ tracing::error!(error = %e, repo_id = %repo.id, "merge queue: looking up a pull request failed");
113+ }
114+ }
115+}
116+
117+/// A commit status was written for `sha`. Each candidate testing at `sha` is evaluated again.
118+pub async fn on_status(state: &AppState, repo: &Repo, sha: &str) {
119+ let entries = match state.store.queue_testing_on(&repo.id, sha).await {
120+ Ok(entries) => entries,
121+ Err(e) => {
122+ tracing::error!(error = %e, repo_id = %repo.id, "merge queue: listing candidates failed");
123+ return;
124+ }
125+ };
126+ for entry in entries {
127+ match evaluate(state, repo, &entry.id).await {
128+ Ok(true) => advance(state, repo, &entry.branch).await,
129+ Ok(false) => {}
130+ Err(e) => {
131+ tracing::error!(error = %e, repo_id = %repo.id, "merge queue: evaluating a candidate failed");
132+ }
133+ }
134+ }
135+}
136+
137+/// Starts the head of the branch queue for as long as nothing is testing or merging. Failures
138+/// are logged; the queue keeps its state, so the next event retries.
139+pub async fn advance(state: &AppState, repo: &Repo, branch: &str) {
140+ if let Err(e) = advance_inner(state, repo, branch).await {
141+ tracing::error!(error = %e, repo_id = %repo.id, branch, "merge queue: advancing failed");
142+ }
143+}
144+
145+async fn advance_inner(state: &AppState, repo: &Repo, branch: &str) -> forge_core::Result<()> {
146+ loop {
147+ let entries = state.store.queue_for_branch(&repo.id, branch).await?;
148+ if entries
149+ .iter()
150+ .any(|e| matches!(e.state, QueueState::Testing | QueueState::Merging))
151+ {
152+ return Ok(());
153+ }
154+ let Some(head) = entries.into_iter().next() else {
155+ return Ok(());
156+ };
157+ let Some(pr) = state
158+ .store
159+ .pull_by_number(&repo.id, head.pull_number)
160+ .await?
161+ else {
162+ remove(state, repo, &head, "removed").await;
163+ continue;
164+ };
165+ if let Some(reason) = unready(state, repo, &pr).await? {
166+ remove(state, repo, &head, reason).await;
167+ continue;
168+ }
169+ if !start(state, repo, &pr, &head).await? {
170+ continue;
171+ }
172+ if !evaluate(state, repo, &head.id).await? {
173+ return Ok(());
174+ }
175+ }
176+}
177+
178+/// Why `pr` cannot be tested now, if it cannot.
179+async fn unready(
180+ state: &AppState,
181+ repo: &Repo,
182+ pr: &PullRequest,
183+) -> forge_core::Result<Option<&'static str>> {
184+ if pr.merged_at.is_some() || pr.issue.state != IssueState::Open {
185+ return Ok(Some("closed"));
186+ }
187+ if pr.head_repo_id.is_none() {
188+ return Ok(Some(ERR_HEAD_MISSING));
189+ }
190+ if pr.draft {
191+ return Ok(Some(ERR_DRAFT));
192+ }
193+ let gate = merge_gate(state, repo, pr).await?;
194+ let blocked = gate
195+ .blockers()
196+ .into_iter()
197+ .any(|code| !matches!(code, ERR_NEEDS_CHECKS | ERR_NOT_UP_TO_DATE));
198+ Ok(blocked.then_some("blocked"))
199+}
200+
201+/// Builds the candidate of the head entry on the current target tip, points the test ref at it
202+/// and starts its CI run. `Ok(false)` when the entry was failed (it could not be built) or moved
203+/// on meanwhile.
204+async fn start(
205+ state: &AppState,
206+ repo: &Repo,
207+ pr: &PullRequest,
208+ entry: &QueueEntry,
209+) -> forge_core::Result<bool> {
210+ let base_path = repo_path(&state.git.data_dir, &repo.id)?;
211+ let Some(base_tip) = default_branch_commit(&base_path, &entry.branch)? else {
212+ remove(state, repo, entry, "no_branch").await;
213+ return Ok(false);
214+ };
215+ let Some(user) = state.store.user_by_id(&entry.enqueued_by).await? else {
216+ remove(state, repo, entry, "removed").await;
217+ return Ok(false);
218+ };
219+ let tested =
220+ match merge_commit(state, repo, pr, &user, entry.merge_style, None, &base_tip).await? {
221+ Ok(oid) => oid,
222+ Err(MergeOutcome::Refused { message, .. }) => {
223+ let text = format!("could not build the merge with the target branch: {message}.");
224+ fail(state, repo, entry, pr, "conflict", &text).await?;
225+ return Ok(false);
226+ }
227+ Err(MergeOutcome::Merged { .. }) => return Ok(false),
228+ };
229+ let test_ref = test_ref_name(&entry.branch, entry.pull_number);
230+ set_ref(&state.git, &base_path, &test_ref, &tested).await?;
231+ if !state
232+ .store
233+ .queue_set_testing(&entry.id, &base_tip, &tested, &test_ref)
234+ .await?
235+ {
236+ return Ok(false);
237+ }
238+ notify_changed(state, &repo.id);
239+ // A run is created here only when the workflow runs for this candidate. Its statuses may
240+ // arrive before this returns; `evaluate` finds the run through its ref and commit.
241+ merge_queue_run(
242+ state,
243+ repo,
244+ &test_ref,
245+ &entry.branch,
246+ &tested,
247+ &user.id,
248+ pr.issue.number,
249+ )
250+ .await?;
251+ Ok(true)
252+}
253+
254+/// Looks at the candidate of a testing entry. Returns `Ok(false)` while it waits for CI or for
255+/// its required checks, and `Ok(true)` when the entry finished (merged or failed), or went back
256+/// to the head of the queue to be built again.
257+pub async fn evaluate(state: &AppState, repo: &Repo, entry_id: &str) -> forge_core::Result<bool> {
258+ let Some(entry) = state.store.queue_entry(entry_id).await? else {
259+ return Ok(true);
260+ };
261+ if entry.state != QueueState::Testing {
262+ return Ok(true);
263+ }
264+ let Some(pr) = state
265+ .store
266+ .pull_by_number(&repo.id, entry.pull_number)
267+ .await?
268+ else {
269+ remove(state, repo, &entry, "removed").await;
270+ return Ok(true);
271+ };
272+ let tested = entry.tested_oid.clone().unwrap_or_default();
273+ let test_ref = entry.test_ref.clone().unwrap_or_default();
274+ let run = state
275+ .store
276+ .latest_run_on_ref(&repo.id, &test_ref)
277+ .await?
278+ .filter(|run| run.commit_oid == tested);
279+ if let Some(run) = &run {
280+ if !run.state.is_terminal() {
281+ return Ok(false);
282+ }
283+ if run.state != forge_core::ci::RunState::Success {
284+ let url = format!(
285+ "{}/{}/{}/ci/runs/{}",
286+ state.config.base_url.trim_end_matches('/'),
287+ repo.owner_name,
288+ repo.name,
289+ run.number
290+ );
291+ let text = format!("the merge queue test run {url} did not pass.");
292+ fail(state, repo, &entry, &pr, "tests_failed", &text).await?;
293+ return Ok(true);
294+ }
295+ }
296+ let rules = state.store.list_branch_rules(&repo.id).await?;
297+ let rule = effective(&rules, &repo.default_branch, &entry.branch);
298+ if !rule.required_checks.is_empty() {
299+ let statuses = state.store.statuses_for(&repo.id, &tested).await?;
300+ let mut waiting = false;
301+ for context in &rule.required_checks {
302+ match statuses
303+ .iter()
304+ .find(|s| &s.context == context)
305+ .map(|s| s.state)
306+ {
307+ Some(StatusState::Success) => {}
308+ Some(StatusState::Failure | StatusState::Error) => {
309+ let text =
310+ format!("the required check {context} failed on the merge candidate.");
311+ fail(state, repo, &entry, &pr, "checks_failed", &text).await?;
312+ return Ok(true);
313+ }
314+ _ => waiting = true,
315+ }
316+ }
317+ if waiting {
318+ return Ok(false);
319+ }
320+ }
321+ land(state, repo, &entry, &pr).await
322+}
323+
324+/// Moves the target from the tip the candidate was built on to the candidate. Returns `Ok(true)`
325+/// when the entry is finished or back in the queue, `Ok(false)` when another event owns it.
326+async fn land(
327+ state: &AppState,
328+ repo: &Repo,
329+ entry: &QueueEntry,
330+ pr: &PullRequest,
331+) -> forge_core::Result<bool> {
332+ if !state.store.queue_set_merging(&entry.id).await? {
333+ return Ok(false);
334+ }
335+ let tested = entry.tested_oid.clone().unwrap_or_default();
336+ let base = entry.base_oid.clone().unwrap_or_default();
337+ let Some(user) = state.store.user_by_id(&entry.enqueued_by).await? else {
338+ finish_removed(state, repo, entry, "removed").await?;
339+ return Ok(true);
340+ };
341+ let collaborator = state.store.collaborator_role(&repo.id, &user.id).await?;
342+ let org = state
343+ .store
344+ .org_repo_role(&repo.owner_id, &user.id, &repo.id)
345+ .await?;
346+ if authorize(Some(&user), repo, collaborator, org, Action::Write).is_err() {
347+ finish_removed(state, repo, entry, "permission").await?;
348+ return Ok(true);
349+ }
350+ let refname = format!("refs/heads/{}", entry.branch);
351+ let base_path = repo_path(&state.git.data_dir, &repo.id)?;
352+ match update_ref_cas(&state.git, &base_path, &refname, &tested, &base).await {
353+ Ok(()) => {}
354+ Err(forge_git::error::Error::RefMoved(_)) => {
355+ // The target moved since the candidate was built: build it again on the new tip.
356+ state.store.queue_set_queued(&entry.id).await?;
357+ notify_changed(state, &repo.id);
358+ return Ok(true);
359+ }
360+ Err(e) => {
361+ state.store.queue_set_queued(&entry.id).await?;
362+ notify_changed(state, &repo.id);
363+ return Err(e.into());
364+ }
365+ }
366+ finish_merge(state, repo, pr, &user, &refname, &base, &tested).await;
367+ finish_removed(state, repo, entry, "merged").await?;
368+ Ok(true)
369+}
370+
371+/// Ends a merging entry as removed with `reason`.
372+async fn finish_removed(
373+ state: &AppState,
374+ repo: &Repo,
375+ entry: &QueueEntry,
376+ reason: &str,
377+) -> forge_core::Result<()> {
378+ state
379+ .store
380+ .queue_finish(&entry.id, QueueState::Removed, reason)
381+ .await?;
382+ notify_changed(state, &repo.id);
383+ Ok(())
384+}
385+
386+/// Ends an entry as failed and comments on its pull request, mentioning the person who queued it.
387+async fn fail(
388+ state: &AppState,
389+ repo: &Repo,
390+ entry: &QueueEntry,
391+ pr: &PullRequest,
392+ reason: &str,
393+ text: &str,
394+) -> forge_core::Result<()> {
395+ if !state
396+ .store
397+ .queue_finish(&entry.id, QueueState::Failed, reason)
398+ .await?
399+ {
400+ return Ok(());
401+ }
402+ notify_changed(state, &repo.id);
403+ let who = match state.store.user_by_id(&entry.enqueued_by).await? {
404+ Some(user) => format!("@{}", user.username),
405+ None => String::new(),
406+ };
407+ let body = format!("{who} The merge queue removed this pull request: {text}")
408+ .trim_start()
409+ .to_owned();
410+ let ghost = state.store.ensure_ghost_user().await?;
411+ match state
412+ .store
413+ .add_comment(&pr.issue.id, &ghost.id, &body)
414+ .await
415+ {
416+ Ok(_) => {
417+ notify::dispatch(
418+ state,
419+ repo,
420+ &pr.issue,
421+ &ghost.id,
422+ Activity::Comment,
423+ Some(&body),
424+ )
425+ .await;
426+ }
427+ Err(e) => {
428+ tracing::error!(error = %e, repo_id = %repo.id, "merge queue: commenting failed");
429+ }
430+ }
431+ Ok(())
432+}
433+
434+/// Wakes the queue pages of `repo_id`.
435+pub fn notify_changed(state: &AppState, repo_id: &str) {
436+ state.ci_live.bump_queue(repo_id);
437+}
crates/forge-web/src/pages/issue_parts.rsmodified+3 -0
@@ -1378,6 +1378,9 @@ pub(crate) async fn post_comment(
1378 ("reopened", Activity::Reopened)1378 ("reopened", Activity::Reopened)
1379 };1379 };
1380 emit_item_action(state, &ctx.repo, &sender, pull, item.number, action).await;1380 emit_item_action(state, &ctx.repo, &sender, pull, item.number, action).await;
1381+ if pull && action == "closed" {
1382+ crate::merge_queue::drop_pull(state, &ctx.repo, &item.id, "closed").await;
1383+ }
1381 if pull1384 if pull
1382 && action == "reopened"1385 && action == "reopened"
1383 && let Some(pr) = state1386 && let Some(pr) = state
crates/forge-web/src/pages/merge_queue.rsadded+436 -0
@@ -0,0 +1,436 @@
1+//! The merge queue: the queue page of a repo and the pull request actions that join and leave it.
2+//!
3+//! - `GET /{owner}/{repo}/merge-queue` lists the waiting entries with their position, state, CI run
4+//! and a remove button, and `?show=history` the finished ones. It follows the queue live.
5+//! - `GET /{owner}/{repo}/merge-queue/events` is the `changed` stream of that page.
6+//! - `POST /{owner}/{repo}/pulls/{number}/merge-queue` adds a pull request to the queue.
7+//! - `POST /{owner}/{repo}/pulls/{number}/merge-queue/remove` takes it out again.
8+//!
9+//! The actions need Write, a valid CSRF token and an open pull request. They answer with a
10+//! redirect back to the pull request, carrying a refusal code when there is one.
11+
12+use std::collections::HashMap;
13+
14+use forge_core::merge_queue::{QueueEntry, QueueState};
15+use forge_core::{Action, MergeStyle, PullRequest, authorize};
16+use futures_util::{Stream, stream};
17+use serde::Deserialize;
18+use tokio::sync::watch;
19+use topcoat::Result;
20+use topcoat::context::{Cx, app_context};
21+use topcoat::router::content::Form;
22+use topcoat::router::content::sse::Event;
23+use topcoat::router::error::{bad_request, forbidden, not_found, see_other};
24+use topcoat::router::response::Response;
25+use topcoat::router::{page, path_param, query_params, route};
26+use topcoat::view::{View, component, view};
27+
28+use crate::auth::require_csrf;
29+use crate::i18n::merge_queue::{self as g, K};
30+use crate::i18n::{self, Lang};
31+use crate::merge_queue as queue;
32+use crate::pages::ci_runs::{changed_event, events_response};
33+use crate::pages::issue_parts::parse_number;
34+use crate::pages::pulls_merge::ERR_NOT_OPEN;
35+use crate::pages::repo::repo_head;
36+use crate::pages::repo_ctx::{RepoCtx, load_repo};
37+use crate::state::AppState;
38+use crate::views::{repo_href, shell};
39+
40+path_param!(owner);
41+path_param!(repo);
42+path_param!(number);
43+
44+#[derive(Deserialize)]
45+struct QueueForm {
46+ #[serde(default)]
47+ csrf: String,
48+ #[serde(default)]
49+ style: String,
50+}
51+
52+#[query_params(error = bad_request)]
53+struct QueueQuery {
54+ show: Option<String>,
55+}
56+
57+fn pull_href(ctx: &RepoCtx, number: i64) -> String {
58+ repo_href(
59+ &ctx.repo.owner_name,
60+ &ctx.repo.name,
61+ "pulls",
62+ &number.to_string(),
63+ )
64+}
65+
66+fn queue_href(ctx: &RepoCtx) -> String {
67+ repo_href(&ctx.repo.owner_name, &ctx.repo.name, "merge-queue", "")
68+}
69+
70+/// Back to the pull request, with a refusal code when there is one.
71+fn back_to_pull(href: &str, code: Option<&str>) -> Result<Response> {
72+ let target = match code {
73+ Some(code) => format!("{href}?merge_error={code}"),
74+ None => href.to_owned(),
75+ };
76+ Err(see_other(target).into())
77+}
78+
79+async fn load_pull(cx: &Cx, ctx: &RepoCtx, number: i64) -> Result<PullRequest> {
80+ let state = app_context::<AppState>(cx);
81+ match state.store.pull_by_number(&ctx.repo.id, number).await? {
82+ Some(pr) => Ok(pr),
83+ None => Err(not_found().into()),
84+ }
85+}
86+
87+#[route(POST "/{owner}/{repo}/pulls/{number}/merge-queue")]
88+async fn enqueue_post(cx: &Cx, Form(form): Form<QueueForm>) -> Result<Response> {
89+ let number = parse_number(path_param::<Number>(cx))?;
90+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
91+ let (user, _) = require_csrf(cx, &form.csrf).await?;
92+ if ctx.repo.archived
93+ || authorize(
94+ Some(&user),
95+ &ctx.repo,
96+ ctx.role,
97+ ctx.org_role,
98+ Action::Write,
99+ )
100+ .is_err()
101+ {
102+ return Err(forbidden().into());
103+ }
104+ let state = app_context::<AppState>(cx);
105+ let pr = load_pull(cx, &ctx, number).await?;
106+ let href = pull_href(&ctx, number);
107+ if pr.merged_at.is_some() || pr.issue.state != forge_core::IssueState::Open {
108+ return back_to_pull(&href, Some(ERR_NOT_OPEN));
109+ }
110+ if !queue::requires_queue(state, &ctx.repo, &pr.base_branch).await? {
111+ return back_to_pull(&href, None);
112+ }
113+ let style = if form.style.is_empty() {
114+ MergeStyle::Merge
115+ } else {
116+ form.style
117+ .parse::<MergeStyle>()
118+ .map_err(|e| bad_request(e.to_string()))?
119+ };
120+ match queue::enqueue(state, &ctx.repo, &pr, &user, style).await? {
121+ Ok(_) => back_to_pull(&href, None),
122+ Err(code) => back_to_pull(&href, Some(code)),
123+ }
124+}
125+
126+#[route(POST "/{owner}/{repo}/pulls/{number}/merge-queue/remove")]
127+async fn remove_post(cx: &Cx, Form(form): Form<QueueForm>) -> Result<Response> {
128+ let number = parse_number(path_param::<Number>(cx))?;
129+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
130+ let (user, _) = require_csrf(cx, &form.csrf).await?;
131+ if ctx.repo.archived
132+ || authorize(
133+ Some(&user),
134+ &ctx.repo,
135+ ctx.role,
136+ ctx.org_role,
137+ Action::Write,
138+ )
139+ .is_err()
140+ {
141+ return Err(forbidden().into());
142+ }
143+ let state = app_context::<AppState>(cx);
144+ let pr = load_pull(cx, &ctx, number).await?;
145+ let href = pull_href(&ctx, number);
146+ if let Some(entry) = state.store.queue_entry_for_pull(&pr.issue.id).await? {
147+ queue::remove(state, &ctx.repo, &entry, "removed").await;
148+ queue::advance(state, &ctx.repo, &entry.branch).await;
149+ }
150+ back_to_pull(&href, None)
151+}
152+
153+/// The queue page: waiting entries, or the history with `?show=history`.
154+#[page("/{owner}/{repo}/merge-queue")]
155+async fn queue_page(cx: &Cx) -> Result<impl View> {
156+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
157+ let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(u, _)| u));
158+ let history = query_params::<QueueQuery>(cx)?.show.as_deref() == Some("history");
159+ let state = app_context::<AppState>(cx);
160+ let frame = crate::pages::issue_meta::RepoFrame::new(&ctx, state, "pulls").await?;
161+ let entries = state.store.queue_overview(&ctx.repo.id).await?;
162+ let rows = queue_rows(state, &ctx, lang, entries, history).await?;
163+ let protected = state
164+ .store
165+ .list_branch_rules(&ctx.repo.id)
166+ .await?
167+ .iter()
168+ .any(|rule| rule.require_merge_queue);
169+ let title = g::t(lang, K::MergeQueueTitle).to_owned();
170+ let waiting_href = queue_href(&ctx);
171+ let history_href = format!("{waiting_href}?show=history");
172+ let live = format!("{waiting_href}/events");
173+ let empty = rows.is_empty();
174+ Ok(view! {
175+ shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
176+ queue_body(lang: lang, head: frame.head,
177+ waiting_href: waiting_href, history_href: history_href, history: history,
178+ live: live, rows: rows, empty: empty, protected: protected,
179+ csrf: frame.csrf.clone()))
180+ })
181+}
182+
183+/// One row of the queue table, with its strings resolved.
184+struct QueueRow {
185+ position: String,
186+ pull_title: String,
187+ pull_href: String,
188+ remove_action: String,
189+ pull_number: i64,
190+ branch: String,
191+ state: &'static str,
192+ state_class: &'static str,
193+ by: String,
194+ queued: String,
195+ run_href: Option<String>,
196+ run_label: String,
197+ reason: String,
198+ remove: bool,
199+}
200+
201+/// `2026-10-21T19:11:22.700Z` as `2026-10-21 19:11` (UTC), for the queue table.
202+fn stamp_minute(stamp: &str) -> String {
203+ match stamp.get(..16) {
204+ Some(minute) => minute.replace('T', " "),
205+ None => stamp.to_owned(),
206+ }
207+}
208+
209+async fn queue_rows(
210+ state: &AppState,
211+ ctx: &RepoCtx,
212+ lang: Lang,
213+ entries: Vec<QueueEntry>,
214+ history: bool,
215+) -> forge_core::Result<Vec<QueueRow>> {
216+ let mut ids: Vec<String> = entries.iter().map(|e| e.enqueued_by.clone()).collect();
217+ ids.sort();
218+ ids.dedup();
219+ let names: HashMap<String, (String, Option<String>)> = if ids.is_empty() {
220+ HashMap::new()
221+ } else {
222+ state.store.usernames_by_ids(&ids).await?
223+ };
224+ // Position counts the waiting entries of each branch from the head.
225+ let mut position: HashMap<String, usize> = HashMap::new();
226+ let mut rows = Vec::new();
227+ for entry in entries {
228+ let waiting = entry.finished_at.is_none();
229+ let pos = if waiting {
230+ let next = position.entry(entry.branch.clone()).or_insert(0);
231+ *next += 1;
232+ *next
233+ } else {
234+ 0
235+ };
236+ if waiting == history {
237+ continue;
238+ }
239+ let pull = state
240+ .store
241+ .pull_by_number(&ctx.repo.id, entry.pull_number)
242+ .await?;
243+ let pull_title = pull
244+ .as_ref()
245+ .map(|pr| pr.issue.title.clone())
246+ .unwrap_or_default();
247+ let run = match &entry.test_ref {
248+ Some(test_ref) => state
249+ .store
250+ .latest_run_on_ref(&ctx.repo.id, test_ref)
251+ .await?
252+ .filter(|run| Some(&run.commit_oid) == entry.tested_oid.as_ref()),
253+ None => None,
254+ };
255+ let run_href = run.as_ref().map(|run| {
256+ repo_href(
257+ &ctx.repo.owner_name,
258+ &ctx.repo.name,
259+ "ci",
260+ &format!("runs/{}", run.number),
261+ )
262+ });
263+ let run_label = run
264+ .as_ref()
265+ .map(|run| format!("#{}", run.number))
266+ .unwrap_or_else(|| g::t(lang, K::QueueNoRun).to_owned());
267+ let by = names
268+ .get(&entry.enqueued_by)
269+ .map(|(display, _)| display.clone())
270+ .unwrap_or_default();
271+ rows.push(QueueRow {
272+ position: if waiting {
273+ pos.to_string()
274+ } else {
275+ String::new()
276+ },
277+ pull_title,
278+ pull_href: pull_href(ctx, entry.pull_number),
279+ remove_action: format!("{}/remove", pull_href(ctx, entry.pull_number)),
280+ pull_number: entry.pull_number,
281+ branch: entry.branch.clone(),
282+ state: state_label(lang, entry.state),
283+ state_class: state_class(entry.state),
284+ by,
285+ queued: stamp_minute(&entry.enqueued_at),
286+ run_href,
287+ run_label,
288+ reason: entry
289+ .reason
290+ .as_deref()
291+ .map(|reason| reason_label(lang, reason))
292+ .unwrap_or_default(),
293+ remove: waiting && ctx.can_write(),
294+ });
295+ }
296+ Ok(rows)
297+}
298+
299+fn state_label(lang: Lang, state: QueueState) -> &'static str {
300+ g::t(
301+ lang,
302+ match state {
303+ QueueState::Queued => K::StateQueued,
304+ QueueState::Testing => K::StateTesting,
305+ QueueState::Merging => K::StateMerging,
306+ QueueState::Failed => K::StateFailed,
307+ QueueState::Removed => K::StateRemoved,
308+ },
309+ )
310+}
311+
312+fn state_class(state: QueueState) -> &'static str {
313+ match state {
314+ QueueState::Queued => "queue-state queue-queued",
315+ QueueState::Testing | QueueState::Merging => "queue-state queue-running",
316+ QueueState::Failed => "queue-state queue-bad",
317+ QueueState::Removed => "queue-state queue-muted",
318+ }
319+}
320+
321+fn reason_label(lang: Lang, reason: &str) -> String {
322+ let key = match reason {
323+ "merged" => K::ReasonMerged,
324+ "removed" => K::ReasonRemoved,
325+ "closed" => K::ReasonClosed,
326+ "head_changed" => K::ReasonHeadChanged,
327+ "conflict" => K::ReasonConflict,
328+ "tests_failed" => K::ReasonTestsFailed,
329+ "checks_failed" => K::ReasonChecksFailed,
330+ "permission" => K::ReasonPermission,
331+ "blocked" => K::ReasonBlocked,
332+ "no_branch" => K::ReasonNoBranch,
333+ _ => return reason.to_owned(),
334+ };
335+ g::t(lang, key).to_owned()
336+}
337+
338+/// The live `changed` stream of a repo's queue. Subscribed before the response is sent, so a change
339+/// after that point is sent.
340+#[route(GET "/{owner}/{repo}/merge-queue/events")]
341+async fn queue_events(cx: &Cx) -> Result<Response> {
342+ let ctx = load_repo(cx, path_param::<Owner>(cx), path_param::<Repo>(cx)).await?;
343+ let state = app_context::<AppState>(cx);
344+ let wake = state.ci_live.subscribe_queue(&ctx.repo.id);
345+ events_response(cx, queue_changes(wake))
346+}
347+
348+fn queue_changes(wake: watch::Receiver<u64>) -> impl Stream<Item = Result<Event>> + Send + 'static {
349+ stream::unfold(wake, |mut wake| async move {
350+ wake.changed().await.ok()?;
351+ Some((changed_event("queue".to_owned()), wake))
352+ })
353+}
354+
355+#[component]
356+async fn queue_body(
357+ lang: Lang,
358+ head: crate::pages::repo_ctx::RepoHead,
359+ waiting_href: String,
360+ history_href: String,
361+ history: bool,
362+ live: String,
363+ rows: Vec<QueueRow>,
364+ empty: bool,
365+ protected: bool,
366+ csrf: String,
367+) -> Result<impl View> {
368+ let remove_label = g::t(lang, K::RemoveFromQueue);
369+ let hint = g::t(lang, K::MergeQueueHint);
370+ Ok(view! {
371+ repo_head(head: head)
372+ <div data-live=(live.as_str())>
373+ <nav class="issue-tabs" aria-label=(g::t(lang, K::MergeQueueNav))>
374+ <a class=(tab_class(!history)) href=(waiting_href.as_str())>(g::t(lang, K::QueueWaiting))</a>
375+ <a class=(tab_class(history)) href=(history_href.as_str())>(g::t(lang, K::QueueHistory))</a>
376+ </nav>
377+ if !protected {
378+ <section class="card notice" role="status">(g::t(lang, K::QueueNoBranch))</section>
379+ }
380+ if empty {
381+ <p class="muted">(g::t(lang, K::QueueEmpty))</p>
382+ } else {
383+ <div class="table-wrap">
384+ <table class="queue-table">
385+ <thead>
386+ <tr>
387+ <th>(g::t(lang, K::QueueColPosition))</th>
388+ <th>(g::t(lang, K::QueueColPull))</th>
389+ <th>(g::t(lang, K::QueueColBranch))</th>
390+ <th>(g::t(lang, K::QueueColState))</th>
391+ <th>(g::t(lang, K::QueueColBy))</th>
392+ <th>(g::t(lang, K::QueueColQueued))</th>
393+ <th>(g::t(lang, K::QueueColRun))</th>
394+ <th>(g::t(lang, K::QueueColReason))</th>
395+ <th></th>
396+ </tr>
397+ </thead>
398+ <tbody>
399+ for row in rows.iter() {
400+ <tr>
401+ <td class="mono">(row.position.as_str())</td>
402+ <td><a href=(row.pull_href.as_str())>"#"(row.pull_number)" "(row.pull_title.as_str())</a></td>
403+ <td><code>(row.branch.as_str())</code></td>
404+ <td><span class=(row.state_class)>(row.state)</span></td>
405+ <td>(row.by.as_str())</td>
406+ <td class="muted small">(row.queued.as_str())</td>
407+ <td>
408+ if let Some(href) = row.run_href.as_ref() {
409+ <a href=(href.as_str())>(row.run_label.as_str())</a>
410+ } else {
411+ <span class="muted">(row.run_label.as_str())</span>
412+ }
413+ </td>
414+ <td class="muted small">(row.reason.as_str())</td>
415+ <td>
416+ if row.remove {
417+ <form method="post" action=(row.remove_action.as_str()) class="merge-flow">
418+ <input type="hidden" name="csrf" value=(csrf.as_str())>
419+ <button type="submit">(remove_label)</button>
420+ </form>
421+ }
422+ </td>
423+ </tr>
424+ }
425+ </tbody>
426+ </table>
427+ </div>
428+ }
429+ <p class="muted small">(hint)</p>
430+ </div>
431+ })
432+}
433+
434+fn tab_class(on: bool) -> &'static str {
435+ if on { "issue-tab on" } else { "issue-tab" }
436+}
crates/forge-web/src/pages/mod.rsmodified+1 -0
@@ -61,6 +61,7 @@ pub mod labels_css;
61 pub mod labels_page;61 pub mod labels_page;
62 pub mod login;62 pub mod login;
63 pub mod media;63 pub mod media;
64+pub mod merge_queue;
64 pub mod milestones_page;65 pub mod milestones_page;
65 pub mod new_repo;66 pub mod new_repo;
66 pub mod not_found_page;67 pub mod not_found_page;
crates/forge-web/src/pages/pull_view.rsmodified+84 -6
@@ -36,7 +36,7 @@ use crate::pages::pulls_merge::{
36 ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED,36 ERR_ALREADY_MERGED, ERR_AUTO_MERGE_BLOCKED, ERR_BASE_MISSING, ERR_BASE_MOVED,
37 ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING,37 ERR_CHANGES_REQUESTED, ERR_CONFLICT, ERR_DRAFT, ERR_FF_IMPOSSIBLE, ERR_HEAD_MISSING,
38 ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, ERR_NOT_UP_TO_DATE,38 ERR_MESSAGE_INVALID, ERR_NEEDS_APPROVALS, ERR_NEEDS_CHECKS, ERR_NOT_OPEN, ERR_NOT_UP_TO_DATE,
39- ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, merge_gate,39+ ERR_QUEUE_ALREADY, ERR_QUEUE_REQUIRED, ERR_REBASE_CONFLICT, ERR_UP_TO_DATE, merge_gate,
40 };40 };
41 use crate::pages::repo::repo_head;41 use crate::pages::repo::repo_head;
42 use crate::pages::repo_ctx::{RepoCtx, load_repo};42 use crate::pages::repo_ctx::{RepoCtx, load_repo};
@@ -297,6 +297,10 @@ struct FlowView {
297 auto_on: Option<(String, String)>,297 auto_on: Option<(String, String)>,
298 /// Auto-merge can be enabled: the action.298 /// Auto-merge can be enabled: the action.
299 auto_enable: Option<String>,299 auto_enable: Option<String>,
300+ /// The pull request waits in the merge queue: its position line and the remove action.
301+ queue_position: Option<(String, String)>,
302+ /// The pull request can join the merge queue: the action.
303+ queue_add: Option<String>,
300 }304 }
301 305
302 /// The mergeability status and, for writers on a clean branch, the merge form. `tone` is one of306 /// 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(
329 draft_toggle,333 draft_toggle,
330 auto_on,334 auto_on,
331 auto_enable,335 auto_enable,
336+ queue_position,
337+ queue_add,
332 } = flow;338 } = flow;
339+ let queue_add_label =
340+ crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::AddToMergeQueue);
341+ let queue_remove_label =
342+ crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::RemoveFromQueue);
343+ let queue_hint = crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::MergeQueueHint);
333 let reload_text = g::t(lang, K::ReloadToCheck);344 let reload_text = g::t(lang, K::ReloadToCheck);
334 let style_legend = g::t(lang, K::MergeStyleLegend);345 let style_legend = g::t(lang, K::MergeStyleLegend);
335 let style_merge = g::t(lang, K::StyleMergeCommit);346 let style_merge = g::t(lang, K::StyleMergeCommit);
@@ -391,6 +402,25 @@ async fn merge_box(
391 <div><button type="submit" class="primary">(merge_button)</button></div>402 <div><button type="submit" class="primary">(merge_button)</button></div>
392 </form>403 </form>
393 }404 }
405+ if let Some((text, action)) = queue_position {
406+ <form method="post" action=(action.as_str()) class="merge-flow">
407+ <input type="hidden" name="csrf" value=(flow_csrf.as_str())>
408+ <p class="merge-headline">(text.as_str())</p>
409+ <button type="submit">(queue_remove_label)</button>
410+ </form>
411+ }
412+ if let Some(action) = queue_add {
413+ <form method="post" action=(action.as_str()) class="merge-flow">
414+ <input type="hidden" name="csrf" value=(flow_csrf.as_str())>
415+ <p class="muted small">(queue_hint)</p>
416+ <select name="style" aria-label=(queue_add_label)>
417+ <option value="merge">(style_merge_option.trim())</option>
418+ <option value="squash">(style_squash_option.trim())</option>
419+ <option value="rebase">(style_rebase.trim())</option>
420+ </select>
421+ <button type="submit" class="primary">(queue_add_label)</button>
422+ </form>
423+ }
394 if let Some((text, action)) = auto_on {424 if let Some((text, action)) = auto_on {
395 <form method="post" action=(action.as_str()) class="merge-flow">425 <form method="post" action=(action.as_str()) class="merge-flow">
396 <input type="hidden" name="csrf" value=(flow_csrf.as_str())>426 <input type="hidden" name="csrf" value=(flow_csrf.as_str())>
@@ -643,11 +673,23 @@ async fn pull_conversation(
643 } else {673 } else {
644 None674 None
645 };675 };
646- let blocked = gate676+ // A branch that requires the merge queue tests the pull request on the current tip, so an
647- .as_ref()677+ // outdated head does not block it.
648- .and_then(|gate| gate.blocked())678+ let queue_required =
649- .and_then(|code| merge_error_text(lang, code))679+ crate::merge_queue::requires_queue(state, &ctx.repo, &pr.base_branch).await?;
650- .map(str::to_owned);680+ let queue_blocker = gate.as_ref().and_then(|gate| {
681+ gate.blockers()
682+ .into_iter()
683+ .find(|code| !(queue_required && *code == ERR_NOT_UP_TO_DATE))
684+ });
685+ let blocked = if queue_required {
686+ queue_blocker.and_then(|code| merge_error_text(lang, code))
687+ } else {
688+ gate.as_ref()
689+ .and_then(|gate| gate.blocked())
690+ .and_then(|code| merge_error_text(lang, code))
691+ }
692+ .map(str::to_owned);
651 let approvals = gate693 let approvals = gate
652 .as_ref()694 .as_ref()
653 .filter(|gate| gate.rule.required_approvals > 0)695 .filter(|gate| gate.rule.required_approvals > 0)
@@ -695,7 +737,35 @@ async fn pull_conversation(
695 let auto_waiting = gate737 let auto_waiting = gate
696 .as_ref()738 .as_ref()
697 .is_some_and(|gate| !gate.blockers().is_empty() && gate.waiting_only());739 .is_some_and(|gate| !gate.blockers().is_empty() && gate.waiting_only());
740+ let queue_entry = match (open, queue_required) {
741+ (true, true) => state.store.queue_entry_for_pull(&pr.issue.id).await?,
742+ _ => None,
743+ };
744+ let queue_position = match queue_entry.as_ref() {
745+ Some(entry) => state
746+ .store
747+ .queue_for_branch(&ctx.repo.id, &entry.branch)
748+ .await?
749+ .iter()
750+ .position(|waiting| waiting.id == entry.id)
751+ .map(|index| index + 1),
752+ None => None,
753+ };
754+ let queue_can_add = open
755+ && can_write
756+ && queue_required
757+ && queue_entry.is_none()
758+ && pr.mergeable != Mergeable::Conflict
759+ && pr.head_repo_id.is_some()
760+ && blocked.is_none();
698 let flow = FlowView {761 let flow = FlowView {
762+ queue_position: queue_position.filter(|_| can_write).map(|position| {
763+ (
764+ crate::i18n::merge_queue::position_text(lang, position),
765+ format!("{href}/merge-queue/remove"),
766+ )
767+ }),
768+ queue_add: queue_can_add.then(|| format!("{href}/merge-queue")),
699 csrf: csrf.clone(),769 csrf: csrf.clone(),
700 draft_toggle: (open770 draft_toggle: (open
701 && !archived771 && !archived
@@ -722,6 +792,7 @@ async fn pull_conversation(
722 }),792 }),
723 auto_enable: (open793 auto_enable: (open
724 && can_write794 && can_write
795+ && !queue_required
725 && pr.auto_merge.is_none()796 && pr.auto_merge.is_none()
726 && auto_waiting797 && auto_waiting
727 && pr.mergeable != Mergeable::Conflict798 && pr.mergeable != Mergeable::Conflict
@@ -730,6 +801,7 @@ async fn pull_conversation(
730 };801 };
731 let merge_form = if open802 let merge_form = if open
732 && can_write803 && can_write
804+ && !queue_required
733 && pr.mergeable == Mergeable::Clean805 && pr.mergeable == Mergeable::Clean
734 && pr.head_repo_id.is_some()806 && pr.head_repo_id.is_some()
735 && blocked.is_none()807 && blocked.is_none()
@@ -862,6 +934,12 @@ fn merge_error_text(lang: Lang, code: &str) -> Option<&'static str> {
862 ERR_NEEDS_CHECKS => g::t(lang, K::ErrNeedsChecks),934 ERR_NEEDS_CHECKS => g::t(lang, K::ErrNeedsChecks),
863 ERR_REBASE_CONFLICT => g::t(lang, K::ErrRebaseConflict),935 ERR_REBASE_CONFLICT => g::t(lang, K::ErrRebaseConflict),
864 ERR_AUTO_MERGE_BLOCKED => g::t(lang, K::ErrAutoMergeBlocked),936 ERR_AUTO_MERGE_BLOCKED => g::t(lang, K::ErrAutoMergeBlocked),
937+ ERR_QUEUE_REQUIRED => {
938+ crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::ErrQueueRequired)
939+ }
940+ ERR_QUEUE_ALREADY => {
941+ crate::i18n::merge_queue::t(lang, crate::i18n::merge_queue::K::ErrQueueAlready)
942+ }
865 _ => return None,943 _ => return None,
866 })944 })
867 }945 }
crates/forge-web/src/pages/pulls_list.rsmodified+3 -0
@@ -12,6 +12,7 @@ use topcoat::context::{Cx, app_context};
12 use topcoat::router::{page, path_param, query_params};12 use topcoat::router::{page, path_param, query_params};
13 use topcoat::view::{View, view};13 use topcoat::view::{View, view};
14 14
15+use crate::i18n::merge_queue as mq;
15 use crate::i18n::pulls::{self as g, K};16 use crate::i18n::pulls::{self as g, K};
16 use crate::i18n::{self, Lang};17 use crate::i18n::{self, Lang};
17 use crate::pages::issues_list::{18 use crate::pages::issues_list::{
@@ -246,6 +247,7 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
246 247
247 let can_create = ctx.viewer.is_some() && !ctx.repo.archived;248 let can_create = ctx.viewer.is_some() && !ctx.repo.archived;
248 let compare_href = repo_href(&owner_name, &repo_name, "compare", "");249 let compare_href = repo_href(&owner_name, &repo_name, "compare", "");
250+ let queue_href = repo_href(&owner_name, &repo_name, "merge-queue", "");
249 let labels_href = repo_href(&owner_name, &repo_name, "labels.css", "");251 let labels_href = repo_href(&owner_name, &repo_name, "labels.css", "");
250 let title = g::list_title(lang, &owner_name, &repo_name);252 let title = g::list_title(lang, &owner_name, &repo_name);
251 let empty_text = if open_count + closed_count == 0 {253 let empty_text = if open_count + closed_count == 0 {
@@ -269,6 +271,7 @@ async fn pulls_list_page(cx: &Cx) -> Result<impl View> {
269 <a class=(state_tab_class(state_word == "all")) href=(all_href.as_str())>(all_text.as_str())</a>271 <a class=(state_tab_class(state_word == "all")) href=(all_href.as_str())>(all_text.as_str())</a>
270 </nav>272 </nav>
271 <div class="issue-tools">273 <div class="issue-tools">
274+ <a class="issue-tab-link" href=(queue_href.as_str())>(mq::t(lang, mq::K::MergeQueueTitle))</a>
272 if can_create {275 if can_create {
273 <a class="button" href=(compare_href.as_str())>(g::t(lang, K::NewPullRequest))</a>276 <a class="button" href=(compare_href.as_str())>(g::t(lang, K::NewPullRequest))</a>
274 }277 }
crates/forge-web/src/pages/pulls_merge.rsmodified+65 -22
@@ -68,6 +68,8 @@ pub const ERR_DRAFT: &str = "draft";
68 pub const ERR_NEEDS_CHECKS: &str = "needs_checks";68 pub const ERR_NEEDS_CHECKS: &str = "needs_checks";
69 pub const ERR_REBASE_CONFLICT: &str = "rebase_conflict";69 pub const ERR_REBASE_CONFLICT: &str = "rebase_conflict";
70 pub const ERR_AUTO_MERGE_BLOCKED: &str = "auto_merge_blocked";70 pub const ERR_AUTO_MERGE_BLOCKED: &str = "auto_merge_blocked";
71+pub const ERR_QUEUE_REQUIRED: &str = "queue_required";
72+pub const ERR_QUEUE_ALREADY: &str = "queue_already";
71 73
72 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.";74 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.";
73 const CONFLICTS_MSG: &str = "This branch has conflicts that must be resolved";75 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<MergeForm>) -> Result<Response> {
140 if let Some(code) = merge_gate(state, &ctx.repo, &pr).await?.blocked() {142 if let Some(code) = merge_gate(state, &ctx.repo, &pr).await?.blocked() {
141 return back_to_pull(&pull_href, code);143 return back_to_pull(&pull_href, code);
142 }144 }
145+ if crate::merge_queue::requires_queue(state, &ctx.repo, &pr.base_branch).await? {
146+ return back_to_pull(&pull_href, ERR_QUEUE_REQUIRED);
147+ }
143 let style = if form.style.is_empty() {148 let style = if form.style.is_empty() {
144 MergeStyle::Merge149 MergeStyle::Merge
145 } else {150 } else {
@@ -387,11 +392,45 @@ pub async fn perform_merge(
387 }392 }
388 },393 },
389 };394 };
395+ let new = match merge_commit(state, repo, pr, viewer, style, message, &base_tip).await? {
396+ Ok(new) => new,
397+ Err(refusal) => return Ok(refusal),
398+ };
399+
400+ match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await {
401+ Ok(()) => {}
402+ Err(forge_git::error::Error::RefMoved(_)) => {
403+ return Ok(refused(StatusCode::CONFLICT, MOVED_MSG));
404+ }
405+ Err(e) => return Err(e.into()),
406+ }
407+
408+ finish_merge(state, repo, pr, viewer, &refname, &base_tip, &new).await;
409+ Ok(MergeOutcome::Merged { commit: new })
410+}
411+
412+/// The commit that merging `pr` into `base_tip` makes in `style`, committed as `committer`. No ref
413+/// moves. A refusal the caller can act on comes back as the inner `Err`. Fast-forward returns the
414+/// head itself.
415+pub async fn merge_commit(
416+ state: &AppState,
417+ repo: &forge_core::Repo,
418+ pr: &PullRequest,
419+ committer: &User,
420+ style: MergeStyle,
421+ message: Option<&str>,
422+ base_tip: &str,
423+) -> forge_core::Result<std::result::Result<String, MergeOutcome>> {
424+ let base_path = repo_path(&state.git.data_dir, &repo.id)?;
425+ let base_tip = base_tip.to_owned();
426+ let viewer = committer;
390 let head = pr.head_oid.as_str();427 let head = pr.head_oid.as_str();
391 let tree = match check_merge(&state.git, &base_path, &base_tip, head).await? {428 let tree = match check_merge(&state.git, &base_path, &base_tip, head).await? {
392 MergeCheck::Clean { tree } => tree,429 MergeCheck::Clean { tree } => tree,
393- MergeCheck::Conflict { .. } => return Ok(refused(StatusCode::CONFLICT, CONFLICTS_MSG)),430+ MergeCheck::Conflict { .. } => {
394- MergeCheck::UpToDate => return Ok(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG)),431+ return Ok(Err(refused(StatusCode::CONFLICT, CONFLICTS_MSG)));
432+ }
433+ MergeCheck::UpToDate => return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG))),
395 };434 };
396 435
397 let now = now_unix();436 let now = now_unix();
@@ -403,7 +442,7 @@ pub async fn perform_merge(
403 let new = match style {442 let new = match style {
404 MergeStyle::FastForward => {443 MergeStyle::FastForward => {
405 if !is_ancestor(&state.git, &base_path, &base_tip, head).await? {444 if !is_ancestor(&state.git, &base_path, &base_tip, head).await? {
406- return Ok(refused(StatusCode::CONFLICT, FF_MSG));445+ return Ok(Err(refused(StatusCode::CONFLICT, FF_MSG)));
407 }446 }
408 head.to_owned()447 head.to_owned()
409 }448 }
@@ -411,10 +450,10 @@ pub async fn perform_merge(
411 match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? {450 match rebase_commits(&state.git, &base_path, &base_tip, head, &committer).await? {
412 RebaseResult::Clean { tip, count } if count > 0 => tip,451 RebaseResult::Clean { tip, count } if count > 0 => tip,
413 RebaseResult::Clean { .. } => {452 RebaseResult::Clean { .. } => {
414- return Ok(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG));453+ return Ok(Err(refused(StatusCode::CONFLICT, UP_TO_DATE_MSG)));
415 }454 }
416 RebaseResult::Conflict { .. } => {455 RebaseResult::Conflict { .. } => {
417- return Ok(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG));456+ return Ok(Err(refused(StatusCode::CONFLICT, REBASE_CONFLICT_MSG)));
418 }457 }
419 }458 }
420 }459 }
@@ -464,22 +503,22 @@ pub async fn perform_merge(
464 .await?503 .await?
465 }504 }
466 };505 };
506+ Ok(Ok(new))
507+}
467 508
468- match update_ref_cas(&state.git, &base_path, &refname, &new, &base_tip).await {509+/// The work after a merge moved `refname` from `base_tip` to `new`: the pull request is marked
469- Ok(()) => {}510+/// merged, its events and notifications go out, and the ref update runs its post-update work.
470- Err(forge_git::error::Error::RefMoved(_)) => {511+/// Failures here are logged, not reported: the merge is already in place.
471- return Ok(refused(StatusCode::CONFLICT, MOVED_MSG));512+pub async fn finish_merge(
472- }513+ state: &AppState,
473- Err(e) => return Err(e.into()),514+ repo: &forge_core::Repo,
474- }515+ pr: &PullRequest,
475-516+ viewer: &User,
476- // The ref has moved, so the merge happened. Post-merge steps that fail are logged, not517+ refname: &str,
477- // reported: the viewer's merge is already in place.518+ base_tip: &str,
478- match state519+ new: &str,
479- .store520+) {
480- .mark_merged(&pr.issue.id, &viewer.id, &new)521+ match state.store.mark_merged(&pr.issue.id, &viewer.id, new).await {
481- .await
482- {
483 Ok(()) => {522 Ok(()) => {
484 let sender = Sender::of(viewer);523 let sender = Sender::of(viewer);
485 emit_item_action(state, repo, &sender, true, pr.issue.number, "merged").await;524 emit_item_action(state, repo, &sender, true, pr.issue.number, "merged").await;
@@ -490,10 +529,14 @@ pub async fn perform_merge(
490 }529 }
491 }530 }
492 trigger_maintenance(&state.git, &repo.id);531 trigger_maintenance(&state.git, &repo.id);
493- if let Err(e) = after_ref_update(state, repo, &viewer.id, &refname, &base_tip, &new).await {532+ // Boxed: the queue lands through this path, and the post-update work can reach the queue again.
533+ if let Err(e) = Box::pin(after_ref_update(
534+ state, repo, &viewer.id, refname, base_tip, new,
535+ ))
536+ .await
537+ {
494 tracing::error!(error = %e, repo_id = %repo.id, ref_name = %refname, "merge: post-update failed");538 tracing::error!(error = %e, repo_id = %repo.id, ref_name = %refname, "merge: post-update failed");
495 }539 }
496- Ok(MergeOutcome::Merged { commit: new })
497 }540 }
498 541
499 /// The address written into a commit for `user`: their email, or a noreply address on this542 /// The address written into a commit for `user`: their email, or a noreply address on this
crates/forge-web/src/pages/repo_settings.rsmodified+17 -0
@@ -30,6 +30,7 @@ use topcoat::view::{View, component, view};
30 30
31 use crate::audit::{self, Actor, Target};31 use crate::audit::{self, Actor, Target};
32 use crate::auth::{require_csrf, require_user};32 use crate::auth::{require_csrf, require_user};
33+use crate::i18n::merge_queue as mq;
33 use crate::i18n::repo_admin::{self as g, K};34 use crate::i18n::repo_admin::{self as g, K};
34 use crate::i18n::{self, Lang};35 use crate::i18n::{self, Lang};
35 use crate::pages::discussion_settings::discussions_card;36 use crate::pages::discussion_settings::discussions_card;
@@ -127,6 +128,8 @@ struct BranchForm {
127 require_up_to_date: Option<String>,128 require_up_to_date: Option<String>,
128 #[serde(default)]129 #[serde(default)]
129 restrict_push: Option<String>,130 restrict_push: Option<String>,
131+ #[serde(default)]
132+ require_merge_queue: Option<String>,
130 /// Required check contexts, separated by commas or new lines.133 /// Required check contexts, separated by commas or new lines.
131 #[serde(default)]134 #[serde(default)]
132 required_checks: String,135 required_checks: String,
@@ -439,6 +442,7 @@ fn parse_rule_flags(lang: Lang, form: &BranchForm) -> std::result::Result<RuleFl
439 block_on_changes_requested: form.block_on_changes_requested.is_some(),442 block_on_changes_requested: form.block_on_changes_requested.is_some(),
440 require_up_to_date: form.require_up_to_date.is_some(),443 require_up_to_date: form.require_up_to_date.is_some(),
441 restrict_push: form.restrict_push.is_some(),444 restrict_push: form.restrict_push.is_some(),
445+ require_merge_queue: form.require_merge_queue.is_some(),
442 required_checks,446 required_checks,
443 })447 })
444 }448 }
@@ -458,6 +462,9 @@ fn rule_summary(lang: Lang, rule: &BranchRule) -> String {
458 if rule.restrict_push {462 if rule.restrict_push {
459 parts.push(g::t(lang, K::RuleRestrictPush).to_owned());463 parts.push(g::t(lang, K::RuleRestrictPush).to_owned());
460 }464 }
465+ if rule.require_merge_queue {
466+ parts.push(mq::t(lang, mq::K::RuleMergeQueue).to_owned());
467+ }
461 if !rule.required_checks.is_empty() {468 if !rule.required_checks.is_empty() {
462 parts.push(g::checks_count(lang, rule.required_checks.len()));469 parts.push(g::checks_count(lang, rule.required_checks.len()));
463 }470 }
@@ -530,6 +537,7 @@ async fn branch_rule_form(
530 block_on_changes_requested: bool,537 block_on_changes_requested: bool,
531 require_up_to_date: bool,538 require_up_to_date: bool,
532 restrict_push: bool,539 restrict_push: bool,
540+ require_merge_queue: bool,
533 required_checks: String,541 required_checks: String,
534 contexts: Vec<String>,542 contexts: Vec<String>,
535 error: Option<String>,543 error: Option<String>,
@@ -570,6 +578,11 @@ async fn branch_rule_form(
570 <input type="checkbox" name="restrict_push" value="on" checked=(restrict_push)>578 <input type="checkbox" name="restrict_push" value="on" checked=(restrict_push)>
571 <span>(g::t(lang, K::RestrictPush))</span>579 <span>(g::t(lang, K::RestrictPush))</span>
572 </label>580 </label>
581+ <label class="inline">
582+ <input type="checkbox" name="require_merge_queue" value="on" checked=(require_merge_queue)>
583+ <span>(mq::t(lang, mq::K::RequireMergeQueue))</span>
584+ </label>
585+ <p class="muted small">(mq::t(lang, mq::K::RequireMergeQueueHint))</p>
573 <label>586 <label>
574 <span>(g::t(lang, K::RequiredChecks))</span>587 <span>(g::t(lang, K::RequiredChecks))</span>
575 <input type="text" name="required_checks" value=(required_checks.as_str()) autocomplete="off" spellcheck="false" placeholder="ci/test, ci/lint">588 <input type="text" name="required_checks" value=(required_checks.as_str()) autocomplete="off" spellcheck="false" placeholder="ci/test, ci/lint">
@@ -599,6 +612,7 @@ struct RuleDraft {
599 block_on_changes_requested: bool,612 block_on_changes_requested: bool,
600 require_up_to_date: bool,613 require_up_to_date: bool,
601 restrict_push: bool,614 restrict_push: bool,
615+ require_merge_queue: bool,
602 required_checks: String,616 required_checks: String,
603 error: Option<String>,617 error: Option<String>,
604 }618 }
@@ -614,6 +628,7 @@ impl RuleDraft {
614 block_on_changes_requested: false,628 block_on_changes_requested: false,
615 require_up_to_date: false,629 require_up_to_date: false,
616 restrict_push: false,630 restrict_push: false,
631+ require_merge_queue: false,
617 required_checks: String::new(),632 required_checks: String::new(),
618 error: None,633 error: None,
619 }634 }
@@ -685,6 +700,7 @@ async fn settings_body(
685 required_approvals: draft.required_approvals,700 required_approvals: draft.required_approvals,
686 block_on_changes_requested: draft.block_on_changes_requested,701 block_on_changes_requested: draft.block_on_changes_requested,
687 require_up_to_date: draft.require_up_to_date, restrict_push: draft.restrict_push,702 require_up_to_date: draft.require_up_to_date, restrict_push: draft.restrict_push,
703+ require_merge_queue: draft.require_merge_queue,
688 required_checks: draft.required_checks, contexts: contexts,704 required_checks: draft.required_checks, contexts: contexts,
689 error: draft.error)705 error: draft.error)
690 </section>706 </section>
@@ -1101,6 +1117,7 @@ async fn settings_branch_save(cx: &Cx, Form(form): Form<BranchForm>) -> Result<i
1101 block_on_changes_requested: form.block_on_changes_requested.is_some(),1117 block_on_changes_requested: form.block_on_changes_requested.is_some(),
1102 require_up_to_date: form.require_up_to_date.is_some(),1118 require_up_to_date: form.require_up_to_date.is_some(),
1103 restrict_push: form.restrict_push.is_some(),1119 restrict_push: form.restrict_push.is_some(),
1120+ require_merge_queue: form.require_merge_queue.is_some(),
1104 required_checks: form.required_checks.clone(),1121 required_checks: form.required_checks.clone(),
1105 error: Some(message),1122 error: Some(message),
1106 },1123 },
crates/forge-web/src/pulls_sync.rsmodified+1 -0
@@ -106,6 +106,7 @@ async fn sync_head(
106 let head_path = forge_git::repo::repo_path(&state.git.data_dir, &head_repo.id)?;106 let head_path = forge_git::repo::repo_path(&state.git.data_dir, &head_repo.id)?;
107 fetch_into_pull_ref(&state.git, &base_path, &head_path, new, number).await?;107 fetch_into_pull_ref(&state.git, &base_path, &head_path, new, number).await?;
108 state.store.update_pull_head(issue_id, new).await?;108 state.store.update_pull_head(issue_id, new).await?;
109+ crate::merge_queue::drop_pull(state, &base_repo, issue_id, "head_changed").await;
109 if pr.auto_merge.is_some() {110 if pr.auto_merge.is_some() {
110 // `update_pull_head` already cleared the setting; tell the timeline why.111 // `update_pull_head` already cleared the setting; tell the timeline why.
111 state112 state
crates/forge-web/tests/merge_queue_e2e.rsadded+742 -0
@@ -0,0 +1,742 @@
1+//! End-to-end: the merge queue on a protected branch, against the real `forge` binary and the
2+//! real `forge-runner` library (see `ci_e2e.rs` for the harness).
3+//!
4+//! Scenarios:
5+//! - two pull requests queue; the first lands on a tested candidate, the second is removed with
6+//! a comment linking its failing run, and `main` only ever holds the tested commit;
7+//! - a new commit on a queued pull request's head removes it from the queue.
8+
9+// The harness helpers are the same ones `ci_e2e.rs` uses. This file uses a subset of them.
10+#![allow(dead_code)]
11+
12+mod common;
13+use common::{BIN, Server, launch, pick_ports, tool_on_path, write_config};
14+use forge_ci::proto::{JobAssignment, RegisterRequest};
15+use forge_runner::client::ForgeClient;
16+use forge_runner::config::{Limits, RunnerConfig};
17+use forge_runner::executor::HostExecutor;
18+use forge_runner::runner::{RunOptions, Runner};
19+use std::collections::BTreeMap;
20+use std::fs;
21+use std::path::{Path, PathBuf};
22+use std::process::{Command, Output};
23+use std::sync::Arc;
24+use std::time::{Duration, Instant};
25+use tokio_util::sync::CancellationToken;
26+
27+use reqwest::header::{LOCATION, SET_COOKIE};
28+
29+const TAHINLI_PW: &str = "tahinli-password-123";
30+const BOB_PW: &str = "bob-password-4567";
31+const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1";
32+const REPO_PATH: &str = "/tahinli/r";
33+const LABELS: &[&str] = &["linux"];
34+
35+/// A parsed HTTP response. Only the parts the test needs are kept.
36+struct Resp {
37+ status: u16,
38+ location: Option<String>,
39+ set_cookies: Vec<String>,
40+ body: String,
41+}
42+
43+struct Http {
44+ client: reqwest::Client,
45+ base: String,
46+}
47+
48+impl Http {
49+ fn new(port: u16) -> Self {
50+ let client = reqwest::Client::builder()
51+ .redirect(reqwest::redirect::Policy::none())
52+ .timeout(Duration::from_secs(60))
53+ .build()
54+ .expect("http client");
55+ Self {
56+ client,
57+ base: format!("http://127.0.0.1:{port}"),
58+ }
59+ }
60+
61+ async fn get(&self, path: &str, cookie: Option<&str>) -> Resp {
62+ self.send(self.client.get(format!("{}{path}", self.base)), cookie)
63+ .await
64+ }
65+
66+ async fn get_bearer(&self, path: &str, token: &str) -> Resp {
67+ let req = self
68+ .client
69+ .get(format!("{}{path}", self.base))
70+ .bearer_auth(token);
71+ self.send(req, None).await
72+ }
73+
74+ async fn post_form(&self, path: &str, form: &[(&str, &str)], cookie: Option<&str>) -> Resp {
75+ self.send(
76+ self.client.post(format!("{}{path}", self.base)).form(form),
77+ cookie,
78+ )
79+ .await
80+ }
81+
82+ async fn send(&self, req: reqwest::RequestBuilder, cookie: Option<&str>) -> Resp {
83+ let req = match cookie {
84+ Some(cookie) => req.header(reqwest::header::COOKIE, cookie),
85+ None => req,
86+ };
87+ let res = req.send().await.expect("http request");
88+ let status = res.status().as_u16();
89+ let location = res
90+ .headers()
91+ .get(LOCATION)
92+ .and_then(|v| v.to_str().ok())
93+ .map(str::to_owned);
94+ let set_cookies = res
95+ .headers()
96+ .get_all(SET_COOKIE)
97+ .iter()
98+ .filter_map(|v| v.to_str().ok().map(str::to_owned))
99+ .collect();
100+ let body = res.text().await.unwrap_or_default();
101+ Resp {
102+ status,
103+ location,
104+ set_cookies,
105+ body,
106+ }
107+ }
108+}
109+
110+/// Returns `name=value` for the cookie whose name ends with `suffix`. Cleared cookies are ignored.
111+fn cookie_named(resp: &Resp, suffix: &str) -> Option<String> {
112+ resp.set_cookies.iter().find_map(|set| {
113+ let pair = set.split(';').next()?;
114+ let (name, value) = pair.split_once('=')?;
115+ (name.ends_with(suffix) && !value.is_empty()).then(|| format!("{name}={value}"))
116+ })
117+}
118+
119+/// The value of the first `<input name="...">` on a page.
120+fn input_value(body: &str, name: &str) -> String {
121+ let doc = scraper::Html::parse_document(body);
122+ let selector = scraper::Selector::parse(&format!("input[name=\"{name}\"]")).expect("selector");
123+ doc.select(&selector)
124+ .next()
125+ .and_then(|el| el.value().attr("value"))
126+ .unwrap_or_else(|| panic!("no input named {name} on page"))
127+ .to_owned()
128+}
129+
130+/// The text of the first element matching `selector`.
131+fn first_text(body: &str, selector: &str) -> String {
132+ let doc = scraper::Html::parse_document(body);
133+ let selector = scraper::Selector::parse(selector).expect("selector");
134+ doc.select(&selector)
135+ .next()
136+ .unwrap_or_else(|| panic!("no element matches {selector:?}"))
137+ .text()
138+ .collect::<String>()
139+ .trim()
140+ .to_owned()
141+}
142+
143+fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
144+ let out = Command::new(BIN)
145+ .arg("--config")
146+ .arg(config)
147+ .args(["admin", "create-user", username])
148+ .args(extra)
149+ .env("FORGE_PASSWORD", password)
150+ .output()
151+ .expect("run admin create-user");
152+ ok(&out, &format!("create-user {username}"));
153+}
154+
155+fn ok(out: &Output, what: &str) {
156+ assert!(
157+ out.status.success(),
158+ "{what} failed:\n{}",
159+ String::from_utf8_lossy(&out.stderr)
160+ );
161+}
162+
163+/// Runs git in `cwd` with `env` applied on top of the inherited environment. Returns stdout.
164+fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String {
165+ let mut cmd = Command::new("git");
166+ cmd.current_dir(cwd)
167+ .args(["-c", "credential.helper="])
168+ .args(args)
169+ .env("GIT_TERMINAL_PROMPT", "0");
170+ for (key, value) in env {
171+ cmd.env(key, value);
172+ }
173+ let out = cmd.output().expect("run git");
174+ assert!(
175+ out.status.success(),
176+ "git {args:?} failed:\n{}",
177+ String::from_utf8_lossy(&out.stderr)
178+ );
179+ String::from_utf8_lossy(&out.stdout).trim().to_owned()
180+}
181+
182+fn git(cwd: &Path, args: &[&str]) -> String {
183+ git_env(cwd, args, &[])
184+}
185+
186+/// Writes `file` (creating its directory), commits it with `who` as author and committer, and
187+/// returns the new HEAD.
188+fn commit(
189+ repo: &Path,
190+ file: &str,
191+ contents: &str,
192+ message: &str,
193+ who: &str,
194+ email: &str,
195+) -> String {
196+ let path = repo.join(file);
197+ if let Some(parent) = path.parent() {
198+ fs::create_dir_all(parent).expect("create dir");
199+ }
200+ fs::write(&path, contents).expect("write file");
201+ git(repo, &["add", file]);
202+ git_env(
203+ repo,
204+ &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message],
205+ &[
206+ ("GIT_AUTHOR_NAME", who),
207+ ("GIT_AUTHOR_EMAIL", email),
208+ ("GIT_COMMITTER_NAME", who),
209+ ("GIT_COMMITTER_EMAIL", email),
210+ ],
211+ );
212+ git(repo, &["rev-parse", "HEAD"])
213+}
214+
215+/// Clones `url` into `into` (a path that does not exist yet) and returns it.
216+fn clone(url: &str, into: &Path) -> PathBuf {
217+ let parent = into.parent().expect("clone target has a parent");
218+ git(
219+ parent,
220+ &["clone", "-q", url, into.to_str().expect("utf-8 path")],
221+ );
222+ into.to_path_buf()
223+}
224+
225+/// The HTTPS remote for `owner/repo`, authenticated with a token.
226+fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {
227+ format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
228+}
229+
230+/// The CSRF token shown on any settings page of the signed-in user.
231+async fn csrf_from(http: &Http, path: &str, session: &str) -> String {
232+ let page = http.get(path, Some(session)).await;
233+ assert_eq!(page.status, 200, "GET {path}");
234+ input_value(&page.body, "csrf")
235+}
236+
237+/// Logs in through the real `/login` form and returns the `__Host-forge_session` cookie header.
238+async fn login(http: &Http, username: &str, password: &str) -> String {
239+ let page = http.get("/login", None).await;
240+ assert_eq!(page.status, 200, "GET /login");
241+ let precsrf_cookie = cookie_named(&page, "forge_precsrf").expect("precsrf cookie");
242+ let precsrf = input_value(&page.body, "precsrf");
243+ let res = http
244+ .post_form(
245+ "/login",
246+ &[
247+ ("username", username),
248+ ("password", password),
249+ ("next", "/"),
250+ ("precsrf", &precsrf),
251+ ],
252+ Some(&precsrf_cookie),
253+ )
254+ .await;
255+ assert_eq!(res.status, 303, "login as {username}: {}", res.body);
256+ cookie_named(&res, "forge_session").expect("session cookie after login")
257+}
258+
259+/// Creates an access token through `/settings/tokens` and returns the token shown once.
260+async fn create_token(http: &Http, session: &str, name: &str) -> String {
261+ let csrf = csrf_from(http, "/settings/tokens", session).await;
262+ let res = http
263+ .post_form(
264+ "/settings/tokens",
265+ &[("csrf", &csrf), ("name", name), ("expires", "30")],
266+ Some(session),
267+ )
268+ .await;
269+ assert_eq!(res.status, 200, "create token: {}", res.body);
270+ let token = first_text(&res.body, "pre.code code");
271+ assert!(token.starts_with("forge_"), "unexpected token shape");
272+ token
273+}
274+
275+/// Creates a public repo `name` owned by tahinli through `/new`.
276+async fn create_repo(http: &Http, session: &str, name: &str) {
277+ let page = http.get("/new", Some(session)).await;
278+ assert_eq!(page.status, 200, "GET /new");
279+ let csrf = input_value(&page.body, "csrf");
280+ let res = http
281+ .post_form(
282+ "/new",
283+ &[
284+ ("csrf", &csrf),
285+ ("name", name),
286+ ("description", ""),
287+ ("visibility", "public"),
288+ ("default_branch", "main"),
289+ ],
290+ Some(session),
291+ )
292+ .await;
293+ assert_eq!(res.status, 303, "create repo {name}: {}", res.body);
294+ assert_eq!(
295+ res.location.as_deref(),
296+ Some(format!("/tahinli/{name}").as_str())
297+ );
298+}
299+
300+/// Adds or replaces a repo secret through the settings form.
301+async fn set_secret(http: &Http, session: &str, name: &str, value: &str) {
302+ let csrf = csrf_from(http, &format!("{REPO_PATH}/settings/secrets"), session).await;
303+ let res = http
304+ .post_form(
305+ &format!("{REPO_PATH}/settings/secrets"),
306+ &[("csrf", &csrf), ("name", name), ("value", value)],
307+ Some(session),
308+ )
309+ .await;
310+ assert_eq!(res.status, 303, "set secret {name}: {}", res.body);
311+}
312+
313+/// A running server with its own temp data dir. Field order matters: the server is dropped (and
314+/// killed) before the temp dir is removed.
315+struct Booted {
316+ _server: Server,
317+ _root: tempfile::TempDir,
318+ dir: PathBuf,
319+ http: Http,
320+ base_url: String,
321+ port: u16,
322+}
323+
324+/// The server's log, for assertion messages.
325+fn server_log(b: &Booted) -> String {
326+ fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()
327+}
328+
329+/// Creates tahinli (admin) and bob, then boots the server on fresh ports.
330+async fn boot() -> Booted {
331+ // Keep the path short: the internal unix socket path is limited to 108 bytes.
332+ let root = tempfile::Builder::new()
333+ .prefix("ci2e")
334+ .tempdir_in("/tmp")
335+ .expect("temp dir");
336+ let dir = root.path().to_path_buf();
337+ let ports = pick_ports();
338+ let config = write_config(&dir, ports);
339+
340+ run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
341+ run_admin(&config, "bob", &[], BOB_PW);
342+ let (server, ports) = launch(&dir, ports).await;
343+ Booted {
344+ _server: server,
345+ _root: root,
346+ dir,
347+ http: Http::new(ports.http),
348+ base_url: format!("http://127.0.0.1:{}", ports.http),
349+ port: ports.http,
350+ }
351+}
352+
353+/// A registered runner and the secret it claims with.
354+struct Worker {
355+ runner: Runner,
356+ secret: String,
357+ labels: Vec<String>,
358+}
359+
360+impl Worker {
361+ /// One claim. `None` means the forge had nothing for this runner (after its long poll).
362+ async fn claim(&self) -> Option<JobAssignment> {
363+ self.runner
364+ .client()
365+ .claim(&self.secret, &self.labels)
366+ .await
367+ .expect("claim")
368+ .job
369+ }
370+
371+ /// Claims and runs jobs until the forge has nothing left. Returns how many ran.
372+ async fn drain(&self) -> usize {
373+ let mut ran = 0;
374+ while let Some(job) = self.claim().await {
375+ self.runner.process(job, CancellationToken::new()).await;
376+ ran += 1;
377+ }
378+ ran
379+ }
380+}
381+
382+/// Registers a runner through the admin page and the runner API. The admin is `admin_session`.
383+async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker {
384+ let page = b.http.get("/admin/runners", Some(admin_session)).await;
385+ assert_eq!(page.status, 200, "GET /admin/runners");
386+ let csrf = input_value(&page.body, "csrf");
387+ let res = b
388+ .http
389+ .post_form(
390+ "/admin/runners/tokens",
391+ &[("csrf", &csrf)],
392+ Some(admin_session),
393+ )
394+ .await;
395+ assert_eq!(res.status, 200, "create registration token: {}", res.body);
396+ let token = first_text(&res.body, "#reg-token");
397+
398+ let client = ForgeClient::new(&b.base_url).expect("runner client");
399+ let registered = client
400+ .register(&RegisterRequest {
401+ token,
402+ name: name.to_owned(),
403+ labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
404+ })
405+ .await
406+ .expect("register runner");
407+ let config = RunnerConfig {
408+ url: b.base_url.clone(),
409+ runner_id: registered.runner_id,
410+ runner_secret: registered.runner_secret.clone(),
411+ name: name.to_owned(),
412+ labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
413+ work_dir: b.dir.join("runner-work"),
414+ concurrency: 1,
415+ limits: Limits::default(),
416+ executor: forge_runner::config::ExecutorKind::default(),
417+ images: forge_runner::config::ImagesConfig::default(),
418+ sandbox: forge_runner::config::SandboxConfig::default(),
419+ registries: Vec::new(),
420+ // The e2e runner must not replace the test binary under itself.
421+ auto_update: false,
422+ cache_max_gib: 0,
423+ };
424+ let runner =
425+ Runner::new(config, Arc::new(HostExecutor), RunOptions::default()).expect("runner");
426+ Worker {
427+ runner,
428+ secret: registered.runner_secret,
429+ labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
430+ }
431+}
432+
433+/// One commit status as the status API reports it.
434+#[derive(Debug, Clone)]
435+struct Status {
436+ state: String,
437+ description: String,
438+ target_url: String,
439+}
440+
441+/// The statuses on `sha` of tahinli/r, keyed by context.
442+async fn statuses(http: &Http, token: &str, sha: &str) -> BTreeMap<String, Status> {
443+ let res = http
444+ .get_bearer(
445+ &format!("/api/v1/repos/tahinli/r/commits/{sha}/statuses"),
446+ token,
447+ )
448+ .await;
449+ assert_eq!(res.status, 200, "statuses for {sha}: {}", res.body);
450+ let json: serde_json::Value = serde_json::from_str(&res.body).expect("statuses json");
451+ json["statuses"]
452+ .as_array()
453+ .expect("statuses array")
454+ .iter()
455+ .map(|s| {
456+ let field = |k: &str| s[k].as_str().unwrap_or_default().to_owned();
457+ (
458+ field("context"),
459+ Status {
460+ state: field("state"),
461+ description: field("description"),
462+ target_url: field("target_url"),
463+ },
464+ )
465+ })
466+ .collect()
467+}
468+
469+/// Polls the statuses until every context in `contexts` is present, then returns them.
470+async fn wait_statuses(
471+ http: &Http,
472+ token: &str,
473+ sha: &str,
474+ contexts: &[&str],
475+) -> BTreeMap<String, Status> {
476+ let deadline = Instant::now() + Duration::from_secs(20);
477+ loop {
478+ let found = statuses(http, token, sha).await;
479+ if contexts.iter().all(|c| found.contains_key(*c)) {
480+ return found;
481+ }
482+ assert!(
483+ Instant::now() < deadline,
484+ "statuses never showed {contexts:?}; got {found:?}"
485+ );
486+ tokio::time::sleep(Duration::from_millis(100)).await;
487+ }
488+}
489+
490+/// The job id at the end of a status `target_url` (`.../ci/jobs/<id>`).
491+fn job_id_of(status: &Status) -> String {
492+ status
493+ .target_url
494+ .rsplit('/')
495+ .next()
496+ .filter(|id| !id.is_empty())
497+ .unwrap_or_else(|| panic!("no job id in {:?}", status.target_url))
498+ .to_owned()
499+}
500+
501+/// Pushes `.forge/ci.toml` (with `contents`) to `main` as tahinli. Returns the pushed commit.
502+fn push_ci_config(work: &Path, contents: &str) -> String {
503+ let sha = commit(
504+ work,
505+ ".forge/ci.toml",
506+ contents,
507+ "add ci",
508+ "tahinli",
509+ "tahinli@example.test",
510+ );
511+ git(work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
512+ sha
513+}
514+
515+/// The queue's workflow. Only the queue runs it (`merge_queue = true`), never the push to main.
516+/// The job fails when a candidate holds both files, which is what a semantic conflict looks like.
517+const CI_TOML_QUEUE: &str = r#"[on]
518+merge_queue = true
519+
520+[jobs.test]
521+image = "docker.io/library/alpine:3"
522+run = "if [ -f a.txt ] && [ -f b.txt ]; then echo both files present; exit 1; fi"
523+"#;
524+
525+/// Turns the merge queue on for `main` through the branch rule form.
526+async fn require_merge_queue(http: &Http, session: &str) {
527+ let csrf = csrf_from(http, &format!("{REPO_PATH}/settings"), session).await;
528+ let res = http
529+ .post_form(
530+ &format!("{REPO_PATH}/settings/branches"),
531+ &[
532+ ("csrf", &csrf),
533+ ("pattern", "main"),
534+ ("required_approvals", "0"),
535+ ("require_merge_queue", "on"),
536+ ],
537+ Some(session),
538+ )
539+ .await;
540+ assert!(
541+ res.status == 200 || res.status == 303,
542+ "save branch rule: {} {}",
543+ res.status,
544+ res.body
545+ );
546+}
547+
548+/// Pushes one new file on a branch cut from `origin/main`, opens a pull request for it and
549+/// returns the pull request number.
550+async fn open_pull(http: &Http, session: &str, work: &Path, branch: &str, file: &str) -> i64 {
551+ git(work, &["fetch", "-q", "origin"]);
552+ let start = "origin/main";
553+ git(work, &["checkout", "-q", "-B", branch, start]);
554+ let author = "tahinli@example.test";
555+ commit(
556+ work,
557+ file,
558+ "change\n",
559+ &format!("add {file}"),
560+ "tahinli",
561+ author,
562+ );
563+ let target = format!("HEAD:refs/heads/{branch}");
564+ git(work, &["push", "-q", "-f", "origin", &target]);
565+
566+ let csrf = csrf_from(http, &format!("{REPO_PATH}/pulls"), session).await;
567+ let res = http
568+ .post_form(
569+ &format!("{REPO_PATH}/pulls"),
570+ &[
571+ ("csrf", &csrf),
572+ ("title", &format!("Add {file}")),
573+ ("body", ""),
574+ ("base", "main"),
575+ ("head", branch),
576+ ],
577+ Some(session),
578+ )
579+ .await;
580+ assert_eq!(res.status, 303, "open pull for {branch}: {}", res.body);
581+ let location = res.location.expect("pull location");
582+ location
583+ .rsplit('/')
584+ .next()
585+ .and_then(|n| n.parse().ok())
586+ .expect("pull number in location")
587+}
588+
589+/// Queues a pull request with the merge style `merge`.
590+async fn enqueue(http: &Http, session: &str, number: i64) {
591+ let csrf = csrf_from(http, &format!("{REPO_PATH}/pulls/{number}"), session).await;
592+ let res = http
593+ .post_form(
594+ &format!("{REPO_PATH}/pulls/{number}/merge-queue"),
595+ &[("csrf", &csrf), ("style", "merge")],
596+ Some(session),
597+ )
598+ .await;
599+ assert_eq!(res.status, 303, "enqueue #{number}: {}", res.body);
600+}
601+
602+/// The body of a pull request page, lowercased for loose text checks.
603+async fn pull_page(http: &Http, session: &str, number: i64) -> String {
604+ let res = http
605+ .get(&format!("{REPO_PATH}/pulls/{number}"), Some(session))
606+ .await;
607+ assert_eq!(res.status, 200, "GET pull #{number}");
608+ res.body
609+}
610+
611+/// Pushes the queue workflow to `main` and runs its push-less base state to completion, so the
612+/// only runs from here on are queue candidates.
613+async fn setup_queue_repo(b: &Booted, tahinli: &str, token: &str) -> (Worker, PathBuf) {
614+ create_repo(&b.http, tahinli, "r").await;
615+ require_merge_queue(&b.http, tahinli).await;
616+ let worker = register_runner(b, tahinli, "runner-a").await;
617+ let work = clone(
618+ &remote(b.port, "tahinli", token, "tahinli", "r"),
619+ &b.dir.join("tahinli-work"),
620+ );
621+ commit(
622+ &work,
623+ ".forge/ci.toml",
624+ CI_TOML_QUEUE,
625+ "add queue ci",
626+ "tahinli",
627+ "tahinli@example.test",
628+ );
629+ git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
630+ (worker, work)
631+}
632+
633+#[tokio::test]
634+async fn merge_queue_lands_the_first_pull_and_kicks_out_the_conflicting_second() {
635+ if !tool_on_path("git") {
636+ eprintln!("SKIP merge_queue_e2e: `git` was not found on PATH");
637+ return;
638+ }
639+ let b = boot().await;
640+ let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
641+ let token = create_token(&b.http, &tahinli, "mq-token").await;
642+ let (worker, work) = setup_queue_repo(&b, &tahinli, &token).await;
643+
644+ let first = open_pull(&b.http, &tahinli, &work, "one", "a.txt").await;
645+ let second = open_pull(&b.http, &tahinli, &work, "two", "b.txt").await;
646+ enqueue(&b.http, &tahinli, first).await;
647+ enqueue(&b.http, &tahinli, second).await;
648+
649+ let waiting = pull_page(&b.http, &tahinli, second).await;
650+ assert!(
651+ waiting.contains("Position 2 in the merge queue"),
652+ "second pull shows its place: {}\n{}",
653+ waiting.len(),
654+ server_log(&b)
655+ );
656+
657+ // The first candidate passes and lands. The second candidate is then built on the new tip,
658+ // holds both files, and fails.
659+ let ran = worker.drain().await;
660+ assert_eq!(ran, 2, "one candidate run each: {}", server_log(&b));
661+
662+ git(&work, &["fetch", "-q", "origin"]);
663+ let main_tip = git(&work, &["rev-parse", "origin/main"]);
664+ let files = git(&work, &["ls-tree", "--name-only", "origin/main"]);
665+ assert!(files.contains("a.txt"), "first pull landed: {files}");
666+ assert!(
667+ !files.contains("b.txt"),
668+ "second pull did not land: {files}"
669+ );
670+
671+ // The target only points at a tested commit: the candidate carries its passing run.
672+ let found = statuses(&b.http, &token, &main_tip).await;
673+ assert_eq!(
674+ found["ci/test"].state, "success",
675+ "main is the tested commit"
676+ );
677+
678+ let landed = pull_page(&b.http, &tahinli, first).await.to_lowercase();
679+ assert!(landed.contains("merged"), "first pull is merged");
680+
681+ let kicked = pull_page(&b.http, &tahinli, second).await.to_lowercase();
682+ assert!(
683+ kicked.contains("the merge queue removed this pull request"),
684+ "second pull got the comment"
685+ );
686+ assert!(
687+ kicked.contains("/ci/runs/"),
688+ "the comment links the failing run"
689+ );
690+
691+ let queue = b
692+ .http
693+ .get(&format!("{REPO_PATH}/merge-queue"), Some(&tahinli))
694+ .await;
695+ assert_eq!(queue.status, 200, "GET queue page");
696+ let history = b
697+ .http
698+ .get(
699+ &format!("{REPO_PATH}/merge-queue?show=history"),
700+ Some(&tahinli),
701+ )
702+ .await;
703+ assert_eq!(history.status, 200, "GET queue history");
704+}
705+
706+#[tokio::test]
707+async fn pushing_to_a_queued_pull_removes_it_from_the_queue() {
708+ if !tool_on_path("git") {
709+ eprintln!("SKIP merge_queue_e2e: `git` was not found on PATH");
710+ return;
711+ }
712+ let b = boot().await;
713+ let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
714+ let token = create_token(&b.http, &tahinli, "mq-token").await;
715+ let (_worker, work) = setup_queue_repo(&b, &tahinli, &token).await;
716+
717+ let number = open_pull(&b.http, &tahinli, &work, "three", "c.txt").await;
718+ enqueue(&b.http, &tahinli, number).await;
719+ let queued = pull_page(&b.http, &tahinli, number).await;
720+ assert!(queued.contains("Position 1 in the merge queue"), "queued");
721+
722+ // A new commit on the pull request head: the entry no longer tests what it was queued for.
723+ commit(
724+ &work,
725+ "c.txt",
726+ "changed again\n",
727+ "more",
728+ "tahinli",
729+ "tahinli@example.test",
730+ );
731+ git(&work, &["push", "-q", "origin", "HEAD:refs/heads/three"]);
732+
733+ let after = pull_page(&b.http, &tahinli, number).await;
734+ assert!(
735+ !after.contains("Position 1 in the merge queue"),
736+ "a moved head leaves the queue"
737+ );
738+ assert!(
739+ after.contains("Add to merge queue"),
740+ "back to the merge box"
741+ );
742+}
docs/ci.mdmodified+1 -0
@@ -39,6 +39,7 @@ page and a `ci/config` status set to `error`.
39 | `manual` | bool | `true` | Writers can start a run on an existing branch from the CI tab. |39 | `manual` | bool | `true` | Writers can start a run on an existing branch from the CI tab. |
40 | `cancel_superseded` | bool | `true` | A push to a branch cancels the queued and running runs for older commits on that branch (see [Superseded runs](#superseded-runs)). |40 | `cancel_superseded` | bool | `true` | A push to a branch cancels the queued and running runs for older commits on that branch (see [Superseded runs](#superseded-runs)). |
41 | `schedule` | array of string | `[]` | Cron expressions (5 fields, UTC). See [Scheduled runs](#scheduled-runs). Max 8. |41 | `schedule` | array of string | `[]` | Cron expressions (5 fields, UTC). See [Scheduled runs](#scheduled-runs). Max 8. |
42+| `merge_queue` | bool | `false` | Run the workflow on each merge queue candidate of a branch that requires the queue. Without it, a candidate runs the `push` jobs of its target branch. See [Merge queue](merge-queue.md). |
42 43
43 ### `[jobs.<name>]`44 ### `[jobs.<name>]`
44 45
docs/merge-queue.mdadded+90 -0
@@ -0,0 +1,90 @@
1+# Merge queue
2+
3+A protected branch can require the merge queue. Then the branch only ever moves to commits that
4+CI has tested, and pull requests that were tested against an older tip cannot land on a newer one
5+by accident.
6+
7+## Turning it on
8+
9+Open the repo's settings, go to branch protection and edit the rule for the branch (usually
10+`main`). Tick **Require merge queue** and save. The rule's summary shows `merge queue required`.
11+
12+With the option on:
13+
14+- The merge box of a pull request shows **Add to merge queue** instead of **Merge**. The merge
15+ style select is kept. Auto-merge is not offered, and the direct merge endpoint refuses the
16+ branch.
17+- The pull request still has to pass the merge checks it would need for a direct merge:
18+ approvals, no changes requested, and no conflicts. Its required status checks must also be
19+ green on its own head, so a pull request that has not passed CI yet cannot enter the queue.
20+ An outdated head does not block it, because the queue tests it on the current tip.
21+- Once queued, the merge box shows **Position N in the merge queue** and a **Remove from queue**
22+ button.
23+
24+## How an entry moves
25+
26+Entries are kept per target branch, in the order they joined.
27+
28+1. **queued**: waiting for the entries ahead of it.
29+2. **testing**: the head of the queue. The forge merges the current tip of the branch and the
30+ pull request head with the merge style the person chose. The merge is made in the object
31+ store, with no working tree, and named by the temporary ref
32+ `refs/forge/merge-queue/{branch}/{number}`. A CI run tests that ref.
33+3. **merging**: the run passed and every required check is green on the candidate. The branch
34+ moves from the tip the candidate was built on to the candidate, as a compare-and-swap. The
35+ pull request is then marked merged, with the usual events, notifications and post-push work.
36+ The entry leaves the queue with the reason `merged`.
37+
38+One thing sends an entry back, and it needs no person:
39+
40+- **The target moved** before the swap. The candidate is built again on the new tip, and its
41+ run starts again. The entry keeps its place at the head.
42+
43+An entry also ends early when:
44+
45+- **Failed** (`tests_failed`, `checks_failed`, `conflict`): the forge comments on the pull
46+ request, mentions the person who queued it, and links the failing run. The entry stays in the
47+ history with its reason.
48+- **Removed** (`removed`): someone pressed **Remove from queue**.
49+- **Removed** (`head_changed`, `closed`): the pull request's head moved, or it was closed while
50+ it waited.
51+- **Removed** (`blocked`, `permission`, `no_branch`): a merge check no longer passes, the person
52+ who queued it can no longer write to the repo, or the branch is gone.
53+
54+When an entry finishes, the next one starts. Nothing polls: each step follows an event, a commit
55+status on a candidate, a request that changes the queue, or a finished entry.
56+
57+## Testing candidates in CI
58+
59+A candidate is a normal commit, so the workflow in `.forge/ci.toml` reads the candidate's own
60+files. The run is started with trigger `merge_queue`, on the commit of the candidate, and its
61+statuses (`ci/<job>`) are written to that commit. Required checks on the branch are read from
62+those statuses.
63+
64+To pick which workflow runs, use the `merge_queue` key in `[on]`:
65+
66+```toml
67+[on]
68+merge_queue = true
69+```
70+
71+- With `merge_queue = true`, the workflow's jobs run for every candidate.
72+- Without it, a candidate runs the `push` jobs of its target branch, the same jobs that run when
73+ a commit lands there. If the workflow has no `push` trigger for the branch, the candidate has
74+ no run.
75+- With no workflow file at the candidate, there is no run. The queue then lands the candidate once
76+ the required checks, if any, are green.
77+
78+See [CI](ci.md#format-reference) for the other `[on]` keys.
79+
80+## Notes
81+
82+- Batching is not supported yet: one pull request is tested at a time.
83+- The comments that the queue writes on a pull request are in English, whatever the viewer's
84+ language.
85+- The queue page is at `/{owner}/{repo}/merge-queue`. It lists the waiting entries with their
86+ position, state, CI run and a remove button. `?show=history` lists the finished entries. The page
87+ follows changes live.
88+- A queued pull request's candidate is kept under `refs/forge/merge-queue/`. Those refs are
89+ temporary; once an entry finishes, its ref is left in place until the next candidate of the
90+ same pull request replaces it.