forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

merge_queue.rs445 lines, 15.9 KiBHistoryRawDownload
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
15use forge_core::merge_queue::{QueueEntry, QueueState, test_ref_name};
16use forge_core::protection::effective;
17use forge_core::store::commit_status::StatusState;
18use forge_core::{Action, IssueState, MergeStyle, Mergeable, PullRequest, Repo, User, authorize};
19use forge_git::browse::default_branch_commit;
20use forge_git::pulls::{set_ref, update_ref_cas};
21use forge_git::repo::repo_path;
22
23use crate::ci::schedule::merge_queue_run;
24use crate::merge::{
25 ERR_CONFLICT, ERR_DRAFT, ERR_HEAD_MISSING, ERR_NEEDS_CHECKS, ERR_NOT_UP_TO_DATE,
26 ERR_QUEUE_ALREADY, MergeOutcome, finish_merge, merge_commit, merge_gate,
27};
28use crate::notify::{self, Activity};
29use crate::state::AppState;
30
31/// Whether the protection of `branch` routes merges through the queue. Direct merges are refused
32/// then.
33pub 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.
46pub 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_entry(state, repo, &entry);
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.
88pub 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_entry(state, repo, entry),
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.
104pub 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.
118pub 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.
139pub 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
145async 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.
179async 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.
204async 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_entry(state, repo, entry);
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.
257pub 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.
326async 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 // Reviews may have changed while the candidate was tested (a change request, a dismissed
351 // approval): the same readiness test as before testing, now right before the target moves.
352 if let Some(reason) = unready(state, repo, pr).await? {
353 finish_removed(state, repo, entry, reason).await?;
354 return Ok(true);
355 }
356 let refname = format!("refs/heads/{}", entry.branch);
357 let base_path = repo_path(&state.git.data_dir, &repo.id)?;
358 match update_ref_cas(&state.git, &base_path, &refname, &tested, &base).await {
359 Ok(()) => {}
360 Err(forge_git::error::Error::RefMoved(_)) => {
361 // The target moved since the candidate was built: build it again on the new tip.
362 state.store.queue_set_queued(&entry.id).await?;
363 notify_entry(state, repo, entry);
364 return Ok(true);
365 }
366 Err(e) => {
367 state.store.queue_set_queued(&entry.id).await?;
368 notify_entry(state, repo, entry);
369 return Err(e.into());
370 }
371 }
372 finish_merge(state, repo, pr, &user, &refname, &base, &tested).await;
373 finish_removed(state, repo, entry, "merged").await?;
374 Ok(true)
375}
376
377/// Ends a merging entry as removed with `reason`.
378async fn finish_removed(
379 state: &AppState,
380 repo: &Repo,
381 entry: &QueueEntry,
382 reason: &str,
383) -> forge_core::Result<()> {
384 state
385 .store
386 .queue_finish(&entry.id, QueueState::Removed, reason)
387 .await?;
388 notify_entry(state, repo, entry);
389 Ok(())
390}
391
392/// Ends an entry as failed and comments on its pull request, mentioning the person who queued it.
393async fn fail(
394 state: &AppState,
395 repo: &Repo,
396 entry: &QueueEntry,
397 pr: &PullRequest,
398 reason: &str,
399 text: &str,
400) -> forge_core::Result<()> {
401 if !state
402 .store
403 .queue_finish(&entry.id, QueueState::Failed, reason)
404 .await?
405 {
406 return Ok(());
407 }
408 notify_entry(state, repo, entry);
409 let who = match state.store.user_by_id(&entry.enqueued_by).await? {
410 Some(user) => format!("@{}", user.username),
411 None => String::new(),
412 };
413 let body = format!("{who} The merge queue removed this pull request: {text}")
414 .trim_start()
415 .to_owned();
416 let ghost = state.store.ensure_ghost_user().await?;
417 match state
418 .store
419 .add_comment(&pr.issue.id, &ghost.id, &body)
420 .await
421 {
422 Ok(_) => {
423 crate::live::bump_pull(state, &repo.id, &pr.issue.id);
424 notify::dispatch(
425 state,
426 repo,
427 &pr.issue,
428 &ghost.id,
429 Activity::Comment,
430 Some(&body),
431 )
432 .await;
433 }
434 Err(e) => {
435 tracing::error!(error = %e, repo_id = %repo.id, "merge queue: commenting failed");
436 }
437 }
438 Ok(())
439}
440
441/// Wakes the queue pages of `repo_id`, and the pull page and list of the entry's pull request.
442fn notify_entry(state: &AppState, repo: &Repo, entry: &QueueEntry) {
443 state.ci_live.bump_queue(&repo.id);
444 crate::live::bump_pull(state, &repo.id, &entry.issue_id);
445}