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_e2e.rs625 lines, 20.4 KiBHistoryRawDownload
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
12use crate::common::{
13 FAST_CLAIMS, Http, Server, bin, input_value, launch_with, login, pick_ports, tool_on_path,
14 write_config,
15};
16use forge_ci::proto::{JobAssignment, RegisterRequest};
17use forge_runner::client::ForgeClient;
18use forge_runner::config::{Limits, RunnerConfig};
19use forge_runner::executor::HostExecutor;
20use forge_runner::runner::{RunOptions, Runner};
21use std::collections::BTreeMap;
22use std::fs;
23use std::path::{Path, PathBuf};
24use std::process::{Command, Output};
25use std::sync::Arc;
26use std::time::{Duration, Instant};
27use tokio_util::sync::CancellationToken;
28
29const TAHINLI_PW: &str = "tahinli-password-123";
30const BOB_PW: &str = "bob-password-4567";
31const BOB_EMAIL: &str = "bob@users.noreply.127.0.0.1";
32const REPO_PATH: &str = "/tahinli/r";
33const LABELS: &[&str] = &["linux"];
34
35/// The text of the first element matching `selector`.
36fn first_text(body: &str, selector: &str) -> String {
37 let doc = scraper::Html::parse_document(body);
38 let selector = scraper::Selector::parse(selector).expect("selector");
39 doc.select(&selector)
40 .next()
41 .unwrap_or_else(|| panic!("no element matches {selector:?}"))
42 .text()
43 .collect::<String>()
44 .trim()
45 .to_owned()
46}
47
48fn run_admin(config: &Path, username: &str, extra: &[&str], password: &str) {
49 let out = Command::new(bin())
50 .arg("--config")
51 .arg(config)
52 .args(["admin", "create-user", username])
53 .args(extra)
54 .env("FORGE_PASSWORD", password)
55 .output()
56 .expect("run admin create-user");
57 ok(&out, &format!("create-user {username}"));
58}
59
60fn ok(out: &Output, what: &str) {
61 assert!(
62 out.status.success(),
63 "{what} failed:\n{}",
64 String::from_utf8_lossy(&out.stderr)
65 );
66}
67
68/// Runs git in `cwd` with `env` applied on top of the inherited environment. Returns stdout.
69fn git_env(cwd: &Path, args: &[&str], env: &[(&str, &str)]) -> String {
70 let mut cmd = Command::new("git");
71 cmd.current_dir(cwd)
72 .args(["-c", "credential.helper="])
73 .args(args)
74 .env("GIT_TERMINAL_PROMPT", "0");
75 for (key, value) in env {
76 cmd.env(key, value);
77 }
78 let out = cmd.output().expect("run git");
79 assert!(
80 out.status.success(),
81 "git {args:?} failed:\n{}",
82 String::from_utf8_lossy(&out.stderr)
83 );
84 String::from_utf8_lossy(&out.stdout).trim().to_owned()
85}
86
87fn git(cwd: &Path, args: &[&str]) -> String {
88 git_env(cwd, args, &[])
89}
90
91/// Writes `file` (creating its directory), commits it with `who` as author and committer, and
92/// returns the new HEAD.
93fn commit(
94 repo: &Path,
95 file: &str,
96 contents: &str,
97 message: &str,
98 who: &str,
99 email: &str,
100) -> String {
101 let path = repo.join(file);
102 if let Some(parent) = path.parent() {
103 fs::create_dir_all(parent).expect("create dir");
104 }
105 fs::write(&path, contents).expect("write file");
106 git(repo, &["add", file]);
107 git_env(
108 repo,
109 &["-c", "commit.gpgsign=false", "commit", "-q", "-m", message],
110 &[
111 ("GIT_AUTHOR_NAME", who),
112 ("GIT_AUTHOR_EMAIL", email),
113 ("GIT_COMMITTER_NAME", who),
114 ("GIT_COMMITTER_EMAIL", email),
115 ],
116 );
117 git(repo, &["rev-parse", "HEAD"])
118}
119
120/// Clones `url` into `into` (a path that does not exist yet) and returns it.
121fn clone(url: &str, into: &Path) -> PathBuf {
122 let parent = into.parent().expect("clone target has a parent");
123 git(
124 parent,
125 &["clone", "-q", url, into.to_str().expect("utf-8 path")],
126 );
127 into.to_path_buf()
128}
129
130/// The HTTPS remote for `owner/repo`, authenticated with a token.
131fn remote(port: u16, user: &str, token: &str, owner: &str, repo: &str) -> String {
132 format!("http://{user}:{token}@127.0.0.1:{port}/{owner}/{repo}.git")
133}
134
135/// The CSRF token shown on any settings page of the signed-in user.
136async fn csrf_from(http: &Http, path: &str, session: &str) -> String {
137 let page = http.get(path, Some(session)).await;
138 assert_eq!(page.status, 200, "GET {path}");
139 input_value(&page.body, "csrf")
140}
141
142/// Creates an access token through `/settings/tokens` and returns the token shown once.
143async fn create_token(http: &Http, session: &str, name: &str) -> String {
144 let csrf = csrf_from(http, "/settings/keys", session).await;
145 let res = http
146 .post_form(
147 "/settings/tokens",
148 &[("csrf", &csrf), ("name", name), ("expires", "30")],
149 Some(session),
150 )
151 .await;
152 assert_eq!(res.status, 200, "create token: {}", res.body);
153 let token = first_text(&res.body, "pre.code code");
154 assert!(token.starts_with("forge_"), "unexpected token shape");
155 token
156}
157
158/// Creates a public repo `name` owned by tahinli through `/new`.
159async fn create_repo(http: &Http, session: &str, name: &str) {
160 let page = http.get("/new", Some(session)).await;
161 assert_eq!(page.status, 200, "GET /new");
162 let csrf = input_value(&page.body, "csrf");
163 let res = http
164 .post_form(
165 "/new",
166 &[
167 ("csrf", &csrf),
168 ("name", name),
169 ("description", ""),
170 ("visibility", "public"),
171 ("default_branch", "main"),
172 ],
173 Some(session),
174 )
175 .await;
176 assert_eq!(res.status, 303, "create repo {name}: {}", res.body);
177 assert_eq!(
178 res.location().as_deref(),
179 Some(format!("/tahinli/{name}").as_str())
180 );
181}
182
183/// Adds or replaces a repo secret through the settings form.
184async fn set_secret(http: &Http, session: &str, name: &str, value: &str) {
185 let csrf = csrf_from(http, &format!("{REPO_PATH}/settings/secrets"), session).await;
186 let res = http
187 .post_form(
188 &format!("{REPO_PATH}/settings/secrets"),
189 &[("csrf", &csrf), ("name", name), ("value", value)],
190 Some(session),
191 )
192 .await;
193 assert_eq!(res.status, 303, "set secret {name}: {}", res.body);
194}
195
196/// A running server with its own temp data dir. Field order matters: the server is dropped (and
197/// killed) before the temp dir is removed.
198struct Booted {
199 _server: Server,
200 _root: tempfile::TempDir,
201 dir: PathBuf,
202 http: Http,
203 base_url: String,
204 port: u16,
205}
206
207/// The server's log, for assertion messages.
208fn server_log(b: &Booted) -> String {
209 fs::read_to_string(b.dir.join("serve.log")).unwrap_or_default()
210}
211
212/// Creates tahinli (admin) and bob, then boots the server on fresh ports.
213async fn boot() -> Booted {
214 // Keep the path short: the internal unix socket path is limited to 108 bytes.
215 let root = tempfile::Builder::new()
216 .prefix("ci2e")
217 .tempdir_in("/tmp")
218 .expect("temp dir");
219 let dir = root.path().to_path_buf();
220 let ports = pick_ports();
221 let config = write_config(&dir, ports);
222
223 run_admin(&config, "tahinli", &["--admin"], TAHINLI_PW);
224 run_admin(&config, "bob", &[], BOB_PW);
225 let (server, ports) = launch_with(&dir, ports, FAST_CLAIMS).await;
226 Booted {
227 _server: server,
228 _root: root,
229 dir,
230 http: Http::new(ports.http),
231 base_url: format!("http://127.0.0.1:{}", ports.http),
232 port: ports.http,
233 }
234}
235
236/// A registered runner and the secret it claims with.
237struct Worker {
238 runner: Runner,
239 secret: String,
240 labels: Vec<String>,
241}
242
243impl Worker {
244 /// One claim. `None` means the forge had nothing for this runner (after its long poll).
245 async fn claim(&self) -> Option<JobAssignment> {
246 self.runner
247 .client()
248 .claim(&self.secret, &self.labels)
249 .await
250 .expect("claim")
251 .job
252 }
253
254 /// Claims and runs jobs until the forge has nothing left. Returns how many ran.
255 async fn drain(&self) -> usize {
256 let mut ran = 0;
257 while let Some(job) = self.claim().await {
258 self.runner.process(job, CancellationToken::new()).await;
259 ran += 1;
260 }
261 ran
262 }
263}
264
265/// Registers a runner through the admin page and the runner API. The admin is `admin_session`.
266async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker {
267 let page = b.http.get("/admin/runners", Some(admin_session)).await;
268 assert_eq!(page.status, 200, "GET /admin/runners");
269 let csrf = input_value(&page.body, "csrf");
270 let res = b
271 .http
272 .post_form(
273 "/admin/runners/tokens",
274 &[("csrf", &csrf)],
275 Some(admin_session),
276 )
277 .await;
278 assert_eq!(res.status, 200, "create registration token: {}", res.body);
279 let token = first_text(&res.body, "#reg-token");
280
281 let client = ForgeClient::new(&b.base_url).expect("runner client");
282 let registered = client
283 .register(&RegisterRequest {
284 token,
285 name: name.to_owned(),
286 labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
287 })
288 .await
289 .expect("register runner");
290 let config = RunnerConfig {
291 url: b.base_url.clone(),
292 runner_id: registered.runner_id,
293 runner_secret: registered.runner_secret.clone(),
294 name: name.to_owned(),
295 labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
296 work_dir: b.dir.join("runner-work"),
297 concurrency: 1,
298 limits: Limits::default(),
299 executor: forge_runner::config::ExecutorKind::default(),
300 images: forge_runner::config::ImagesConfig::default(),
301 sandbox: forge_runner::config::SandboxConfig::default(),
302 registries: Vec::new(),
303 // The e2e runner must not replace the test binary under itself.
304 auto_update: false,
305 cache_max_gib: 0,
306 };
307 let runner =
308 Runner::new(config, Arc::new(HostExecutor), RunOptions::default()).expect("runner");
309 Worker {
310 runner,
311 secret: registered.runner_secret,
312 labels: LABELS.iter().map(|l| (*l).to_owned()).collect(),
313 }
314}
315
316/// One commit status as the status API reports it.
317#[derive(Debug, Clone)]
318struct Status {
319 state: String,
320 description: String,
321 target_url: String,
322}
323
324/// The statuses on `sha` of tahinli/r, keyed by context.
325async fn statuses(http: &Http, token: &str, sha: &str) -> BTreeMap<String, Status> {
326 let res = http
327 .get_bearer(
328 &format!("/api/v1/repos/tahinli/r/commits/{sha}/statuses"),
329 token,
330 )
331 .await;
332 assert_eq!(res.status, 200, "statuses for {sha}: {}", res.body);
333 let json: serde_json::Value = serde_json::from_str(&res.body).expect("statuses json");
334 json["statuses"]
335 .as_array()
336 .expect("statuses array")
337 .iter()
338 .map(|s| {
339 let field = |k: &str| s[k].as_str().unwrap_or_default().to_owned();
340 (
341 field("context"),
342 Status {
343 state: field("state"),
344 description: field("description"),
345 target_url: field("target_url"),
346 },
347 )
348 })
349 .collect()
350}
351
352/// Polls the statuses until every context in `contexts` is present, then returns them.
353async fn wait_statuses(
354 http: &Http,
355 token: &str,
356 sha: &str,
357 contexts: &[&str],
358) -> BTreeMap<String, Status> {
359 let deadline = Instant::now() + Duration::from_secs(20);
360 loop {
361 let found = statuses(http, token, sha).await;
362 if contexts.iter().all(|c| found.contains_key(*c)) {
363 return found;
364 }
365 assert!(
366 Instant::now() < deadline,
367 "statuses never showed {contexts:?}; got {found:?}"
368 );
369 tokio::time::sleep(Duration::from_millis(100)).await;
370 }
371}
372
373/// The job id at the end of a status `target_url` (`.../ci/jobs/<id>`).
374fn job_id_of(status: &Status) -> String {
375 status
376 .target_url
377 .rsplit('/')
378 .next()
379 .filter(|id| !id.is_empty())
380 .unwrap_or_else(|| panic!("no job id in {:?}", status.target_url))
381 .to_owned()
382}
383
384/// Pushes `.forge/ci.toml` (with `contents`) to `main` as tahinli. Returns the pushed commit.
385fn push_ci_config(work: &Path, contents: &str) -> String {
386 let sha = commit(
387 work,
388 ".forge/ci.toml",
389 contents,
390 "add ci",
391 "tahinli",
392 "tahinli@example.test",
393 );
394 git(work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
395 sha
396}
397
398/// The queue's workflow. Only the queue runs it (`merge_queue = true`), never the push to main.
399/// The job fails when a candidate holds both files, which is what a semantic conflict looks like.
400const CI_TOML_QUEUE: &str = r#"[on]
401merge_queue = true
402
403[jobs.test]
404image = "docker.io/library/alpine:3"
405run = "if [ -f a.txt ] && [ -f b.txt ]; then echo both files present; exit 1; fi"
406"#;
407
408/// Turns the merge queue on for `main` through the branch rule form.
409async fn require_merge_queue(http: &Http, session: &str) {
410 let csrf = csrf_from(http, &format!("{REPO_PATH}/settings"), session).await;
411 let res = http
412 .post_form(
413 &format!("{REPO_PATH}/settings/branches"),
414 &[
415 ("csrf", &csrf),
416 ("pattern", "main"),
417 ("required_approvals", "0"),
418 ("require_merge_queue", "on"),
419 ],
420 Some(session),
421 )
422 .await;
423 assert!(
424 res.status == 200 || res.status == 303,
425 "save branch rule: {} {}",
426 res.status,
427 res.body
428 );
429}
430
431/// Pushes one new file on a branch cut from `origin/main`, opens a pull request for it and
432/// returns the pull request number.
433async fn open_pull(http: &Http, session: &str, work: &Path, branch: &str, file: &str) -> i64 {
434 git(work, &["fetch", "-q", "origin"]);
435 let start = "origin/main";
436 git(work, &["checkout", "-q", "-B", branch, start]);
437 let author = "tahinli@example.test";
438 commit(
439 work,
440 file,
441 "change\n",
442 &format!("add {file}"),
443 "tahinli",
444 author,
445 );
446 let target = format!("HEAD:refs/heads/{branch}");
447 git(work, &["push", "-q", "-f", "origin", &target]);
448
449 let csrf = csrf_from(http, &format!("{REPO_PATH}/pulls"), session).await;
450 let res = http
451 .post_form(
452 &format!("{REPO_PATH}/pulls"),
453 &[
454 ("csrf", &csrf),
455 ("title", &format!("Add {file}")),
456 ("body", ""),
457 ("base", "main"),
458 ("head", branch),
459 ],
460 Some(session),
461 )
462 .await;
463 assert_eq!(res.status, 303, "open pull for {branch}: {}", res.body);
464 let location = res.location().expect("pull location");
465 location
466 .rsplit('/')
467 .next()
468 .and_then(|n| n.parse().ok())
469 .expect("pull number in location")
470}
471
472/// Queues a pull request with the merge style `merge`.
473async fn enqueue(http: &Http, session: &str, number: i64) {
474 let csrf = csrf_from(http, &format!("{REPO_PATH}/pulls/{number}"), session).await;
475 let res = http
476 .post_form(
477 &format!("{REPO_PATH}/pulls/{number}/merge-queue"),
478 &[("csrf", &csrf), ("style", "merge")],
479 Some(session),
480 )
481 .await;
482 assert_eq!(res.status, 303, "enqueue #{number}: {}", res.body);
483}
484
485/// The body of a pull request page, lowercased for loose text checks.
486async fn pull_page(http: &Http, session: &str, number: i64) -> String {
487 let res = http
488 .get(&format!("{REPO_PATH}/pulls/{number}"), Some(session))
489 .await;
490 assert_eq!(res.status, 200, "GET pull #{number}");
491 res.body
492}
493
494/// Pushes the queue workflow to `main` and runs its push-less base state to completion, so the
495/// only runs from here on are queue candidates.
496async fn setup_queue_repo(b: &Booted, tahinli: &str, token: &str) -> (Worker, PathBuf) {
497 create_repo(&b.http, tahinli, "r").await;
498 require_merge_queue(&b.http, tahinli).await;
499 let worker = register_runner(b, tahinli, "runner-a").await;
500 let work = clone(
501 &remote(b.port, "tahinli", token, "tahinli", "r"),
502 &b.dir.join("tahinli-work"),
503 );
504 commit(
505 &work,
506 ".forge/ci.toml",
507 CI_TOML_QUEUE,
508 "add queue ci",
509 "tahinli",
510 "tahinli@example.test",
511 );
512 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/main"]);
513 (worker, work)
514}
515
516#[tokio::test]
517async fn merge_queue_lands_the_first_pull_and_kicks_out_the_conflicting_second() {
518 if !tool_on_path("git") {
519 eprintln!("SKIP merge_queue_e2e: `git` was not found on PATH");
520 return;
521 }
522 let b = boot().await;
523 let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
524 let token = create_token(&b.http, &tahinli, "mq-token").await;
525 let (worker, work) = setup_queue_repo(&b, &tahinli, &token).await;
526
527 let first = open_pull(&b.http, &tahinli, &work, "one", "a.txt").await;
528 let second = open_pull(&b.http, &tahinli, &work, "two", "b.txt").await;
529 enqueue(&b.http, &tahinli, first).await;
530 enqueue(&b.http, &tahinli, second).await;
531
532 let waiting = pull_page(&b.http, &tahinli, second).await;
533 assert!(
534 waiting.contains("Position 2 in the merge queue"),
535 "second pull shows its place: {}\n{}",
536 waiting.len(),
537 server_log(&b)
538 );
539
540 // The first candidate passes and lands. The second candidate is then built on the new tip,
541 // holds both files, and fails.
542 let ran = worker.drain().await;
543 assert_eq!(ran, 2, "one candidate run each: {}", server_log(&b));
544
545 git(&work, &["fetch", "-q", "origin"]);
546 let main_tip = git(&work, &["rev-parse", "origin/main"]);
547 let files = git(&work, &["ls-tree", "--name-only", "origin/main"]);
548 assert!(files.contains("a.txt"), "first pull landed: {files}");
549 assert!(
550 !files.contains("b.txt"),
551 "second pull did not land: {files}"
552 );
553
554 // The target only points at a tested commit: the candidate carries its passing run.
555 let found = statuses(&b.http, &token, &main_tip).await;
556 assert_eq!(
557 found["ci/test"].state, "success",
558 "main is the tested commit"
559 );
560
561 let landed = pull_page(&b.http, &tahinli, first).await.to_lowercase();
562 assert!(landed.contains("merged"), "first pull is merged");
563
564 let kicked = pull_page(&b.http, &tahinli, second).await.to_lowercase();
565 assert!(
566 kicked.contains("the merge queue removed this pull request"),
567 "second pull got the comment"
568 );
569 assert!(
570 kicked.contains("/ci/runs/"),
571 "the comment links the failing run"
572 );
573
574 let queue = b
575 .http
576 .get(&format!("{REPO_PATH}/merge-queue"), Some(&tahinli))
577 .await;
578 assert_eq!(queue.status, 200, "GET queue page");
579 let history = b
580 .http
581 .get(
582 &format!("{REPO_PATH}/merge-queue?show=history"),
583 Some(&tahinli),
584 )
585 .await;
586 assert_eq!(history.status, 200, "GET queue history");
587}
588
589#[tokio::test]
590async fn pushing_to_a_queued_pull_removes_it_from_the_queue() {
591 if !tool_on_path("git") {
592 eprintln!("SKIP merge_queue_e2e: `git` was not found on PATH");
593 return;
594 }
595 let b = boot().await;
596 let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await;
597 let token = create_token(&b.http, &tahinli, "mq-token").await;
598 let (_worker, work) = setup_queue_repo(&b, &tahinli, &token).await;
599
600 let number = open_pull(&b.http, &tahinli, &work, "three", "c.txt").await;
601 enqueue(&b.http, &tahinli, number).await;
602 let queued = pull_page(&b.http, &tahinli, number).await;
603 assert!(queued.contains("Position 1 in the merge queue"), "queued");
604
605 // A new commit on the pull request head: the entry no longer tests what it was queued for.
606 commit(
607 &work,
608 "c.txt",
609 "changed again\n",
610 "more",
611 "tahinli",
612 "tahinli@example.test",
613 );
614 git(&work, &["push", "-q", "origin", "HEAD:refs/heads/three"]);
615
616 let after = pull_page(&b.http, &tahinli, number).await;
617 assert!(
618 !after.contains("Position 1 in the merge queue"),
619 "a moved head leaves the queue"
620 );
621 assert!(
622 after.contains("Add to merge queue"),
623 "back to the merge box"
624 );
625}