diff --git a/Cargo.toml b/Cargo.toml index be5593f..2e65cdd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,7 +31,7 @@ serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["preserve_order", "raw_value"] } tempfile = "=3.27.0" thiserror = "2" -tokio = { version = "1", features = ["rt", "macros", "time", "process", "io-std", "io-util", "fs", "sync"] } +tokio = { version = "1", features = ["rt", "macros", "time", "process", "io-std", "io-util", "fs", "sync", "signal"] } toml_edit = "=0.25.15" url = "2" uuid = { version = "1", features = ["serde", "v7"] } diff --git a/src/hooks.rs b/src/hooks.rs index e39691d..96e1d4e 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -24,7 +24,10 @@ use crate::outcome::{self, Outcome}; use crate::render::location; use crate::severity::Severity; use crate::text::one_line; -use crate::{RepositoryArgs, Verdict, connect, connected_repository, preflight, read_review, say}; +use crate::{ + OnInterrupt, ReadReview, RepositoryArgs, Verdict, WaitResult, connect, connected_repository, + preflight, read_review, say, +}; /// Identifies a script this CLI wrote. Uninstall removes a hook only when its /// whole text is the script this version writes, so an edited hook stays. @@ -369,6 +372,9 @@ enum Report { detail: Box, state: Option, }, + + /// The wait was interrupted by `Ctrl-C`. + Interrupted, } /// The subjects to review, and how many pushed branches were left out. @@ -463,6 +469,9 @@ pub(crate) async fn run( report } }; + if matches!(report, Report::Interrupted) { + return Ok(Verdict::Interrupted); + } reports.push((subject.label, report)); } Ok(conclude(hook, &settings, &reports, skipped)) @@ -495,17 +504,28 @@ async fn request( verify_finding_ids: Vec::new(), }; let requested = api.request_patch_review(repository_id, &request).await?; - let (_, detail, state) = - read_review(api, requested.review_id, Some(deadline), false).await?; - anyhow::Ok((requested.review_id, detail, state)) + let on_interrupt = OnInterrupt::for_stoppable_request(requested.existing); + let wait = read_review( + api, + requested.review_id, + Some(deadline), + false, + on_interrupt, + ) + .await?; + anyhow::Ok((requested.review_id, wait)) }; match requested.await { - Ok((review_id, detail, state)) => Report::Read { - review_id, - url: api.review_url(review_id), - detail: Box::new(detail), - state, - }, + Ok((_, WaitResult::Interrupted)) => Report::Interrupted, + Ok((review_id, WaitResult::Ready(read))) => { + let ReadReview { detail, state, .. } = *read; + Report::Read { + review_id, + url: api.review_url(review_id), + detail: Box::new(detail), + state, + } + } Err(error) => Report::Unreviewed(format!("{error:#}")), } } @@ -658,6 +678,7 @@ fn conclude( print_read(label, *review_id, url, detail, *state, complete); failing |= reaches_fail_on(detail, complete, settings.fail_on); } + Report::Interrupted => {} } } if skipped > 0 { diff --git a/src/lib.rs b/src/lib.rs index 2716904..b9a48a2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -415,6 +415,8 @@ pub enum Verdict { Blocked, /// A deploy failed or one of its checks recorded a regression. Regressed, + /// Interrupted by `Ctrl-C` while waiting for a review. + Interrupted, } /// Runs one command. `token` is `PROOFLINE_TOKEN`, read by the caller. @@ -975,7 +977,7 @@ async fn review(api: &Api, args: &ReviewArgs) -> anyhow::Result { "" } )); - finish(api, requested.review_id, args).await + finish(api, requested.review_id, OnInterrupt::Detach, args).await } /// Reviews the checkout's local changes against the commit they build on. @@ -1034,7 +1036,13 @@ async fn review_local(api: &Api, args: &ReviewArgs) -> anyhow::Result { verifying.finding_id, verifying.iteration )); } - finish(api, requested.review_id, args).await + finish( + api, + requested.review_id, + OnInterrupt::for_stoppable_request(requested.existing), + args, + ) + .await } async fn review_files(api: &Api, args: &ReviewArgs) -> anyhow::Result { @@ -1057,7 +1065,13 @@ async fn review_files(api: &Api, args: &ReviewArgs) -> anyhow::Result { request.paths.len(), request.commit_sha )); - finish(api, requested.review_id, args).await + finish( + api, + requested.review_id, + OnInterrupt::for_stoppable_request(requested.existing), + args, + ) + .await } /// Reviews pushed commits: one commit against its parent, or a range. The @@ -1086,11 +1100,22 @@ async fn review_pushed(api: &Api, args: &ReviewArgs) -> anyhow::Result request.base_commit_sha, request.head_commit_sha )); - finish(api, requested.review_id, args).await + finish( + api, + requested.review_id, + OnInterrupt::for_stoppable_request(requested.existing), + args, + ) + .await } /// Prints the requested review's link, or waits for it and prints its result. -async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> anyhow::Result { +async fn finish( + api: &Api, + review_id: Uuid, + on_interrupt: OnInterrupt, + args: &ReviewArgs, +) -> anyhow::Result { if args.no_wait { let mut stdout = std::io::stdout().lock(); let url = api.review_url(review_id); @@ -1112,6 +1137,7 @@ async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> anyhow::Result &args.output, OutputFormat::from_json(args.output.json), args.fail_on, + on_interrupt, ) .await } @@ -1148,7 +1174,16 @@ async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { } else { OutputFormat::from_json(args.output.json) }; - show(api, review_id, args.wait, &args.output, format, None).await + show( + api, + review_id, + args.wait, + &args.output, + format, + None, + OnInterrupt::Detach, + ) + .await } #[derive(Debug, thiserror::Error)] @@ -1166,41 +1201,188 @@ fn poll_deadline(minutes: u64) -> Result Self { + if existing { Self::Detach } else { Self::Stop } + } +} + +/// One review snapshot returned by [`read_review`]. +pub(crate) struct ReadReview { + pub(crate) raw: serde_json::Value, + pub(crate) detail: ReviewDetail, + pub(crate) state: Option, +} + +/// Outcome of polling a review until it finishes, times out, or is interrupted. +pub(crate) enum WaitResult { + Ready(Box), + Interrupted, +} + +/// Resolves when `Ctrl-C` arrives. If the platform signal handler cannot be +/// registered, stays pending rather than falsely cancelling a running review. +async fn wait_ctrl_c() { + if tokio::signal::ctrl_c().await.is_err() { + std::future::pending::<()>().await; + } +} + +/// Reads the review, polling until it finishes, `deadline` passes, or `Ctrl-C` +/// interrupts the wait. Without a deadline it reads once. Every read confirms +/// the server's answer is of the review requested, not a cache or routing +/// mix-up that would otherwise let a result for a different review decide this +/// one's outcome. +pub(crate) async fn read_review( + api: &Api, + review_id: Uuid, + deadline: Option, + sarif: bool, + on_interrupt: OnInterrupt, +) -> anyhow::Result { + if deadline.is_none() { + return read_review_until( + api, + review_id, + None, + sarif, + on_interrupt, + std::future::pending(), + std::future::pending(), + ) + .await; + } + read_review_until( + api, + review_id, + deadline, + sarif, + on_interrupt, + wait_ctrl_c(), + wait_ctrl_c(), + ) + .await +} + +async fn read_review_until( api: &Api, review_id: Uuid, deadline: Option, sarif: bool, -) -> anyhow::Result<(serde_json::Value, ReviewDetail, Option)> { + on_interrupt: OnInterrupt, + first_interrupt: F1, + second_interrupt: F2, +) -> anyhow::Result +where + F1: Future, + F2: Future, +{ + let mut interrupt = std::pin::pin!(first_interrupt); let mut delay = FIRST_POLL_SECONDS; loop { - let (raw, detail) = api.review(review_id).await?; + let (raw, detail) = tokio::select! { + biased; + () = &mut interrupt => { + handle_interrupt(api, review_id, on_interrupt, second_interrupt).await; + return Ok(WaitResult::Interrupted); + } + polled = api.review(review_id) => polled?, + }; outcome::same_review(&detail, review_id)?; if sarif { sarif::validate_subject(&detail, review_id)?; } let state = outcome::terminal(&detail); let Some(deadline) = deadline else { - return Ok((raw, detail, state)); + return Ok(WaitResult::Ready(Box::new(ReadReview { + raw, + detail, + state, + }))); }; let now = tokio::time::Instant::now(); if state.is_some() || now >= deadline { - return Ok((raw, detail, state)); + return Ok(WaitResult::Ready(Box::new(ReadReview { + raw, + detail, + state, + }))); } say(&format!( "Review is {}; checking again in {delay} seconds.", text::one_line(&detail.status) )); let pause = Duration::from_secs(delay).min(deadline.saturating_duration_since(now)); - tokio::time::sleep(pause).await; + tokio::select! { + biased; + () = &mut interrupt => { + handle_interrupt(api, review_id, on_interrupt, second_interrupt).await; + return Ok(WaitResult::Interrupted); + } + () = tokio::time::sleep(pause) => {} + } delay = (delay * 2).min(LONGEST_POLL_SECONDS); } } +async fn handle_interrupt( + api: &Api, + review_id: Uuid, + on_interrupt: OnInterrupt, + second_interrupt: F, +) where + F: Future, +{ + let url = api.review_url(review_id); + match on_interrupt { + OnInterrupt::Detach => { + say(&format!( + "Interrupted; review {review_id} continues at {url}. Run `proofline findings --review {review_id} --wait` to check it later." + )); + } + OnInterrupt::Stop => { + say(&format!("Interrupted; stopping review {review_id}...")); + let stop = tokio::time::timeout(STOP_ON_INTERRUPT_TIMEOUT, api.stop_review(review_id)); + tokio::select! { + biased; + () = second_interrupt => { + say(&format!( + "Aborted before stop completed. Run `proofline stop {review_id}` to stop it, or open {url}" + )); + } + result = stop => match result { + Ok(Ok(_)) => { + say(&format!("Stopped review {review_id} ({url}).")); + } + Ok(Err(error)) => { + say(&format!( + "Could not stop review {review_id}: {error}. Run `proofline stop {review_id}` to retry, or open {url}" + )); + } + Err(_) => { + say(&format!( + "Timed out stopping review {review_id}. Run `proofline stop {review_id}` to retry, or open {url}" + )); + } + } + } + } + } +} + /// Prints the review, after waiting for it to finish when `wait` is set. async fn show( api: &Api, @@ -1209,6 +1391,7 @@ async fn show( output: &OutputArgs, format: OutputFormat, fail_on: Option, + on_interrupt: OnInterrupt, ) -> anyhow::Result { let deadline = if wait { Some(poll_deadline(output.timeout)?) @@ -1216,7 +1399,12 @@ async fn show( None }; let sarif = matches!(format, OutputFormat::Sarif); - let (raw, detail, state) = read_review(api, review_id, deadline, sarif).await?; + let WaitResult::Ready(read) = + read_review(api, review_id, deadline, sarif, on_interrupt).await? + else { + return Ok(Verdict::Interrupted); + }; + let ReadReview { raw, detail, state } = *read; // `audit_mode` marks an audit, as on a listed review (`ReviewSummary`). if raw.get("audit_mode").is_some_and(|mode| !mode.is_null()) { print_audit(api, raw, &detail, format)?; @@ -1233,7 +1421,11 @@ async fn show( Verdict::Unavailable => say( "Proofline returned the completed review without `open_items`, so --fail-on could not be measured. It is not a pass.", ), - Verdict::Done | Verdict::NotComplete | Verdict::Blocked | Verdict::Regressed => {} + Verdict::Done + | Verdict::NotComplete + | Verdict::Blocked + | Verdict::Regressed + | Verdict::Interrupted => {} } return Ok(verdict); } @@ -1401,8 +1593,18 @@ async fn ci_review( return Ok(Verdict::Unavailable); }; let sarif_path = args.sarif.as_deref(); - let (raw, detail, state) = - read_review(api, review_id, Some(deadline), sarif_path.is_some()).await?; + let WaitResult::Ready(read) = read_review( + api, + review_id, + Some(deadline), + sarif_path.is_some(), + OnInterrupt::Detach, + ) + .await? + else { + return Ok(Verdict::Interrupted); + }; + let ReadReview { raw, detail, state } = *read; confirm_ci_subject(&detail, commit, repository_id)?; if let Some(path) = sarif_path { write_sarif(api, review_id, &detail, path).await?; @@ -1548,7 +1750,11 @@ fn say_ci_ending( Verdict::Unavailable => say( "Proofline returned the completed review without `open_items`, so --fail-on could not be measured. It is not a pass.", ), - Verdict::Done | Verdict::NotComplete | Verdict::Blocked | Verdict::Regressed => {} + Verdict::Done + | Verdict::NotComplete + | Verdict::Blocked + | Verdict::Regressed + | Verdict::Interrupted => {} }, Some(ended) => say_not_complete(ended), } @@ -2237,4 +2443,231 @@ mod tests { Verdict::NotComplete ); } + fn running_review_json(review_id: Uuid) -> serde_json::Value { + json!({ + "id": review_id, + "kind": "PATCH", + "status": "RUNNING", + "assessment_count": 0, + "assessments": [], + "code_assessment": null, + "base_commit_sha": "b".repeat(40), + "head_commit_sha": "c".repeat(40), + "open_items": null, + "pull_request_number": null, + "repository_full_name": "acme/web", + "run_number": null, + }) + } + + async fn spawn_interrupt_server( + org_id: Uuid, + review_id: Uuid, + stop_status: axum::http::StatusCode, + hang_stop: bool, + ) -> ( + Api, + tokio::sync::oneshot::Receiver<()>, + tokio::sync::oneshot::Receiver<()>, + Arc, + tokio::task::JoinHandle<()>, + ) { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use axum::extract::Path as AxumPath; + use axum::http::StatusCode; + + let (polled_tx, polled_rx) = tokio::sync::oneshot::channel(); + let polled_tx = Arc::new(Mutex::new(Some(polled_tx))); + let (stop_started_tx, stop_started_rx) = tokio::sync::oneshot::channel(); + let stop_started_tx = Arc::new(Mutex::new(Some(stop_started_tx))); + let stops = Arc::new(AtomicUsize::new(0)); + let stop_count = Arc::clone(&stops); + + let app = Router::new() + .route( + &format!("/api/v1/organizations/{org_id}/reviews/{{id}}"), + get(move |AxumPath(id): AxumPath| { + let polled_tx = Arc::clone(&polled_tx); + async move { + let tx = polled_tx.lock().unwrap().take(); + if let Some(tx) = tx { + let _ = tx.send(()); + } + (StatusCode::OK, Json(running_review_json(id))) + } + }), + ) + .route( + &format!("/api/v1/organizations/{org_id}/reviews/{{id}}/stop"), + post(move |AxumPath(id): AxumPath| { + let stop_count = Arc::clone(&stop_count); + let stop_started_tx = Arc::clone(&stop_started_tx); + async move { + assert_eq!(id, review_id); + stop_count.fetch_add(1, Ordering::SeqCst); + let tx = stop_started_tx.lock().unwrap().take(); + if let Some(tx) = tx { + let _ = tx.send(()); + } + if hang_stop { + std::future::pending::<()>().await; + } + if stop_status.is_success() { + ( + stop_status, + Json(json!({ + "review_id": id, + "status": "STOPPED", + "stopped_by": {"github_user_id": 123, "login": "reviewer"}, + "stopped_at": "2026-01-01T00:00:00Z", + })), + ) + } else { + ( + stop_status, + Json(json!({ + "title": "Review already settled", + "status": stop_status.as_u16(), + "detail": "This review can no longer be stopped.", + })), + ) + } + } + }), + ); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let http = Http::new(Origin::parse(&origin).unwrap()).unwrap(); + let api = Api::new(http, SecretString::from("test-token".to_owned()), org_id); + (api, polled_rx, stop_started_rx, stops, server) + } + + #[tokio::test] + async fn interrupt_with_stop_sends_one_stop_request_and_returns_interrupted() { + use std::sync::atomic::Ordering; + + let org_id = Uuid::parse_str(ORG).unwrap(); + let review_id = Uuid::parse_str(REQUESTED).unwrap(); + let (api, polled_rx, _, stops, server) = + spawn_interrupt_server(org_id, review_id, axum::http::StatusCode::OK, false).await; + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + + let result = read_review_until( + &api, + review_id, + Some(deadline), + false, + OnInterrupt::Stop, + async { + let _ = polled_rx.await; + }, + std::future::pending(), + ) + .await + .unwrap(); + + server.abort(); + assert!(matches!(result, WaitResult::Interrupted)); + assert_eq!(stops.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn interrupt_with_detach_never_calls_stop() { + use std::sync::atomic::Ordering; + + let org_id = Uuid::parse_str(ORG).unwrap(); + let review_id = Uuid::parse_str(REQUESTED).unwrap(); + let (api, polled_rx, _, stops, server) = + spawn_interrupt_server(org_id, review_id, axum::http::StatusCode::OK, false).await; + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + + let result = read_review_until( + &api, + review_id, + Some(deadline), + false, + OnInterrupt::Detach, + async { + let _ = polled_rx.await; + }, + std::future::pending(), + ) + .await + .unwrap(); + + server.abort(); + assert!(matches!(result, WaitResult::Interrupted)); + assert_eq!(stops.load(Ordering::SeqCst), 0); + } + + #[tokio::test] + async fn interrupt_with_stop_refusal_does_not_retry_and_returns_interrupted() { + use std::sync::atomic::Ordering; + + let org_id = Uuid::parse_str(ORG).unwrap(); + let review_id = Uuid::parse_str(REQUESTED).unwrap(); + let (api, polled_rx, _, stops, server) = + spawn_interrupt_server(org_id, review_id, axum::http::StatusCode::CONFLICT, false) + .await; + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + + let result = read_review_until( + &api, + review_id, + Some(deadline), + false, + OnInterrupt::Stop, + async { + let _ = polled_rx.await; + }, + std::future::pending(), + ) + .await + .unwrap(); + + server.abort(); + assert!(matches!(result, WaitResult::Interrupted)); + assert_eq!(stops.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn second_interrupt_aborts_hung_stop_immediately() { + use std::sync::atomic::Ordering; + + let org_id = Uuid::parse_str(ORG).unwrap(); + let review_id = Uuid::parse_str(REQUESTED).unwrap(); + let (api, polled_rx, stop_started_rx, stops, server) = + spawn_interrupt_server(org_id, review_id, axum::http::StatusCode::OK, true).await; + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + + let result = tokio::time::timeout( + Duration::from_secs(2), + read_review_until( + &api, + review_id, + Some(deadline), + false, + OnInterrupt::Stop, + async { + let _ = polled_rx.await; + }, + async { + let _ = stop_started_rx.await; + }, + ), + ) + .await + .expect("second interrupt should abort before STOP_ON_INTERRUPT_TIMEOUT") + .unwrap(); + + server.abort(); + assert!(matches!(result, WaitResult::Interrupted)); + assert_eq!(stops.load(Ordering::SeqCst), 1); + } } diff --git a/src/main.rs b/src/main.rs index 04ae422..05e0a68 100644 --- a/src/main.rs +++ b/src/main.rs @@ -55,6 +55,7 @@ fn main() -> ExitCode { // recorded a regression. Ok(Verdict::ThresholdReached | Verdict::Regressed) => ExitCode::from(3), Ok(Verdict::Blocked) => ExitCode::FAILURE, + Ok(Verdict::Interrupted) => ExitCode::from(130), Err(error) => { eprintln!("proofline: {error:#}"); ExitCode::FAILURE diff --git a/src/scan.rs b/src/scan.rs index 330ecfc..c57bf23 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -11,7 +11,9 @@ use uuid::Uuid; use crate::api::{Api, ApiError}; use crate::model::{ScanRequest, ScanResponse}; -use crate::{OutputArgs, OutputFormat, RepositoryArgs, Verdict, git, say, show, text, tools}; +use crate::{ + OnInterrupt, OutputArgs, OutputFormat, RepositoryArgs, Verdict, git, say, show, text, tools, +}; #[derive(Debug, Args)] pub(crate) struct ScanArgs { @@ -131,6 +133,7 @@ pub(crate) async fn run( &args.output, OutputFormat::from_json(args.output.json), None, + OnInterrupt::Detach, ) .await { diff --git a/src/tools.rs b/src/tools.rs index cc68bb4..7fbf4c5 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -5,7 +5,7 @@ use anyhow::{Context as _, bail}; use clap::{Args, Subcommand, ValueEnum}; use uuid::Uuid; -use crate::{OutputArgs, OutputFormat, RepositoryArgs, Verdict, api::Api, say, show}; +use crate::{OnInterrupt, OutputArgs, OutputFormat, RepositoryArgs, Verdict, api::Api, say, show}; #[derive(Debug, Args)] pub(crate) struct RerunArgs { @@ -113,6 +113,7 @@ pub(crate) async fn rerun(api: &Api, args: &RerunArgs) -> anyhow::Result Self { + let checkout = Self { + temporary: tempfile::tempdir().unwrap(), + }; + tokio::fs::create_dir_all(checkout.root()).await.unwrap(); + tokio::fs::write(checkout.config(), "").await.unwrap(); + checkout.git(&["init", "-q", "-b", "main"]).await; + checkout + .git(&["config", "user.name", "Interrupt Test"]) + .await; + checkout + .git(&["config", "user.email", "interrupt@example.test"]) + .await; + checkout + .git(&["remote", "add", "origin", "https://github.com/acme/web.git"]) + .await; + tokio::fs::write(checkout.root().join("hello.txt"), "one\n") + .await + .unwrap(); + checkout.git(&["add", "--all"]).await; + checkout.git(&["commit", "-qm", "base"]).await; + let base = String::from_utf8(checkout.git(&["rev-parse", "HEAD"]).await) + .unwrap() + .trim() + .to_owned(); + checkout + .git(&["update-ref", "refs/remotes/origin/main", &base]) + .await; + checkout + .git(&[ + "symbolic-ref", + "refs/remotes/origin/HEAD", + "refs/remotes/origin/main", + ]) + .await; + tokio::fs::write(checkout.root().join("hello.txt"), "one\ntwo\n") + .await + .unwrap(); + checkout + } + + fn root(&self) -> PathBuf { + self.temporary.path().join("repo") + } + + fn config(&self) -> PathBuf { + self.temporary.path().join("gitconfig") + } + + fn home(&self) -> PathBuf { + self.temporary.path().join("home") + } + + async fn git(&self, args: &[&str]) -> Vec { + let output = Command::new("git") + .current_dir(self.root()) + .args(args) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", self.config()) + .output() + .await + .unwrap(); + assert!( + output.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + output.stdout + } +} + +async fn run_local_review_and_interrupt(existing: bool) -> (std::process::Output, usize) { + let polled = Arc::new(AtomicBool::new(false)); + let stops = Arc::new(AtomicUsize::new(0)); + let observed_poll = Arc::clone(&polled); + let observed_stop = Arc::clone(&stops); + + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/repository-names"), + get(|headers: HeaderMap| async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + Json(json!({ + "repositories": [{ "id": REPOSITORY, "full_name": "acme/web" }], + })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/patch-reviews"), + post( + move |headers: HeaderMap, Json(_body): Json| async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + Json(json!({ + "review_id": REVIEW, + "existing": existing, + "patch_digest": "a".repeat(64), + "verify": [], + })) + }, + ), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{REVIEW}"), + get(move |headers: HeaderMap| { + let observed_poll = Arc::clone(&observed_poll); + async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + observed_poll.store(true, Ordering::SeqCst); + Json(json!({ + "id": REVIEW, + "kind": "PATCH", + "status": "RUNNING", + "assessment_count": 0, + "assessments": [], + "code_assessment": null, + "base_commit_sha": "b".repeat(40), + "head_commit_sha": "c".repeat(40), + "open_items": null, + "pull_request_number": null, + "repository_full_name": "acme/web", + "run_number": null, + })) + } + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{{id}}/stop"), + post(move |AxumPath(id): AxumPath, headers: HeaderMap| { + let observed_stop = Arc::clone(&observed_stop); + async move { + assert_eq!(id.to_string(), REVIEW); + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + observed_stop.fetch_add(1, Ordering::SeqCst); + ( + StatusCode::OK, + Json(json!({ + "review_id": id, + "status": "STOPPED", + "stopped_by": {"github_user_id": 123, "login": "reviewer"}, + "stopped_at": "2026-01-01T00:00:00Z", + })), + ) + } + }), + ); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let checkout = MockCheckout::new().await; + tokio::fs::create_dir_all(checkout.home()).await.unwrap(); + + let child = Command::new(env!("CARGO_BIN_EXE_proofline")) + .current_dir(checkout.root()) + .args(["--base-url", &origin, "--org", ORG, "review", "--json"]) + .env("HOME", checkout.home()) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", checkout.config()) + .env("PROOFLINE_TOKEN", TOKEN) + .env_remove("PROOFLINE_BASE_URL") + .env_remove("PROOFLINE_ORGANIZATION_ID") + .env_remove("PROOFLINE_CA_CERT") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + + let pid = child.id().expect("child should have a pid"); + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while !polled.load(Ordering::SeqCst) { + assert!( + tokio::time::Instant::now() < deadline, + "timed out waiting for first review poll" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } + + let kill_status = std::process::Command::new("kill") + .args(["-INT", &pid.to_string()]) + .status() + .unwrap(); + assert!(kill_status.success()); + + let output = tokio::time::timeout(Duration::from_secs(10), child.wait_with_output()) + .await + .expect("proofline did not exit promptly after SIGINT") + .unwrap(); + + server.abort(); + (output, stops.load(Ordering::SeqCst)) +} + +#[tokio::test] +async fn sigint_stops_newly_requested_local_review_and_exits_130() { + let (output, stops) = run_local_review_and_interrupt(false).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(130), "stderr: {stderr}"); + assert!( + output.stdout.is_empty(), + "stdout must stay empty under --json on interrupt: {}", + String::from_utf8_lossy(&output.stdout) + ); + assert_eq!(stops, 1, "stderr: {stderr}"); + assert!(stderr.contains("Stopped review"), "stderr: {stderr}"); +} + +#[tokio::test] +async fn sigint_detaches_reused_local_review_without_stopping_and_exits_130() { + let (output, stops) = run_local_review_and_interrupt(true).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(130), "stderr: {stderr}"); + assert!( + output.stdout.is_empty(), + "stdout must stay empty under --json on interrupt: {}", + String::from_utf8_lossy(&output.stdout) + ); + assert_eq!(stops, 0, "stderr: {stderr}"); + assert!(stderr.contains("continues at"), "stderr: {stderr}"); + assert!( + stderr.contains(&format!("proofline findings --review {REVIEW} --wait")), + "stderr: {stderr}" + ); +}