diff --git a/Cargo.lock b/Cargo.lock index 8ce9496..3ebda92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1786,6 +1786,7 @@ dependencies = [ "axum", "clap", "flate2", + "httpdate", "jsonschema", "keyring", "reqwest", diff --git a/Cargo.toml b/Cargo.toml index fc76317..c63072a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ path = "src/main.rs" anyhow = "1" clap = { version = "4", features = ["derive", "env"] } flate2 = "1" +httpdate = "1.0" sha2 = "0.10" tar = "0.4" keyring = { version = "3", default-features = false, features = ["apple-native", "windows-native", "sync-secret-service", "crypto-rust", "vendored"] } @@ -29,7 +30,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"] } +tokio = { version = "1", features = ["rt", "macros", "time", "process", "io-std", "io-util", "fs", "signal"] } toml_edit = "=0.25.15" url = "2" uuid = { version = "1", features = ["serde"] } diff --git a/src/api.rs b/src/api.rs index f908670..3e5ed46 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,7 +1,7 @@ //! The review API over HTTP: bearer authentication, bounded bodies, explicit //! timeouts, no redirects, and bounded retries for reads. -use std::time::Duration; +use std::time::{Duration, SystemTime}; use reqwest::{Method, StatusCode, header}; use secrecy::{ExposeSecret as _, SecretString}; @@ -106,6 +106,22 @@ fn json_content_type(headers: &header::HeaderMap) -> bool { }) } +/// Parses an RFC 7231 `Retry-After` header value, supporting both `delay-seconds` +/// (an integer number of seconds) and `HTTP-date` (an absolute timestamp). +pub(crate) fn parse_retry_after(value: &header::HeaderValue) -> Option { + let text = value.to_str().ok()?.trim(); + if let Ok(seconds) = text.parse::() { + return Some(seconds); + } + if let Ok(system_time) = httpdate::parse_http_date(text) { + let wait = system_time + .duration_since(SystemTime::now()) + .map_or(0, |duration| duration.as_secs()); + return Some(wait); + } + None +} + impl ApiError { pub const fn status(&self) -> Option { match self { @@ -192,12 +208,10 @@ impl Http { .map_err(|error| self.transport(&error))?; let status = response.status(); let headers = response.headers().clone(); - let retry_after = response.headers().get(header::RETRY_AFTER).map(|value| { - value - .to_str() - .ok() - .and_then(|text| text.trim().parse::().ok()) - }); + let retry_after = response + .headers() + .get(header::RETRY_AFTER) + .map(parse_retry_after); let body = read_body(response).await.map_err(|error| match error { BodyError::Transport(error) => self.transport(&error), BodyError::TooLarge => self.protocol("the response body exceeds 8 MiB"), @@ -669,3 +683,41 @@ impl Api { .join(["orgs", "by-id", &organization, "reviews", &review]) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_retry_after_integer_seconds() { + let value = header::HeaderValue::from_static("30"); + assert_eq!(parse_retry_after(&value), Some(30)); + + let value_spaces = header::HeaderValue::from_static(" 120 \t"); + assert_eq!(parse_retry_after(&value_spaces), Some(120)); + } + + #[test] + fn parse_retry_after_http_date() { + let now = SystemTime::now(); + let future = now + Duration::from_secs(45); + let date_str = httpdate::fmt_http_date(future); + let value = header::HeaderValue::from_str(&date_str).unwrap(); + let wait = parse_retry_after(&value).unwrap(); + assert!((43..=45).contains(&wait), "expected ~45s, got {wait}s"); + + let past = now - Duration::from_secs(60); + let past_str = httpdate::fmt_http_date(past); + let past_value = header::HeaderValue::from_str(&past_str).unwrap(); + assert_eq!(parse_retry_after(&past_value), Some(0)); + } + + #[test] + fn parse_retry_after_invalid_or_malformed() { + let invalid = header::HeaderValue::from_static("not-a-date-or-number"); + assert_eq!(parse_retry_after(&invalid), None); + + let empty = header::HeaderValue::from_static(""); + assert_eq!(parse_retry_after(&empty), None); + } +} diff --git a/src/lib.rs b/src/lib.rs index 6096711..07a116d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,6 +21,7 @@ mod sarif; mod severity; pub mod text; pub mod update; +pub mod watch; use std::io::Write as _; use std::path::PathBuf; @@ -130,6 +131,8 @@ enum Command { /// Review the checkout's local changes, pushed commits, or an open pull /// request's current head. Review(ReviewArgs), + /// Continuously watch the checkout's uncommitted changes and review incrementally. + Watch(watch::WatchArgs), /// Stop your own pending or running local patch, pushed-commit or named-file review. Stop(StopArgs), /// Show the findings of the latest review of a commit or pull request. @@ -196,24 +199,24 @@ struct LoginArgs { no_browser: bool, } -#[derive(Debug, Args)] -struct RepositoryArgs { +#[derive(Debug, Clone, Args)] +pub(crate) struct RepositoryArgs { /// GitHub repository as owner/name. Defaults to the checkout's remote. #[arg(long, value_name = "OWNER/NAME")] - repo: Option, + pub(crate) repo: Option, /// Git remote that names the repository. #[arg(long, default_value = "origin")] - remote: String, + pub(crate) remote: String, } -#[derive(Debug, Args)] -struct OutputArgs { +#[derive(Debug, Clone, Args)] +pub(crate) struct OutputArgs { /// Print JSON instead of text. #[arg(long)] - json: bool, + pub(crate) json: bool, /// Minutes to wait for a running review. #[arg(long, default_value_t = 20, value_name = "MINUTES")] - timeout: u64, + pub(crate) timeout: u64, } #[derive(Debug, Args)] @@ -225,14 +228,14 @@ struct StopArgs { json: bool, } -#[derive(Debug, Args)] -struct LocalSelectionArgs { +#[derive(Debug, Clone, Args)] +pub(crate) struct LocalSelectionArgs { /// Review the original index against the base, excluding unstaged changes. #[arg(long, conflicts_with_all = ["pr", "include_untracked"])] - staged: bool, + pub(crate) staged: bool, /// Add untracked files that Git does not ignore to the working-tree review. #[arg(long, conflicts_with_all = ["pr", "staged"])] - include_untracked: bool, + pub(crate) include_untracked: bool, } #[derive(Debug, Args)] @@ -329,14 +332,14 @@ struct FindingsArgs { } #[derive(Debug, Clone, Copy)] -enum OutputFormat { +pub(crate) enum OutputFormat { Text, Json, Sarif, } impl OutputFormat { - const fn from_json(json: bool) -> Self { + pub(crate) const fn from_json(json: bool) -> Self { if json { Self::Json } else { Self::Text } } } @@ -465,6 +468,10 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + let api = connect(Http::new(origin)?, token, cli.org).await?; + watch::run(&api, &args).await + } Command::Stop(args) => { let api = connect(Http::new(origin)?, token, cli.org).await?; let (raw, stopped) = api.stop_review(args.review_id).await?; @@ -545,7 +552,7 @@ async fn connect( Ok(Api::new(http, credential.token, credential.organization_id)) } -fn say(line: &str) { +pub(crate) fn say(line: &str) { // Progress goes to standard error so standard output stays the result. let mut stderr = std::io::stderr().lock(); if writeln!(stderr, "{line}").is_err() { @@ -691,7 +698,10 @@ fn unique( } /// A connected repository, for requesting a review: it need not have one yet. -async fn connected_repository(api: &Api, args: &RepositoryArgs) -> anyhow::Result<(String, Uuid)> { +pub(crate) async fn connected_repository( + api: &Api, + args: &RepositoryArgs, +) -> anyhow::Result<(String, Uuid)> { let name = repository_name(args).await?; let names = api.repository_names().await?; let candidates = names @@ -1009,7 +1019,7 @@ async fn read_review( } /// Prints the review, after waiting for it to finish when `wait` is set. -async fn show( +pub(crate) async fn show( api: &Api, review_id: Uuid, wait: bool, diff --git a/src/watch.rs b/src/watch.rs new file mode 100644 index 0000000..4791494 --- /dev/null +++ b/src/watch.rs @@ -0,0 +1,289 @@ +//! Continuous local review daemon. +//! +//! Watches the checkout's uncommitted changes against its merge base, +//! debounces rapid filesystem modifications, dedupes identical diffs, +//! and automatically requests and displays incremental reviews. + +use std::path::Path; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use clap::Args; +use sha2::{Digest, Sha256}; +use tokio::time::sleep; + +use crate::api::Api; +use crate::git::{self, LocalSelection}; +use crate::model::PatchReviewRequest; +use crate::preflight; +use crate::{OutputArgs, OutputFormat, RepositoryArgs, Verdict, connected_repository, say, show}; + +#[derive(Debug, Clone, Args)] +pub struct WatchSelectionArgs { + /// Review the original index against the base, excluding unstaged changes. + #[arg(long, conflicts_with = "include_untracked")] + pub staged: bool, + + /// Add untracked files that Git does not ignore to the working-tree review. + #[arg(long, conflicts_with = "staged")] + pub include_untracked: bool, +} + +#[derive(Debug, Clone, Args)] +pub struct WatchArgs { + /// Debounce duration in milliseconds after the last detected change before reviewing. + #[arg(long, value_name = "MILLIS", default_value = "500")] + pub debounce: u64, + + /// Polling interval in milliseconds to check for working-tree changes. + #[arg(long, value_name = "MILLIS", default_value = "1000")] + pub interval: u64, + + /// Review only this literal repository-relative file in the local patch. + #[arg(long, value_name = "PATH")] + pub path: Option, + + /// Include secret-shaped patch content from this exact repository-relative path. + #[arg(long, value_name = "PATH")] + pub allow_path: Vec, + + #[command(flatten)] + pub(crate) local_selection: WatchSelectionArgs, + + #[command(flatten)] + pub(crate) repository: RepositoryArgs, + + #[command(flatten)] + pub(crate) output: OutputArgs, +} + +/// Computes the SHA-256 digest of patch bytes for deduplication. +pub(crate) fn compute_patch_fingerprint(patch_bytes: &[u8]) -> [u8; 32] { + let mut hasher = Sha256::new(); + hasher.update(patch_bytes); + hasher.finalize().into() +} + +/// The state of the watcher across polling intervals. +#[derive(Debug, Default)] +pub(crate) struct WatchState { + pub(crate) last_reviewed_hash: Option<[u8; 32]>, + pub(crate) pending_hash: Option<[u8; 32]>, + pub(crate) pending_change_time: Option, +} + +impl WatchState { + pub(crate) fn new() -> Self { + Self::default() + } + + /// Evaluates whether a new patch hash should trigger a review given the debounce duration. + /// Returns true if the change has settled and is ready for review. + pub(crate) fn evaluate_change( + &mut self, + current_hash: [u8; 32], + debounce_dur: Duration, + now: Instant, + ) -> bool { + // If identical to the last successfully reviewed patch, ignore. + if self.last_reviewed_hash == Some(current_hash) { + self.pending_hash = None; + self.pending_change_time = None; + return false; + } + + // If this hash is different from the currently pending one, reset debounce clock. + if self.pending_hash != Some(current_hash) { + self.pending_hash = Some(current_hash); + self.pending_change_time = Some(now); + return false; + } + + // If debounce time has elapsed, trigger review. + if let Some(change_time) = self.pending_change_time + && now.saturating_duration_since(change_time) >= debounce_dur + { + self.last_reviewed_hash = Some(current_hash); + self.pending_hash = None; + self.pending_change_time = None; + return true; + } + + false + } + + pub(crate) fn reset_clean(&mut self) { + self.last_reviewed_hash = None; + self.pending_hash = None; + self.pending_change_time = None; + } +} + +/// Runs the continuous review daemon. +pub async fn run(api: &Api, args: &WatchArgs) -> Result { + let selection = if args.local_selection.staged { + LocalSelection::Staged + } else if args.local_selection.include_untracked { + LocalSelection::IncludeUntracked + } else { + LocalSelection::Tracked + }; + + say("Proofline watch mode active. Watching for local changes... (Press Ctrl+C to stop)"); + + let debounce_dur = Duration::from_millis(args.debounce); + let interval_dur = Duration::from_millis(args.interval); + let mut state = WatchState::new(); + + loop { + tokio::select! { + _ = tokio::signal::ctrl_c() => { + say("\nStopping Proofline watch mode."); + return Ok(Verdict::Done); + } + () = sleep(interval_dur) => { + let changes = match git::local_changes( + Path::new("."), + &args.repository.remote, + selection, + args.path.as_deref(), + ).await { + Ok(changes) => changes, + Err(error) => { + say(&format!("warning: could not inspect git status: {error}")); + continue; + } + }; + + let files = changes.files(); + if files == 0 { + state.reset_clean(); + continue; + } + + let current_hash = compute_patch_fingerprint(changes.patch.as_bytes()); + let now = Instant::now(); + + if !state.evaluate_change(current_hash, debounce_dur, now) { + continue; + } + + if let Err(error) = preflight::check(&changes, &args.allow_path) { + say(&format!("Preflight check refused patch: {error}. Waiting for fixes...")); + continue; + } + + let (repo_name, repo_id) = match connected_repository(api, &args.repository).await { + Ok(result) => result, + Err(error) => { + say(&format!("Could not connect repository: {error}")); + continue; + } + }; + + say(&format!( + "\nChanges detected: reviewing {files} changed {} in {repo_name}...", + if files == 1 { "file" } else { "files" } + )); + + let request = PatchReviewRequest { + base_commit_sha: changes.base_commit_sha, + patch: changes.patch, + trigger_source: None, + verify_finding_ids: Vec::new(), + }; + + let requested = match api.request_patch_review(repo_id, &request).await { + Ok(requested) => requested, + Err(error) => { + say(&format!("Failed to request review: {error}")); + continue; + } + }; + + say(&format!( + "{} review of uncommitted changes on {}.", + if requested.existing { "Found existing" } else { "Requested" }, + request.base_commit_sha + )); + + let _ = show( + api, + requested.review_id, + true, + &args.output, + OutputFormat::from_json(args.output.json), + ).await; + + say("\nWatching for local changes... (Press Ctrl+C to stop)"); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn patch_fingerprint_is_deterministic() { + let diff_a = b"diff --git a/foo.rs b/foo.rs\n+println!(\"hello\");"; + let diff_b = b"diff --git a/foo.rs b/foo.rs\n+println!(\"hello\");"; + let diff_c = b"diff --git a/foo.rs b/foo.rs\n+println!(\"world\");"; + + let hash_a = compute_patch_fingerprint(diff_a); + let hash_b = compute_patch_fingerprint(diff_b); + let hash_c = compute_patch_fingerprint(diff_c); + + assert_eq!(hash_a, hash_b); + assert_ne!(hash_a, hash_c); + } + + #[test] + fn state_evaluates_debounce_and_deduplication() { + let mut state = WatchState::new(); + let hash1 = [1u8; 32]; + let hash2 = [2u8; 32]; + let debounce = Duration::from_millis(500); + let start = Instant::now(); + + // Initial change observed at start: should not trigger immediately + assert!(!state.evaluate_change(hash1, debounce, start)); + + // 200ms later with same hash: still in debounce window + let t1 = start + Duration::from_millis(200); + assert!(!state.evaluate_change(hash1, debounce, t1)); + + // 600ms later with same hash: debounce expired, should trigger review! + let t2 = start + Duration::from_millis(600); + assert!(state.evaluate_change(hash1, debounce, t2)); + + // Subsequent poll with identical hash: already reviewed, should NOT trigger + let t3 = start + Duration::from_millis(1000); + assert!(!state.evaluate_change(hash1, debounce, t3)); + + // New change arrives: resets debounce, does not trigger immediately + let t4 = start + Duration::from_millis(1500); + assert!(!state.evaluate_change(hash2, debounce, t4)); + + // 600ms after new change: triggers review for new change! + let t5 = t4 + Duration::from_millis(600); + assert!(state.evaluate_change(hash2, debounce, t5)); + } + + #[test] + fn reset_clean_clears_state() { + let mut state = WatchState::new(); + let hash = [1u8; 32]; + let debounce = Duration::from_millis(100); + let t0 = Instant::now(); + assert!(!state.evaluate_change(hash, debounce, t0)); + assert!(state.evaluate_change(hash, debounce, t0 + Duration::from_millis(200))); + + // After clean reset (e.g. user committed changes), state is cleared + state.reset_clean(); + assert_eq!(state.last_reviewed_hash, None); + assert_eq!(state.pending_hash, None); + assert_eq!(state.pending_change_time, None); + } +} diff --git a/tests/http.rs b/tests/http.rs index b65ed37..1bf6dac 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -2188,3 +2188,65 @@ async fn fix_commands_preserve_context_and_never_retry_verification() { assert_eq!(calls.lock().unwrap().len(), 4); server.abort(); } + +#[tokio::test] +async fn read_retries_on_rate_limit_with_rfc7231_http_date_retry_after() { + let attempts = Arc::new(AtomicUsize::new(0)); + let attempts_clone = Arc::clone(&attempts); + let app = Router::new().route( + &format!("/api/v1/organizations/{ORG}/reviews"), + get(move || { + let attempts = Arc::clone(&attempts_clone); + async move { + let count = attempts.fetch_add(1, Ordering::SeqCst); + if count == 0 { + let future = std::time::SystemTime::now() + std::time::Duration::from_secs(1); + let http_date = httpdate::fmt_http_date(future); + ( + StatusCode::TOO_MANY_REQUESTS, + [ + (header::RETRY_AFTER, http_date), + (header::CONTENT_TYPE, "application/json".to_owned()), + ], + Json(json!({"title": "Too Many Requests", "status": 429, "detail": "Rate limit exceeded"})), + ) + .into_response() + } else { + ( + StatusCode::OK, + [(header::CONTENT_TYPE, "application/json".to_owned())], + Json(json!({ + "items": [], + "next_cursor": null, + "truncated": false, + "filters": { + "environments": [], + "kinds": [], + "repositories": [] + } + })), + ) + .into_response() + } + } + }), + ); + + 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 api = Api::new( + Http::new(Origin::parse(&origin).unwrap()).unwrap(), + SecretString::from(TOKEN), + org(), + ); + let page = api.reviews(None, None, None).await.unwrap(); + assert_eq!(page.items.len(), 0); + assert_eq!( + attempts.load(Ordering::SeqCst), + 2, + "Api::read should have retried after honoring the HTTP-date header" + ); + server.abort(); +} diff --git a/tests/local_patch.rs b/tests/local_patch.rs index 5c704a7..3979e77 100644 --- a/tests/local_patch.rs +++ b/tests/local_patch.rs @@ -894,3 +894,61 @@ async fn local_path_never_expands_a_file_replaced_by_a_directory() { assert_eq!(checkout.index().await, index); server.close().await; } + +#[tokio::test] +async fn watch_mode_detects_changes_and_requests_review() { + let checkout = Checkout::new(&[("tracked.txt", "initial\n")]).await; + let server = Server::start(true).await; + + let mut command = Command::new(env!("CARGO_BIN_EXE_proofline")); + command + .current_dir(checkout.root()) + .env("PROOFLINE_TOKEN", TOKEN) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .args([ + "--base-url", + &server.origin, + "--org", + ORG, + "watch", + "--repo", + "acme/web", + "--interval", + "50", + "--debounce", + "50", + ]); + checkout.git_environment(&mut command); + + let mut child = command.spawn().unwrap(); + + // Wait until the daemon starts up + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + + checkout.write("tracked.txt", "initial\nmodified\n").await; + + // Poll until the review request is received or 5 seconds elapse + let start = std::time::Instant::now(); + while server.fixture.uploads.lock().unwrap().is_empty() + && start.elapsed() < std::time::Duration::from_secs(5) + { + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + + child.kill().await.unwrap(); + let output = child.wait_with_output().await.unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + + { + let uploads = server.fixture.uploads.lock().unwrap(); + assert_eq!( + uploads.len(), + 1, + "watch mode should have uploaded 1 review request. stderr: {stderr}" + ); + let patch = uploads[0]["patch"].as_str().unwrap(); + assert!(patch.contains("+modified")); + } + server.close().await; +}