diff --git a/services/common/src/deploy_stats.rs b/services/common/src/deploy_stats.rs index 59f0d683d..8a1e9b355 100644 --- a/services/common/src/deploy_stats.rs +++ b/services/common/src/deploy_stats.rs @@ -27,6 +27,10 @@ pub const BACKFILL_MARKER_SK: &str = "ANALYTICS#deploy-runs-backfilled#v1"; pub const BACKFILL_REPO_PREFIX: &str = "ANALYTICS#deploy-runs-backfilled#v1#repo#"; /// Set when the backfill was last asked for, so a page load asks at most hourly. pub const BACKFILL_QUEUED_SK: &str = "ANALYTICS#deploy-runs-backfill-queued"; +/// While the backfill runs: how many repositories it has read of how many +/// (`repos_read`, `repos_total`), and the lease of the one pass reading +/// (`lease`, `lease_until`), so a page load never starts a second chain. +pub const BACKFILL_PROGRESS_SK: &str = "ANALYTICS#deploy-runs-backfill-progress"; /// How far back the backfill reads: the longest period the page shows (90 /// days) and the one before it. pub const BACKFILL_DAYS: i64 = 182; diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 119e56924..46058e2d1 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -1169,6 +1169,10 @@ pub struct OnboardRepo { #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct DeployStatsBackfillMessage { pub team_id: String, + /// Set on a pass the backfill queued for itself: the lease that pass + /// holds, so it continues while any other ask waits its turn. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lease: Option, } /// One completed workflow run, from its webhook: the run's own fields @@ -1180,6 +1184,9 @@ pub struct DeployRunMessage { pub repo_owner: String, pub repo_name: String, pub run: serde_json::Value, + /// How many times GitHub's rate limit sent this run back. + #[serde(default)] + pub attempts: u32, } /// Work out suggested hidden fields for one database source from its table diff --git a/services/gateway/src/routes/analytics.rs b/services/gateway/src/routes/analytics.rs index 5b751e4eb..d6803e291 100644 --- a/services/gateway/src/routes/analytics.rs +++ b/services/gateway/src/routes/analytics.rs @@ -1000,6 +1000,42 @@ pub struct DeployBackfill { pub since: Option, /// Repositories whose workflow runs CoderHelm can't read. pub no_access: Vec, + /// Repositories the backfill gave up on, with why, by name. + pub not_read: Vec<(String, String)>, + /// While it runs: repositories read, of how many. + pub progress: Option<(u64, u64)>, +} + +impl DeployBackfill { + /// From the backfill's marker (set once done) and its progress item + /// (written while it runs). + pub fn from_items(marker: Option<&Item>, progress: Option<&Item>) -> DeployBackfill { + let n = |i: &Item, k: &str| { + i.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|x| x.parse::().ok()) + }; + let mut not_read: Vec<(String, String)> = marker + .and_then(|i| i.get("not_read")) + .and_then(|v| v.as_m().ok()) + .map(|m| { + m.iter() + .map(|(repo, why)| (repo.clone(), why.as_s().cloned().unwrap_or_default())) + .collect() + }) + .unwrap_or_default(); + not_read.sort(); + DeployBackfill { + since: marker.map(|i| s(i, "since")).filter(|x| !x.is_empty()), + no_access: marker + .and_then(|i| i.get("no_access")) + .and_then(|v| v.as_ss().ok()) + .cloned() + .unwrap_or_default(), + not_read, + progress: progress.and_then(|p| Some((n(p, "repos_read")?, n(p, "repos_total")?))), + } + } } /// Adds deploys to the comparison: counts in each period, running totals by @@ -1098,6 +1134,18 @@ pub fn add_deploys( "running" }); compared["deploys_no_access"] = json!(backfill.no_access); + compared["deploys_not_read"] = json!(backfill + .not_read + .iter() + .map(|(repo, reason)| json!({"repo": repo, "reason": reason})) + .collect::>()); + // Real progress while earlier deploys are read: repositories read of all. + compared["deploys_backfill_progress"] = match backfill.progress { + Some((read, total)) if backfill.since.is_none() && total > 0 => { + json!({"read": read.min(total), "total": total}) + } + _ => Value::Null, + }; } /// Asks the worker to read the team's earlier deploys from GitHub, at most @@ -1124,6 +1172,7 @@ async fn ask_for_deploy_backfill(state: &AppState, team: &str) { let message = crate::models::WorkerMessage::DeployStatsBackfill( crate::models::DeployStatsBackfillMessage { team_id: team.to_string(), + lease: None, }, ); if super::github_webhook::send_to_queue(state, &state.config.ticket_queue_url, &message) @@ -1189,6 +1238,7 @@ pub async fn queue_deploy_run(state: &AppState, payload: &Value, team_id: &str) repo_owner: repo["owner"]["login"].as_str().unwrap_or("").to_string(), repo_name: repo["name"].as_str().unwrap_or("").to_string(), run: deploy_run_fields(run), + attempts: 0, }); if super::github_webhook::send_to_queue(state, &state.config.ticket_queue_url, &message) .await @@ -2175,25 +2225,27 @@ pub async fn get_analytics( ), ); let backfill_marker = async { - state - .dynamo - .get_item() - .table_name(&state.config.settings_table_name) - .key("pk", av(&team)) - .key("sk", av(common::deploy_stats::BACKFILL_MARKER_SK)) - .send() - .await - .ok() - .and_then(|r| { - r.item().map(|i| DeployBackfill { - since: Some(s(i, "since")).filter(|x| !x.is_empty()), - no_access: i - .get("no_access") - .and_then(|v| v.as_ss().ok()) - .cloned() - .unwrap_or_default(), - }) - }) + let item = |sk: &'static str| { + let state = &state; + let team = &team; + async move { + state + .dynamo + .get_item() + .table_name(&state.config.settings_table_name) + .key("pk", av(team)) + .key("sk", av(sk)) + .send() + .await + .ok() + .and_then(|r| r.item().cloned()) + } + }; + let (marker, progress) = tokio::join!( + item(common::deploy_stats::BACKFILL_MARKER_SK), + item(common::deploy_stats::BACKFILL_PROGRESS_SK), + ); + DeployBackfill::from_items(marker.as_ref(), progress.as_ref()) }; let (runs, reviews, lookups, traces, known, deploys, backfilled, metered) = tokio::join!( load_runs(&state, &team, whole), @@ -2205,7 +2257,7 @@ pub async fn get_analytics( backfill_marker, load_metered(&state, &team, whole), ); - if backfilled.as_ref().is_none_or(|b| b.since.is_none()) && claims.support_view.is_none() { + if backfilled.since.is_none() && claims.support_view.is_none() { ask_for_deploy_backfill(&state, &team).await; } let deploys: Vec = deploys @@ -2250,7 +2302,7 @@ pub async fn get_analytics( previous_full, &deploys, repo, - &backfilled.unwrap_or_default(), + &backfilled, ); out["days"] = json!(if month_to_date { window.day_slots() @@ -2418,7 +2470,7 @@ mod tests { fn known(days_ago: i64) -> DeployBackfill { DeployBackfill { since: Some(at(days_ago)), - no_access: vec![], + ..Default::default() } } @@ -2494,12 +2546,59 @@ mod tests { let b = DeployBackfill { since: Some(at(182)), no_access: vec!["acme/infra".into()], + ..Default::default() }; add_deploys(&mut c, w, p, None, &[], None, &b); assert_eq!(c["deploys_no_access"], json!(["acme/infra"])); assert_eq!(c["deploys_comparable"], true); } + /// The page showed "Counting earlier deploys" for hours: while the + /// backfill runs it says how far it got, and once done it names the + /// repositories it gave up on instead of counting forever. + #[test] + fn the_backfill_says_how_far_it_got_and_names_what_it_could_not_read() { + let (w, p) = windows(); + let progress: Item = HashMap::from([ + ("repos_read".to_string(), AttributeValue::N("12".into())), + ("repos_total".to_string(), AttributeValue::N("40".into())), + ("lease".to_string(), AttributeValue::S("x".into())), + ]); + let running = DeployBackfill::from_items(None, Some(&progress)); + assert_eq!(running.progress, Some((12, 40))); + let rows = vec![dep(2, 1, "staging", "succeeded")]; + let mut c = comparison(w, p, None, &[], &[], &[]); + add_deploys(&mut c, w, p, None, &rows, None, &running); + assert_eq!(c["deploys_backfill"], "running"); + assert_eq!( + c["deploys_backfill_progress"], + json!({"read": 12, "total": 40}) + ); + // The current period counts whatever the backfill's state. + assert_eq!(c["current"]["deploys"], 1); + + let marker: Item = HashMap::from([ + ("since".to_string(), AttributeValue::S(at(182))), + ( + "not_read".to_string(), + AttributeValue::M(HashMap::from([( + "acme/big".to_string(), + AttributeValue::S("GitHub answered 502 Bad Gateway".into()), + )])), + ), + ]); + let done = DeployBackfill::from_items(Some(&marker), Some(&progress)); + let mut d = comparison(w, p, None, &[], &[], &[]); + add_deploys(&mut d, w, p, None, &rows, None, &done); + assert_eq!(d["deploys_backfill"], "done"); + assert_eq!(d["deploys_backfill_progress"], Value::Null); + assert_eq!( + d["deploys_not_read"], + json!([{"repo": "acme/big", "reason": "GitHub answered 502 Bad Gateway"}]) + ); + assert_eq!(d["deploys_previous_state"], "known"); + } + #[test] fn only_runs_coderhelm_may_have_started_go_to_the_worker() { let bot = "coderhelm[bot]"; diff --git a/services/gateway/src/routes/tests_setup.rs b/services/gateway/src/routes/tests_setup.rs index ac77c7c7c..f6f3b13af 100644 --- a/services/gateway/src/routes/tests_setup.rs +++ b/services/gateway/src/routes/tests_setup.rs @@ -114,23 +114,46 @@ impl Gh<'_> { .await .map_err(|e| e.to_string())?; let status = resp.status().as_u16(); - Ok((status, resp.json::().await.unwrap_or(Value::Null))) + let header = |name: &str| { + resp.headers() + .get(name) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) + }; + let limits = RateHeaders { + remaining: header("x-ratelimit-remaining"), + reset: header("x-ratelimit-reset"), + retry_after: header("retry-after"), + }; + let body = resp.json::().await.unwrap_or(Value::Null); + // GitHub's rate limit stops every read alike: say so, never "not found". + if let Some(m) = rate_limit_message(status, &limits, &body, chrono::Utc::now().timestamp()) + { + return Err(m); + } + Ok((status, body)) } - async fn file(&self, repo: &str, path: &str, git_ref: &str) -> Option { + /// A file's text, None when it isn't there. An error when GitHub refused + /// for its rate limit, so a check never reads "no workflow" from a limit. + async fn file(&self, repo: &str, path: &str, git_ref: &str) -> Result, String> { let (status, v) = self .get(&format!( "/repos/{repo}/contents/{path}?ref={}", urlencoding::encode(git_ref) )) - .await - .ok()?; + .await?; if status != 200 { - return None; + return Ok(None); } - let b64: String = v["content"].as_str()?.split_whitespace().collect(); - let bytes = base64::engine::general_purpose::STANDARD.decode(b64).ok()?; - String::from_utf8(bytes).ok() + let Some(content) = v["content"].as_str() else { + return Ok(None); + }; + let b64: String = content.split_whitespace().collect(); + Ok(base64::engine::general_purpose::STANDARD + .decode(b64) + .ok() + .and_then(|b| String::from_utf8(b).ok())) } async fn first_file( @@ -138,13 +161,74 @@ impl Gh<'_> { repo: &str, paths: &[&str], git_ref: &str, - ) -> Option<(String, String)> { + ) -> Result, String> { for p in paths { - if let Some(t) = self.file(repo, p, git_ref).await { - return Some((p.to_string(), t)); + if let Some(t) = self.file(repo, p, git_ref).await? { + return Ok(Some((p.to_string(), t))); } } - None + Ok(None) + } +} + +/// GitHub's rate limit headers on one response. +#[derive(Debug, Default)] +struct RateHeaders { + remaining: Option, + reset: Option, + retry_after: Option, +} + +/// When a response is GitHub's rate limit (a 429, or a 403 with no requests +/// left or a body that says rate limit): what to tell the person, with when +/// it resets. `now`: epoch seconds. +fn rate_limit_message(status: u16, h: &RateHeaders, body: &Value, now: i64) -> Option { + let spent = h.remaining.as_deref().map(str::trim) == Some("0"); + let says = body["message"] + .as_str() + .is_some_and(|m| m.to_ascii_lowercase().contains("rate limit")); + if !(status == 429 || (status == 403 && (spent || says))) { + return None; + } + let at = h + .retry_after + .as_deref() + .and_then(|s| s.trim().parse::().ok()) + .map(|secs| now + secs) + .or_else(|| { + h.reset + .as_deref() + .and_then(|s| s.trim().parse::().ok()) + }) + .filter(|t| *t > now); + Some( + match at.and_then(|t| chrono::DateTime::from_timestamp(t, 0)) { + Some(t) => { + let minutes = ((t.timestamp() - now) + 59) / 60; + format!( + "GitHub's hourly limit for Coderhelm is used up. It resets at {} UTC, in about {} {}; try again then.", + t.format("%H:%M"), + minutes, + if minutes == 1 { "minute" } else { "minutes" } + ) + } + None => { + "GitHub's hourly limit for Coderhelm is used up. Try again in a few minutes.".into() + } + }, + ) +} + +/// What a refused read of the repository itself says: only a 404 means the +/// app can't see it; anything else is what GitHub answered. +fn repo_refusal(status: u16, body: &Value) -> String { + let said = body["message"].as_str().unwrap_or("").trim(); + match status { + 404 => "Coderhelm's GitHub app can't see this repository.".into(), + 401 => "GitHub didn't accept Coderhelm's sign in. Try again.".into(), + 403 if !said.is_empty() => format!("GitHub refused to read this repository: {said}"), + _ if !said.is_empty() => format!("GitHub answered {status}: {said}"), + _ => format!("GitHub answered {status} when reading this repository. Try again."), } } @@ -222,7 +306,7 @@ struct Files { async fn read_repo(gh: &Gh<'_>, repo: &str) -> Result<(Check, Files), String> { let (status, info) = gh.get(&format!("/repos/{repo}")).await?; if status != 200 { - return Err("Coderhelm's GitHub app can't see this repository.".into()); + return Err(repo_refusal(status, &info)); } let branch = info["default_branch"] .as_str() @@ -247,12 +331,12 @@ async fn read_repo(gh: &Gh<'_>, repo: &str) -> Result<(Check, Files), String> { if !(path.ends_with(".yml") || path.ends_with(".yaml")) { continue; } - if let Some(text) = gh.file(repo, path, &branch).await { + if let Some(text) = gh.file(repo, path, &branch).await? { files.push((path.to_string(), text)); } } } - let pkg = gh.file(repo, "package.json", &branch).await; + let pkg = gh.file(repo, "package.json", &branch).await?; let scripts = package_scripts(pkg.as_deref()); let picked = pick_workflow(&files, &scripts); let runner = picked @@ -268,7 +352,7 @@ async fn read_repo(gh: &Gh<'_>, repo: &str) -> Result<(Check, Files), String> { Runner::Cypress => &["cypress.config.ts", "cypress.config.js"], Runner::Junit => &[], }; - let config = gh.first_file(repo, configs, &branch).await; + let config = gh.first_file(repo, configs, &branch).await?; check.reporter_file = config.as_ref().map(|(p, _)| p.clone()); check.reporter_ok = reporter_writes_results(r, config.as_ref().map(|(_, t)| t.as_str()), pkg.as_deref()); @@ -849,6 +933,62 @@ pub async fn on_pr_closed( mod unit { use super::*; + /// "Create setup PR" said the app couldn't see a repository it could: + /// GitHub's hourly limit was used up. A limit says so, with when it + /// resets; only a 404 means the app can't see the repository. + #[test] + fn a_rate_limit_is_never_read_as_cant_see_the_repository() { + let now = 1_000_000; + let spent = RateHeaders { + remaining: Some("0".into()), + reset: Some((now + 1_500).to_string()), + retry_after: None, + }; + let body = json!({"message": "API rate limit exceeded for installation ID 1."}); + let m = rate_limit_message(403, &spent, &body, now).unwrap(); + assert_eq!( + m, + "GitHub's hourly limit for Coderhelm is used up. It resets at 14:11 UTC, in about 25 minutes; try again then." + ); + // A secondary limit: retry-after, no headers spent. + let secondary = RateHeaders { + retry_after: Some("60".into()), + ..Default::default() + }; + let m = rate_limit_message( + 403, + &secondary, + &json!({"message": "You have exceeded a secondary rate limit"}), + now, + ) + .unwrap(); + assert!(m.contains("in about 1 minute;"), "{m}"); + assert!( + rate_limit_message(429, &RateHeaders::default(), &Value::Null, now) + .unwrap() + .contains("Try again in a few minutes") + ); + // Other refusals are not limits, and say what they are. + let plain = RateHeaders { + remaining: Some("4000".into()), + ..Default::default() + }; + let forbidden = json!({"message": "Resource not accessible by integration"}); + assert_eq!(rate_limit_message(403, &plain, &forbidden, now), None); + assert_eq!( + repo_refusal(403, &forbidden), + "GitHub refused to read this repository: Resource not accessible by integration" + ); + assert_eq!( + repo_refusal(404, &json!({"message": "Not Found"})), + "Coderhelm's GitHub app can't see this repository." + ); + assert_eq!( + repo_refusal(502, &Value::Null), + "GitHub answered 502 when reading this repository. Try again." + ); + } + #[test] fn repo_names_are_checked_before_any_github_path() { assert!(valid_repo("acme/web-app")); diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 7488a6748..bde189ad8 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -58,8 +58,162 @@ async fn ok_or_body( return Ok(resp); } let url = resp.url().clone(); + let header = |name: &str| { + resp.headers() + .get(name) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) + }; + let (retry_after, remaining, reset) = ( + header("retry-after"), + header("x-ratelimit-remaining"), + header("x-ratelimit-reset"), + ); let body = resp.text().await.unwrap_or_default(); - Err(status_error_message(status, url.as_str(), &body).into()) + let message = status_error_message(status, url.as_str(), &body); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + match rate_limit_wait( + status.as_u16(), + retry_after.as_deref(), + remaining.as_deref(), + reset.as_deref(), + &body, + now, + ) { + Some(wait_secs) => Err(Box::new(RateLimited { wait_secs, message })), + None => Err(message.into()), + } +} + +/// GitHub refused a request for its rate limit (primary or secondary). The +/// message is the usual status line, so string checks still match; the wait +/// is how long GitHub asked for. +#[derive(Debug)] +pub struct RateLimited { + pub wait_secs: u64, + message: String, +} + +impl std::fmt::Display for RateLimited { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for RateLimited {} + +/// When a response is a rate limit, how long to wait before asking again: +/// a 429, or a 403 with no requests left or a body that says rate limit. +/// `retry-after` wins, then the primary limit's reset time, else a minute. +fn rate_limit_wait( + status: u16, + retry_after: Option<&str>, + remaining: Option<&str>, + reset: Option<&str>, + body: &str, + now: u64, +) -> Option { + let spent = remaining.map(str::trim) == Some("0"); + let limited = status == 429 + || (status == 403 && (spent || body.to_ascii_lowercase().contains("rate limit"))); + if !limited { + return None; + } + let after = retry_after.and_then(|s| s.trim().parse::().ok()); + let until_reset = reset + .and_then(|s| s.trim().parse::().ok()) + .filter(|_| spent) + .map(|r| r.saturating_sub(now) + 1); + Some(after.or(until_reset).unwrap_or(60).max(1)) +} + +/// GitHub's hourly REST budget for one installation, as its last response +/// said: requests left, of how many, and when it refills (epoch seconds). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Budget { + pub remaining: u64, + pub limit: u64, + pub reset: u64, +} + +/// The last budget each installation's responses reported, in this process. +static BUDGETS: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| Mutex::new(HashMap::new())); + +/// The budget a response's headers report. Only the core REST budget: +/// search and GraphQL have budgets of their own. +fn budget_from( + resource: Option<&str>, + remaining: Option<&str>, + limit: Option<&str>, + reset: Option<&str>, +) -> Option { + if resource.is_some_and(|r| r.trim() != "core") { + return None; + } + let n = |s: Option<&str>| s.and_then(|v| v.trim().parse::().ok()); + Some(Budget { + remaining: n(remaining)?, + limit: n(limit).filter(|l| *l > 0)?, + reset: n(reset).unwrap_or(0), + }) +} + +/// Records the budget an installation's response reported, success or not. +pub fn observe_budget(installation_id: u64, headers: &reqwest::header::HeaderMap) { + let h = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()); + if let Some(b) = budget_from( + h("x-ratelimit-resource"), + h("x-ratelimit-remaining"), + h("x-ratelimit-limit"), + h("x-ratelimit-reset"), + ) { + record_budget(installation_id, b); + } +} + +pub fn record_budget(installation_id: u64, b: Budget) { + if let Ok(mut m) = BUDGETS.lock() { + m.insert(installation_id, b); + } +} + +pub fn budget_of(installation_id: u64) -> Option { + BUDGETS.lock().ok()?.get(&installation_id).copied() +} + +/// Background work spends only while at least half the hourly budget is +/// left, so live work (reviews, runs) always has the rest. +pub const BACKGROUND_SHARE_PCT: u64 = 50; + +/// How long background work waits before spending again: None while the +/// budget has headroom (or none was seen yet), else the seconds until the +/// reset (at least a minute). `now`: epoch seconds. +pub fn background_wait(b: Option, now: u64) -> Option { + let b = b?; + if b.remaining * 100 >= b.limit * BACKGROUND_SHARE_PCT { + return None; + } + if b.reset > 0 && b.reset <= now { + // Past the reset: the next response tells the new budget. + return None; + } + Some(b.reset.saturating_sub(now).max(60)) +} + +/// How long GitHub asked to wait, when this error is its rate limit. Reads +/// the typed error, and the status line for errors that lost their type. +pub fn rate_limited(e: &(dyn std::error::Error + Send + Sync + 'static)) -> Option { + if let Some(r) = e.downcast_ref::() { + return Some(r.wait_secs); + } + let m = e.to_string(); + (m.contains("(429 Too Many Requests)") + || (m.contains("(403 Forbidden)") && m.to_ascii_lowercase().contains("rate limit"))) + .then_some(60) } fn status_error_message(status: reqwest::StatusCode, url: &str, body: &str) -> String { @@ -421,6 +575,23 @@ impl GitHubClient { ]) } + /// Sends a request made with the installation's token, recording the + /// budget its response reports. + async fn send_tracked( + &self, + req: reqwest::RequestBuilder, + ) -> Result { + let resp = req.send().await?; + observe_budget(self.installation_id, resp.headers()); + Ok(resp) + } + + /// How long background reads should wait for the installation's budget + /// to refill (see [`background_wait`]); None while there is headroom. + pub fn background_wait(&self) -> Option { + background_wait(budget_of(self.installation_id), Self::now_epoch()) + } + async fn get( &self, url: &str, @@ -430,7 +601,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - let resp = ok_or_body(req.send().await?).await?; + let resp = ok_or_body(self.send_tracked(req).await?).await?; Ok(resp.json().await?) } @@ -444,7 +615,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - let resp = ok_or_body(req.send().await?).await?; + let resp = ok_or_body(self.send_tracked(req).await?).await?; Ok(resp.json().await?) } @@ -458,7 +629,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - let resp = ok_or_body(req.send().await?).await?; + let resp = ok_or_body(self.send_tracked(req).await?).await?; Ok(resp.json().await?) } @@ -478,7 +649,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - let resp = req.send().await?.error_for_status()?; + let resp = self.send_tracked(req).await?.error_for_status()?; let bytes = resp.bytes().await?; if bytes.len() > MAX_TARBALL_BYTES { return Err(format!( @@ -983,7 +1154,7 @@ impl GitHubClient { for (k, v) in &headers { req = req.header(k, v); } - let resp = req.send().await?.error_for_status()?; + let resp = self.send_tracked(req).await?.error_for_status()?; let data: serde_json::Value = resp.json().await?; let items = data .get("items") @@ -1024,7 +1195,7 @@ impl GitHubClient { req = req.header(k, v); } } - let resp = req.send().await?.error_for_status()?; + let resp = self.send_tracked(req).await?.error_for_status()?; let data: serde_json::Value = resp.json().await?; let items = data .get("items") @@ -1195,7 +1366,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - let resp = req.send().await?; + let resp = self.send_tracked(req).await?; match resp.status().as_u16() { 200 => Ok(true), 409 | 422 => Ok(false), // non-fast-forward — someone advanced the ref @@ -1367,7 +1538,7 @@ impl GitHubClient { for (k, v) in &headers { req = req.header(k.clone(), v.clone()); } - let resp = req.send().await?; + let resp = self.send_tracked(req).await?; if resp.status() == reqwest::StatusCode::UNPROCESSABLE_ENTITY { // Branch already exists. INVARIANT: a branch with an OPEN PR is @@ -1466,7 +1637,7 @@ impl GitHubClient { for (k, v) in &headers { req = req.header(k.clone(), v.clone()); } - let resp = req.send().await?; + let resp = self.send_tracked(req).await?; match resp.status().as_u16() { 201 => { self.invalidate_snapshot(owner, repo, base).await; @@ -1505,7 +1676,7 @@ impl GitHubClient { for (k, v) in &headers { req = req.header(k.clone(), v.clone()); } - let resp = req.send().await?; + let resp = self.send_tracked(req).await?; match resp.status().as_u16() { 201 => Ok(Some(resp.json().await?)), 204 => Ok(Some(serde_json::Value::Null)), @@ -2086,7 +2257,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - let resp = req.send().await?; + let resp = self.send_tracked(req).await?; let status = resp.status().as_u16(); if (200..300).contains(&status) { let result: serde_json::Value = resp.json().await?; @@ -2777,7 +2948,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - let resp = req.send().await?; + let resp = self.send_tracked(req).await?; let status = resp.status().as_u16(); if status == 200 { return Ok(MergeOutcome::Merged); @@ -2919,7 +3090,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - ok_or_body(req.send().await?).await?; + ok_or_body(self.send_tracked(req).await?).await?; Ok(()) } @@ -2941,7 +3112,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - ok_or_body(req.send().await?).await?; + ok_or_body(self.send_tracked(req).await?).await?; Ok(()) } @@ -3363,7 +3534,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - let resp = req.send().await?.error_for_status()?; + let resp = self.send_tracked(req).await?.error_for_status()?; Ok(resp.text().await?) } @@ -3744,7 +3915,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - ok_or_body(req.send().await?).await?; + ok_or_body(self.send_tracked(req).await?).await?; Ok(()) } @@ -3788,7 +3959,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - let mut resp = req.send().await?.error_for_status()?; + let mut resp = self.send_tracked(req).await?.error_for_status()?; let mut buf = Vec::new(); while let Some(chunk) = resp.chunk().await? { if buf.len() + chunk.len() > max_bytes { @@ -3827,7 +3998,7 @@ impl GitHubClient { for (k, v) in headers { req = req.header(k, v); } - ok_or_body(req.send().await?).await?; + ok_or_body(self.send_tracked(req).await?).await?; Ok(()) } @@ -3930,7 +4101,7 @@ impl GitHubClient { for (k, v) in &headers { req = req.header(k, v); } - let resp = req.send().await?; + let resp = self.send_tracked(req).await?; if resp.status().is_success() { return Ok(()); } @@ -4534,6 +4705,94 @@ mod status_error_tests { status_error_message(reqwest::StatusCode::FORBIDDEN, "u", "too_large").into(); assert!(!is_not_found(&*forbidden)); } + + #[test] + fn background_reads_keep_half_the_budget_for_live_work() { + let now = 1_000; + let b = budget_from(Some("core"), Some("2600"), Some("5000"), Some("4000")).unwrap(); + assert_eq!(background_wait(Some(b), now), None); + // Below half: wait for the reset. + let low = budget_from(None, Some("2499"), Some("5000"), Some("4000")).unwrap(); + assert_eq!(background_wait(Some(low), now), Some(3000)); + // Past the reset, or never seen: spend, the next response tells. + assert_eq!(background_wait(Some(low), 5000), None); + assert_eq!(background_wait(None, now), None); + // Search and GraphQL budgets are their own, never the core one. + assert_eq!( + budget_from(Some("search"), Some("1"), Some("30"), Some("4000")), + None + ); + // Every response is recorded per installation. + let mut h = reqwest::header::HeaderMap::new(); + h.insert("x-ratelimit-remaining", "10".parse().unwrap()); + h.insert("x-ratelimit-limit", "5000".parse().unwrap()); + h.insert("x-ratelimit-reset", "4000".parse().unwrap()); + observe_budget(987_654_321, &h); + assert_eq!( + budget_of(987_654_321), + Some(Budget { + remaining: 10, + limit: 5000, + reset: 4000 + }) + ); + assert_eq!(budget_of(987_654_322), None); + } + + #[test] + fn rate_limits_are_told_apart_with_their_wait() { + let now = 1_000; + // Primary limit spent: wait until the reset. + assert_eq!( + rate_limit_wait(403, None, Some("0"), Some("1300"), "", now), + Some(301) + ); + // Secondary limit: retry-after wins. + assert_eq!( + rate_limit_wait( + 403, + Some("45"), + Some("12"), + None, + "You have exceeded a secondary rate limit", + now + ), + Some(45) + ); + assert_eq!(rate_limit_wait(429, None, None, None, "", now), Some(60)); + // Other refusals are not rate limits. + assert_eq!( + rate_limit_wait( + 403, + None, + Some("4000"), + None, + "Resource not accessible by integration", + now + ), + None + ); + assert_eq!(rate_limit_wait(404, None, Some("0"), None, "", now), None); + + let typed: Box = Box::new(RateLimited { + wait_secs: 120, + message: status_error_message(reqwest::StatusCode::FORBIDDEN, "u", "x"), + }); + assert_eq!(rate_limited(&*typed), Some(120)); + // Still reads as the status line it carries. + assert!(typed.to_string().contains("(403 Forbidden)")); + assert!(!is_not_found(&*typed)); + let text: Box = status_error_message( + reqwest::StatusCode::FORBIDDEN, + "u", + "API rate limit exceeded", + ) + .into(); + assert_eq!(rate_limited(&*text), Some(60)); + let other: Box = + status_error_message(reqwest::StatusCode::FORBIDDEN, "u", "too_large").into(); + assert_eq!(rate_limited(&*other), None); + } } #[cfg(test)] diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 0c2513be9..08800aa87 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -668,7 +668,7 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) } models::WorkerMessage::DeployStatsBackfill(msg) => { info!(team_id = %msg.team_id, "Deploy stats backfill"); - if let Err(e) = passes::deploy_stats::backfill(&state, &msg.team_id).await { + if let Err(e) = passes::deploy_stats::backfill(&state, &msg).await { error!("Deploy stats backfill failed: {e:?}"); } } diff --git a/services/worker/src/passes/deploy_stats.rs b/services/worker/src/passes/deploy_stats.rs index 11e6143e8..660b506ad 100644 --- a/services/worker/src/passes/deploy_stats.rs +++ b/services/worker/src/passes/deploy_stats.rs @@ -1,33 +1,69 @@ //! Deploys CoderHelm started (`common::deploy_stats`): a completed workflow //! run, from its webhook or read back from GitHub's run history, recorded //! when CoderHelm's app triggered it and it deployed somewhere. +//! +//! The backfill reads each repository's run history a week at a time and +//! saves where it stands after every page, so a pass that runs out of time, +//! or that GitHub's rate limit pauses, continues from that page. A +//! repository that keeps failing is given up on after a few tries and named +//! as not read; the team is marked done once every repository is read or +//! named. One pass reads at a time per team (a lease on the progress item). use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Instant; use aws_sdk_dynamodb::types::AttributeValue; -use chrono::{Duration, Utc}; -use common::deploy_stats::{self as ds, Cause, JobDef}; +use chrono::{DateTime, Duration, Utc}; +use common::deploy_stats::{self as ds, JobDef}; +use common::messages::{DeployRunMessage, DeployStatsBackfillMessage}; use serde_json::{json, Value}; use tracing::{info, warn}; -use crate::clients::github::GitHubClient; +use crate::clients::github::{is_not_found, rate_limited, GitHubClient}; use crate::WorkerState; type GhError = Box; +type Item = HashMap; fn av(v: &str) -> AttributeValue { AttributeValue::S(v.to_string()) } +fn num(n: impl ToString) -> AttributeValue { + AttributeValue::N(n.to_string()) +} + /// A workflow file's jobs are read again after this long. const WORKFLOW_CACHE_SECS: i64 = 3600; /// A backfill pass stops here and queues the next one, well inside the /// worker's 15 minutes. const PASS_BUDGET_SECS: u64 = 600; -/// Run history is read a week at a time: GitHub returns at most 1,000 runs -/// for one filtered query. +/// How long a pass holds the team's lease: longer than any pass can run. +const LEASE_SECS: i64 = 960; +/// Run history is read a week at a time. const CHUNK_DAYS: i64 = 7; +/// GitHub returns at most 1,000 runs for one filtered query: a range with +/// more is halved until it fits (down to an hour). +const RUNS_CAP: u64 = 1000; +const MIN_RANGE_SECS: i64 = 3600; +/// A repository that fails this many passes in a row, reading nothing, is +/// given up on and named as not read. +const MAX_REPO_ATTEMPTS: u32 = 3; +/// A repository GitHub's rate limit stops this many times in a row before it +/// reads a page is given up on too. +const MAX_REPO_PAUSES: u32 = 24; +/// The longest delay a queued message can carry. +const MAX_DELAY_SECS: u64 = 900; +/// The wait before a pass tries the repositories that failed again. +const RETRY_DELAY_SECS: u64 = 120; +/// How many times a webhook's run waits out a rate limit before it is +/// dropped. +const MAX_RUN_ATTEMPTS: u32 = 5; +/// The most GitHub requests one backfill pass makes, whatever the budget. +const MAX_PASS_REQUESTS: usize = 1000; +/// The wait before the pass after one that used its requests. +const CAP_DELAY_SECS: u64 = 300; /// GitHub refused because the app has no access to Actions here. fn is_no_access(e: &(dyn std::error::Error + Send + Sync)) -> bool { @@ -35,174 +71,537 @@ fn is_no_access(e: &(dyn std::error::Error + Send + Sync)) -> bool { m.contains("(403 Forbidden)") && m.contains("not accessible by integration") } -/// The `created` filters that cover `since` to `now`, a week each. -pub fn created_ranges(since: chrono::DateTime, now: chrono::DateTime) -> Vec { - let mut out = Vec::new(); - let mut from = since; - while from < now { - let to = (from + Duration::days(CHUNK_DAYS)).min(now); - out.push(format!( - "{}..{}", - from.to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - to.to_rfc3339_opts(chrono::SecondsFormat::Secs, true) - )); - from = to; +/// Passes a rate limit up; anything else is swallowed by the caller. +fn only_pause(e: GhError) -> Result<(), GhError> { + if rate_limited(&*e).is_some() { + Err(e) + } else { + Ok(()) + } +} + +fn secs(t: DateTime) -> String { + t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true) +} + +fn parse_time(s: &str) -> Option> { + DateTime::parse_from_rfc3339(s) + .ok() + .map(|t| t.with_timezone(&Utc)) +} + +/// One page of one range of a repository's run history: where a read +/// stands, saved after every page. +#[derive(Debug, Clone, PartialEq)] +pub struct Cursor { + pub from: DateTime, + pub to: DateTime, + pub page: u32, +} + +impl Cursor { + /// GitHub's `created` filter for the range. + pub fn created(&self) -> String { + format!("{}..{}", secs(self.from), secs(self.to)) + } + + fn week_from(from: DateTime, now: DateTime) -> Option { + (from < now).then(|| Cursor { + from, + to: (from + Duration::days(CHUNK_DAYS)).min(now), + page: 1, + }) + } + + /// The first range of the window. + pub fn first(since: DateTime, now: DateTime) -> Option { + Self::week_from(since, now) + } + + /// The range after this one, None once the window is read to `now`. + pub fn next(&self, now: DateTime) -> Option { + Self::week_from(self.to, now) + } + + /// Where a repository's read continues: the saved page, unless it fell + /// out of the window, else the window's start. + pub fn resume( + saved: Option<&Cursor>, + since: DateTime, + now: DateTime, + ) -> Option { + match saved { + Some(c) if c.to > since && c.from < now => Some(c.clone()), + _ => Self::first(since, now), + } + } + + /// The first half of this range, read alone when the range holds more + /// runs than GitHub returns. None when it is already an hour or less. + pub fn halved(&self) -> Option { + let span = self.to - self.from; + (span.num_seconds() > MIN_RANGE_SECS).then(|| Cursor { + from: self.from, + to: self.from + span / 2, + page: 1, + }) } - out +} + +/// Where one repository's backfill stands, from its marker. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum RepoState { + #[default] + New, + Reading, + Done, + NoAccess, + Gone, + NotRead, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct RepoMark { + pub state: RepoState, + pub cursor: Option, + pub attempts: u32, + pub pauses: u32, + pub reason: String, +} + +impl RepoMark { + /// Read from the repository's marker. A marker from before `read_state` + /// existed was only written once the repository was read. + pub fn from_item(item: Option<&Item>) -> RepoMark { + let Some(i) = item else { + return RepoMark::default(); + }; + let s = |k: &str| i.get(k).and_then(|v| v.as_s().ok()).cloned(); + let n = |k: &str| { + i.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|x| x.parse::().ok()) + .unwrap_or(0) + }; + let flag = |k: &str| i.get(k).and_then(|v| v.as_bool().ok()) == Some(&true); + let state = match s("read_state").as_deref() { + Some("reading") => RepoState::Reading, + Some("done") => RepoState::Done, + Some("no_access") => RepoState::NoAccess, + Some("gone") => RepoState::Gone, + Some("not_read") => RepoState::NotRead, + Some(_) => RepoState::Reading, + None if flag("no_access") => RepoState::NoAccess, + None if flag("gone") => RepoState::Gone, + None => RepoState::Done, + }; + let cursor = match ( + s("cursor_from").as_deref().and_then(parse_time), + s("cursor_to").as_deref().and_then(parse_time), + ) { + (Some(from), Some(to)) => Some(Cursor { + from, + to, + page: n("cursor_page").max(1), + }), + _ => None, + }; + RepoMark { + state, + cursor, + attempts: n("attempts"), + pauses: n("pauses"), + reason: s("reason").unwrap_or_default(), + } + } +} + +/// What a pass does with a repository whose read stopped on an error. +#[derive(Debug, Clone, PartialEq)] +pub enum AfterError { + /// GitHub's rate limit: save, and continue in a pass after this wait. + Pause(u64), + /// Try again in the next pass. + Retry, + /// Stop trying: the repository is named as not read, with this reason. + GiveUp(String), +} + +/// A plain reason from an error: GitHub's status when it gave one. +fn plain_reason(message: &str) -> String { + let status = message + .split_once("error (") + .and_then(|(_, rest)| rest.split_once(')')) + .map(|(s, _)| s.to_string()); + match status { + Some(s) => format!("GitHub answered {s}"), + None => common::truncate_str(message.trim(), 160).to_string(), + } +} + +/// `wait`: GitHub's rate limit asked for this wait. `progressed`: the pass +/// read at least a page of this repository before the error, which starts +/// the count of failures in a row again. +pub fn after_error( + wait: Option, + message: &str, + mark: &RepoMark, + progressed: bool, +) -> AfterError { + if let Some(w) = wait { + let pauses = if progressed { 1 } else { mark.pauses + 1 }; + return if pauses >= MAX_REPO_PAUSES { + AfterError::GiveUp("GitHub kept refusing for its rate limit".into()) + } else { + AfterError::Pause(w) + }; + } + let attempts = if progressed { 1 } else { mark.attempts + 1 }; + if attempts >= MAX_REPO_ATTEMPTS { + AfterError::GiveUp(plain_reason(message)) + } else { + AfterError::Retry + } +} + +/// What the deploy reads need from GitHub and storage, so the reading is the +/// same code under test. +#[async_trait::async_trait] +pub trait Source: Send + Sync { + /// GET a path under the repository. + async fn get(&self, rest: &str) -> Result; + /// A workflow file's jobs, None when it can't be read. An error only for + /// GitHub's rate limit. + async fn workflow_jobs(&self, path: &str) -> Result>, GhError>; + /// Writes one deploy record. + async fn save_deploy(&self, item: Item) -> bool; + /// Saves where the repository's backfill stands. + async fn save_cursor(&self, cursor: &Cursor); + /// While GitHub's budget for the installation is below the share + /// background reads may spend: the seconds until it refills. + fn headroom_wait(&self) -> Option; + /// GitHub requests this pass has made so far. + fn requests(&self) -> usize; } /// What the worker knows about one repository while it reads its deploys. -struct RepoReads<'a> { - github: &'a GitHubClient, - owner: String, - name: String, - bot: String, - default_branch: String, - setting: HashMap, +pub struct RepoReads { + pub src: S, + pub team_id: String, + /// `owner/name` + pub repo: String, + pub bot: String, + pub default_branch: String, + pub setting: HashMap, /// Workflow jobs by path, read once per pass. workflows: HashMap>>, + /// Whether a pushed ref is a tag, by name, asked once per pass. + tags: HashMap, } -impl RepoReads<'_> { - fn full(&self) -> String { - format!("{}/{}", self.owner, self.name) +impl RepoReads { + pub fn new( + src: S, + team_id: String, + repo: String, + bot: String, + default_branch: String, + setting: HashMap, + ) -> Self { + RepoReads { + src, + team_id, + repo, + bot, + default_branch, + setting, + workflows: HashMap::new(), + tags: HashMap::new(), + } } - async fn jobs_of( - &mut self, - state: &WorkerState, - team_id: &str, - path: &str, - ) -> Option> { + async fn jobs_of(&mut self, path: &str) -> Result>, GhError> { if path.is_empty() { - return None; + return Ok(None); } if let Some(j) = self.workflows.get(path) { - return j.clone(); + return Ok(j.clone()); } - let j = workflow_jobs(state, team_id, self.github, &self.owner, &self.name, path).await; + let j = self.src.workflow_jobs(path).await?; self.workflows.insert(path.to_string(), j.clone()); - j + Ok(j) } - /// Whether CoderHelm caused this run, and how. - async fn cause(&self, run: &Value) -> Option { - let branch = run["head_branch"].as_str().unwrap_or(""); - let event = run["event"].as_str().unwrap_or(""); - let ours = if ds::started_by_coderhelm(run, &self.bot) { - true - } else { - // A merge queue's push of a PR CoderHelm merged. - let (_, kind) = ds::trigger(run); - kind == "Bot" - && event == "push" - && branch == self.default_branch - && self.merged_by_us(run).await + async fn is_tag(&mut self, name: &str) -> Result { + if let Some(t) = self.tags.get(name) { + return Ok(*t); + } + let path: Vec = name + .split('/') + .map(|s| urlencoding::encode(s).into_owned()) + .collect(); + let t = match self + .src + .get(&format!("git/ref/tags/{}", path.join("/"))) + .await + { + Ok(_) => true, + Err(e) => { + only_pause(e)?; + false + } }; - if !ours { - return None; - } - let is_tag = event == "push" - && branch != self.default_branch - && self - .github - .get_repo_path( - &self.owner, - &self.name, - &format!("git/ref/tags/{}", urlencoding::encode(branch)), - ) - .await - .is_ok(); - Some(ds::cause_of(run, &self.default_branch, is_tag)) + self.tags.insert(name.to_string(), t); + Ok(t) } - async fn merged_by_us(&self, run: &Value) -> bool { + async fn merged_by_us(&self, run: &Value) -> Result { let sha = run["head_sha"].as_str().unwrap_or(""); if sha.is_empty() { - return false; + return Ok(false); } - match self - .github - .get_repo_path(&self.owner, &self.name, &format!("commits/{sha}/pulls")) - .await - { - Ok(v) => ds::merged_by_coderhelm( + match self.src.get(&format!("commits/{sha}/pulls")).await { + Ok(v) => Ok(ds::merged_by_coderhelm( v.as_array().map(|a| a.as_slice()).unwrap_or(&[]), &self.bot, - ), - Err(_) => false, + )), + Err(e) => only_pause(e).map(|_| false), } } /// Records a completed run when CoderHelm started it and it deployed. - /// Returns how many deploys it wrote. - async fn record(&mut self, state: &WorkerState, team_id: &str, run: &Value) -> usize { + /// Returns how many deploys it wrote. Everything known without asking + /// GitHub is checked first: who started it, then whether its workflow can + /// deploy at all (the setting, its name, its file, its jobs read once per + /// workflow). Only a run that may be a deploy costs requests of its own. + /// An error only for GitHub's rate limit. + pub async fn record(&mut self, run: &Value) -> Result { if run["status"].as_str().is_some_and(|s| s != "completed") { - return 0; + return Ok(0); + } + let branch = run["head_branch"].as_str().unwrap_or("").to_string(); + let event = run["event"].as_str().unwrap_or(""); + let started = ds::started_by_coderhelm(run, &self.bot); + // A merge queue's push of a PR CoderHelm may have merged. + let queue_push = !started + && ds::trigger(run).1 == "Bot" + && event == "push" + && !branch.is_empty() + && branch == self.default_branch; + if !started && !queue_push { + return Ok(0); } - let Some(cause) = self.cause(run).await else { - return 0; - }; let path = run["path"].as_str().unwrap_or("").to_string(); - let jobs = self.jobs_of(state, team_id, &path).await; let file = path.rsplit('/').next().unwrap_or("").to_ascii_lowercase(); - let maybe = self.setting.contains_key(&file) + let named = self.setting.contains_key(&file) || ds::says_deploy(run["name"].as_str().unwrap_or("")) - || ds::says_deploy(&file) + || ds::says_deploy(&file); + let jobs = self.jobs_of(&path).await?; + let maybe = named || jobs .as_deref() .unwrap_or(&[]) .iter() .any(|j| !j.environment.is_empty() || ds::says_deploy(&j.name)); if !maybe { - return 0; + return Ok(0); + } + if queue_push && !self.merged_by_us(run).await? { + return Ok(0); } + let is_tag = + event == "push" && branch != self.default_branch && self.is_tag(&branch).await?; + let cause = ds::cause_of(run, &self.default_branch, is_tag); let run_id = run["id"].as_u64().unwrap_or(0); let ran: Option> = match self - .github - .get_repo_path( - &self.owner, - &self.name, - &format!("actions/runs/{run_id}/jobs?per_page=100"), - ) + .src + .get(&format!("actions/runs/{run_id}/jobs?per_page=100")) .await { Ok(v) => v["jobs"].as_array().cloned(), Err(e) => { - warn!(run_id, error = %e, "Deploys: could not read a run's jobs"); + only_pause(e)?; + warn!(run_id, "Deploys: could not read a run's jobs"); None } }; let targets = ds::run_targets(run, jobs.as_deref(), ran.as_deref(), &self.setting); - let repo = self.full(); let mut written = 0; for t in &targets { - let item = ds::stat_item(team_id, &repo, run, cause, t); - match state - .dynamo - .put_item() - .table_name(&state.config.settings_table_name) - .set_item(Some(item)) - .send() - .await - { - Ok(_) => written += 1, - Err(e) => warn!(run_id, error = %e, "Deploys: could not record a deploy"), + let item = ds::stat_item(&self.team_id, &self.repo, run, cause, t); + if self.src.save_deploy(item).await { + written += 1; } } - written + Ok(written) } } -/// A workflow file's jobs, cached in settings for an hour. +/// How one repository's backfill ended. +#[derive(Debug, PartialEq)] +pub enum RepoBackfill { + Done, + NoAccess, + OutOfTime, + /// The installation's budget is below the background share: wait this + /// long for it to refill. + Headroom(u64), + /// The pass made its most requests. + Capped, +} + +/// Reads a repository's run history from `start` to `now`, saving the +/// cursor after every page. `progressed` is set once a page was read. +pub async fn backfill_repo( + reads: &mut RepoReads, + start: Option, + now: DateTime, + out_of_time: &(dyn Fn() -> bool + Send + Sync), + progressed: &mut bool, +) -> Result { + let mut written = 0usize; + let mut cur = start; + while let Some(c) = cur.take() { + if out_of_time() { + return Ok(RepoBackfill::OutOfTime); + } + // Live work keeps its share of the budget: background reads yield + // before every page, and stop at the pass's most requests. + if let Some(wait) = reads.src.headroom_wait() { + return Ok(RepoBackfill::Headroom(wait)); + } + if reads.src.requests() >= MAX_PASS_REQUESTS { + return Ok(RepoBackfill::Capped); + } + let rest = format!( + "actions/runs?actor={}&status=completed&created={}&per_page=100&page={}", + urlencoding::encode(&reads.bot), + urlencoding::encode(&c.created()), + c.page + ); + let v = match reads.src.get(&rest).await { + Ok(v) => v, + Err(e) if is_no_access(&*e) => return Ok(RepoBackfill::NoAccess), + Err(e) => return Err(e), + }; + if c.page == 1 && v["total_count"].as_u64().unwrap_or(0) > RUNS_CAP { + if let Some(h) = c.halved() { + reads.src.save_cursor(&h).await; + cur = Some(h); + continue; + } + warn!(repo = %reads.repo, range = %c.created(), "Deploys backfill: more runs in an hour than GitHub lists"); + } + let runs = v["workflow_runs"].as_array().cloned().unwrap_or_default(); + for run in &runs { + written += reads.record(run).await?; + } + *progressed = true; + let next = if runs.len() < 100 || c.page >= 10 { + c.next(now) + } else { + Some(Cursor { + page: c.page + 1, + ..c + }) + }; + if let Some(n) = &next { + reads.src.save_cursor(n).await; + } + cur = next; + } + info!(repo = %reads.repo, written, "Deploys backfill: repository read"); + Ok(RepoBackfill::Done) +} + +/// The live source: GitHub, and the settings table. +struct Live<'a> { + state: &'a WorkerState, + team_id: String, + github: &'a GitHubClient, + owner: String, + name: String, + mark_sk: String, + /// GitHub requests made by the pass, shared by its repositories. + requests: &'a AtomicUsize, +} + +#[async_trait::async_trait] +impl Source for Live<'_> { + fn headroom_wait(&self) -> Option { + self.github.background_wait() + } + + fn requests(&self) -> usize { + self.requests.load(Ordering::Relaxed) + } + + async fn get(&self, rest: &str) -> Result { + self.requests.fetch_add(1, Ordering::Relaxed); + self.github + .get_repo_path(&self.owner, &self.name, rest) + .await + } + + async fn workflow_jobs(&self, path: &str) -> Result>, GhError> { + workflow_jobs( + self.requests, + self.state, + &self.team_id, + self.github, + &self.owner, + &self.name, + path, + ) + .await + } + + async fn save_deploy(&self, item: Item) -> bool { + match self + .state + .dynamo + .put_item() + .table_name(&self.state.config.settings_table_name) + .set_item(Some(item)) + .send() + .await + { + Ok(_) => true, + Err(e) => { + warn!(error = %e, "Deploys: could not record a deploy"); + false + } + } + } + + async fn save_cursor(&self, c: &Cursor) { + update( + self.state, + &self.team_id, + &self.mark_sk, + &[ + ("read_state", av("reading")), + ("cursor_from", av(&secs(c.from))), + ("cursor_to", av(&secs(c.to))), + ("cursor_page", num(c.page)), + ], + &[], + ) + .await; + } +} + +/// A workflow file's jobs, cached in settings for an hour. An error only for +/// GitHub's rate limit. async fn workflow_jobs( + requests: &AtomicUsize, state: &WorkerState, team_id: &str, github: &GitHubClient, owner: &str, repo: &str, path: &str, -) -> Option> { +) -> Result>, GhError> { let table = &state.config.settings_table_name; let sk = format!("DWF#{owner}/{repo}#{path}").to_ascii_lowercase(); let now = Utc::now().timestamp(); @@ -227,7 +626,7 @@ async fn workflow_jobs( .and_then(|v| v.as_s().ok()) .and_then(|s| serde_json::from_str(s).ok()) .unwrap_or_default(); - return Some( + return Ok(Some( jobs.iter() .map(|j| JobDef { key: j["key"].as_str().unwrap_or("").into(), @@ -235,18 +634,24 @@ async fn workflow_jobs( environment: j["environment"].as_str().unwrap_or("").into(), }) .collect(), - ); + )); } } } + requests.fetch_add(1, Ordering::Relaxed); let text = match github.read_file_live(owner, repo, path, "HEAD").await { Ok(t) => t, Err(e) => { + if rate_limited(&*e).is_some() { + return Err(e); + } warn!(path, error = %e, "Deploys: could not read a workflow file"); - return None; + return Ok(None); } }; - let jobs = ds::parse_workflow(&text)?; + let Some(jobs) = ds::parse_workflow(&text) else { + return Ok(None); + }; let stored: Vec = jobs .iter() .map(|j| json!({"key": j.key, "name": j.name, "environment": j.environment})) @@ -258,11 +663,11 @@ async fn workflow_jobs( .item("pk", av(team_id)) .item("sk", av(&sk)) .item("jobs", av(&Value::Array(stored).to_string())) - .item("checked_at", AttributeValue::N(now.to_string())) - .item("ttl", AttributeValue::N((now + 86_400).to_string())) + .item("checked_at", num(now)) + .item("ttl", num(now + 86_400)) .send() .await; - Some(jobs) + Ok(Some(jobs)) } /// The repository's deploy workflows setting, from its review config. @@ -290,150 +695,251 @@ async fn deploy_workflows_setting( ) } -async fn repo_reads<'a>( - state: &WorkerState, +async fn live_reads<'a>( + state: &'a WorkerState, team_id: &str, github: &'a GitHubClient, + requests: &'a AtomicUsize, owner: &str, name: &str, bot: &str, -) -> Result, GhError> { +) -> Result>, GhError> { + requests.fetch_add(1, Ordering::Relaxed); let default_branch = github.get_default_branch(owner, name).await?; - Ok(RepoReads { - github, - owner: owner.to_string(), - name: name.to_string(), - bot: bot.to_string(), + let full = format!("{owner}/{name}"); + Ok(RepoReads::new( + Live { + state, + team_id: team_id.to_string(), + github, + owner: owner.to_string(), + name: name.to_string(), + mark_sk: repo_sk(&full), + requests, + }, + team_id.to_string(), + full.clone(), + bot.to_string(), default_branch, - setting: deploy_workflows_setting(state, team_id, &format!("{owner}/{name}")).await, - workflows: HashMap::new(), - }) + deploy_workflows_setting(state, team_id, &full).await, + )) } -/// Records one completed workflow run from its webhook. -pub async fn record_run( - state: &WorkerState, - msg: &common::messages::DeployRunMessage, -) -> Result<(), String> { - let Some(github) = super::plan_chat::github_for(state, &msg.team_id).await else { - return Err("no GitHub installation for the team".into()); - }; - let bot = github - .app_bot_login() - .await - .map_err(|e| format!("bot login: {e}"))?; - let mut reads = repo_reads( - state, - &msg.team_id, - &github, - &msg.repo_owner, - &msg.repo_name, - &bot, +fn repo_sk(full_name: &str) -> String { + format!( + "{}{}", + ds::BACKFILL_REPO_PREFIX, + full_name.to_ascii_lowercase() ) - .await - .map_err(|e| format!("read repository: {e}"))?; - let n = reads.record(state, &msg.team_id, &msg.run).await; - if n > 0 { - info!( - run_id = msg.run["id"].as_u64().unwrap_or(0), - deploys = n, - "Deploy recorded" - ); - } - Ok(()) } -/// How one repository's backfill ended. -enum RepoBackfill { - Done, - NoAccess, - OutOfTime, +/// Sends a message to the tickets queue, after `delay` seconds. +async fn send(state: &WorkerState, body: String, delay: u64) -> bool { + if state.config.ticket_queue_url.is_empty() { + return false; + } + match state + .sqs + .send_message() + .queue_url(&state.config.ticket_queue_url) + .message_body(body) + .delay_seconds(delay.min(MAX_DELAY_SECS) as i32) + .send() + .await + { + Ok(_) => true, + Err(e) => { + warn!(error = %e, "Deploys: could not queue a message"); + false + } + } } -async fn backfill_repo( - state: &WorkerState, - team_id: &str, - reads: &mut RepoReads<'_>, - since: chrono::DateTime, - started: Instant, -) -> Result { - let mut written = 0usize; - for range in created_ranges(since, Utc::now()) { - for page in 1..=10u32 { - if started.elapsed().as_secs() > PASS_BUDGET_SECS { - return Ok(RepoBackfill::OutOfTime); - } - let rest = format!( - "actions/runs?actor={}&status=completed&created={}&per_page=100&page={page}", - urlencoding::encode(&reads.bot), - urlencoding::encode(&range) - ); - let v = match reads - .github - .get_repo_path(&reads.owner, &reads.name, &rest) - .await - { - Ok(v) => v, - Err(e) if is_no_access(&*e) => return Ok(RepoBackfill::NoAccess), - Err(e) => return Err(e), - }; - let runs = v["workflow_runs"].as_array().cloned().unwrap_or_default(); - for run in &runs { - written += reads.record(state, team_id, run).await; - } - if runs.len() < 100 { - break; +/// Records one completed workflow run from its webhook. GitHub's rate limit +/// sends the run back to wait, a few times, instead of dropping it. +pub async fn record_run(state: &WorkerState, msg: &DeployRunMessage) -> Result<(), String> { + let Some(github) = super::plan_chat::github_for(state, &msg.team_id).await else { + return Err("no GitHub installation for the team".into()); + }; + let requests = AtomicUsize::new(0); + let outcome: Result = async { + let bot = github.app_bot_login().await?; + let mut reads = live_reads( + state, + &msg.team_id, + &github, + &requests, + &msg.repo_owner, + &msg.repo_name, + &bot, + ) + .await?; + reads.record(&msg.run).await + } + .await; + let run_id = msg.run["id"].as_u64().unwrap_or(0); + match outcome { + Ok(n) => { + if n > 0 { + info!(run_id, deploys = n, "Deploy recorded"); } + Ok(()) } + Err(e) => match rate_limited(&*e) { + Some(wait) if msg.attempts < MAX_RUN_ATTEMPTS => { + let mut again = msg.clone(); + again.attempts += 1; + let body = serde_json::to_string(&crate::models::WorkerMessage::DeployRun(again)) + .map_err(|e| e.to_string())?; + if send(state, body, wait).await { + info!(run_id, wait, "Deploy run waits out GitHub's rate limit"); + Ok(()) + } else { + Err(format!("rate limited and could not queue again: {e}")) + } + } + _ => Err(e.to_string()), + }, } - info!(repo = %reads.full(), written, "Deploys backfill: repository read"); - Ok(RepoBackfill::Done) } -async fn mark(state: &WorkerState, team_id: &str, sk: &str, extra: &[(&str, AttributeValue)]) { +/// SET (and REMOVE) attributes of one settings item, creating it when new. +async fn update( + state: &WorkerState, + team_id: &str, + sk: &str, + sets: &[(&str, AttributeValue)], + removes: &[&str], +) { let mut req = state .dynamo - .put_item() + .update_item() .table_name(&state.config.settings_table_name) - .item("pk", av(team_id)) - .item("sk", av(sk)) - .item("at", av(&Utc::now().to_rfc3339())); - for (k, v) in extra { - req = req.item(*k, v.clone()); + .key("pk", av(team_id)) + .key("sk", av(sk)); + let mut set = vec!["#at = :at".to_string()]; + req = req + .expression_attribute_names("#at", "at") + .expression_attribute_values(":at", av(&Utc::now().to_rfc3339())); + for (i, (k, v)) in sets.iter().enumerate() { + set.push(format!("#s{i} = :s{i}")); + req = req + .expression_attribute_names(format!("#s{i}"), *k) + .expression_attribute_values(format!(":s{i}"), v.clone()); } - if let Err(e) = req.send().await { + let mut expr = format!("SET {}", set.join(", ")); + if !removes.is_empty() { + let names: Vec = (0..removes.len()).map(|i| format!("#r{i}")).collect(); + for (i, k) in removes.iter().enumerate() { + req = req.expression_attribute_names(format!("#r{i}"), *k); + } + expr.push_str(&format!(" REMOVE {}", names.join(", "))); + } + if let Err(e) = req.update_expression(expr).send().await { warn!(sk, error = %e, "Deploys backfill: could not write a marker"); } } -async fn queue_next_pass(state: &WorkerState, team_id: &str) { - if state.config.ticket_queue_url.is_empty() { - return; +const CURSOR_FIELDS: [&str; 3] = ["cursor_from", "cursor_to", "cursor_page"]; + +/// Marks a repository finished: read, no access, gone, or not read. +async fn finish_repo(state: &WorkerState, team_id: &str, sk: &str, how: &str, reason: &str) { + let mut sets = vec![("read_state", av(how))]; + if how == "no_access" { + sets.push(("no_access", AttributeValue::Bool(true))); } - let body = json!({"type": "deploy_stats_backfill", "team_id": team_id}).to_string(); - if let Err(e) = state - .sqs - .send_message() - .queue_url(&state.config.ticket_queue_url) - .message_body(body) + if !reason.is_empty() { + sets.push(("reason", av(reason))); + } + update(state, team_id, sk, &sets, &CURSOR_FIELDS).await; +} + +/// Takes the team's lease for this pass: free, expired, or already this +/// pass's own (a pass the backfill queued for itself). None while another +/// pass holds it; else when GitHub's rate limit lets reading resume (epoch +/// seconds, 0 when it isn't waiting). +async fn claim_lease( + state: &WorkerState, + team_id: &str, + lease: &str, +) -> Result, String> { + let now = Utc::now().timestamp(); + let r = state + .dynamo + .update_item() + .table_name(&state.config.settings_table_name) + .key("pk", av(team_id)) + .key("sk", av(ds::BACKFILL_PROGRESS_SK)) + .update_expression("SET #l = :l, #u = :u") + .condition_expression("attribute_not_exists(#u) OR #u < :now OR #l = :l") + .expression_attribute_names("#l", "lease") + .expression_attribute_names("#u", "lease_until") + .expression_attribute_values(":l", av(lease)) + .expression_attribute_values(":u", num(now + LEASE_SECS)) + .expression_attribute_values(":now", num(now)) + .return_values(aws_sdk_dynamodb::types::ReturnValue::AllNew) .send() - .await - { - warn!(error = %e, "Deploys backfill: could not queue the next pass"); + .await; + match r { + Ok(out) => Ok(Some( + out.attributes() + .and_then(|a| a.get("resume_at")) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0), + )), + Err(e) + if e.as_service_error() + .is_some_and(|s| s.is_conditional_check_failed_exception()) => + { + Ok(None) + } + Err(e) => Err(format!("claim the backfill lease: {e}")), + } +} + +async fn progress(state: &WorkerState, team_id: &str, sets: &[(&str, AttributeValue)]) { + update(state, team_id, ds::BACKFILL_PROGRESS_SK, sets, &[]).await; +} + +/// How a pass ended. +enum PassEnd { + /// Every repository read or named: the team is marked done. + Finished, + /// Continue in another pass after this many seconds. + Again(u64), +} + +/// Queues the pass that continues this one, holding the lease until it runs. +/// Lets the lease go when it can't be queued, so the next ask starts over. +async fn queue_next_pass(state: &WorkerState, team_id: &str, lease: &str, delay: u64) { + let delay = delay.min(MAX_DELAY_SECS); + let until = Utc::now().timestamp() + delay as i64 + LEASE_SECS; + progress(state, team_id, &[("lease_until", num(until))]).await; + let body = serde_json::to_string(&crate::models::WorkerMessage::DeployStatsBackfill( + DeployStatsBackfillMessage { + team_id: team_id.to_string(), + lease: Some(lease.to_string()), + }, + )) + .unwrap_or_default(); + if !send(state, body, delay).await { + progress(state, team_id, &[("lease_until", num(0))]).await; } } /// Reads a team's deploys of the last `BACKFILL_DAYS` from GitHub's run -/// history. Safe to repeat: a record is keyed by its run, each repository is -/// marked when read, and a pass that runs out of time queues the next one. -/// The team is marked done only when every repository was read. -pub async fn backfill(state: &WorkerState, team_id: &str) -> Result<(), String> { - let table = &state.config.settings_table_name; - let started = Instant::now(); +/// history. Safe to repeat: a record is keyed by its run, each repository +/// saves its cursor after every page, and one pass reads at a time. A pass +/// that runs out of time, or that GitHub's rate limit pauses, queues the +/// next one; the team is marked done once every repository is read or named +/// as not readable. +pub async fn backfill(state: &WorkerState, msg: &DeployStatsBackfillMessage) -> Result<(), String> { + let team_id = msg.team_id.as_str(); let done = state .dynamo .get_item() - .table_name(table) + .table_name(&state.config.settings_table_name) .key("pk", av(team_id)) .key("sk", av(ds::BACKFILL_MARKER_SK)) .send() @@ -442,125 +948,394 @@ pub async fn backfill(state: &WorkerState, team_id: &str) -> Result<(), String> if done.item().is_some() { return Ok(()); } + let lease = msg + .lease + .clone() + .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); + let Some(resume_at) = claim_lease(state, team_id, &lease).await? else { + info!(team_id, "Deploys backfill: another pass is reading"); + return Ok(()); + }; + // GitHub asked for a longer wait than one queued delay covers: wait on + // without asking it anything. + let wait = resume_at - Utc::now().timestamp(); + if wait > 0 { + queue_next_pass(state, team_id, &lease, wait as u64).await; + return Ok(()); + } + match backfill_pass(state, team_id).await { + Ok(PassEnd::Finished) => { + update( + state, + team_id, + ds::BACKFILL_PROGRESS_SK, + &[], + &["lease", "lease_until"], + ) + .await; + Ok(()) + } + Ok(PassEnd::Again(delay)) => { + queue_next_pass(state, team_id, &lease, delay).await; + Ok(()) + } + Err(e) => { + progress(state, team_id, &[("lease_until", num(0))]).await; + Err(e) + } + } +} + +async fn backfill_pass(state: &WorkerState, team_id: &str) -> Result { + let table = &state.config.settings_table_name; + let started = Instant::now(); + let out_of_time = move || started.elapsed().as_secs() > PASS_BUDGET_SECS; let Some(github) = super::plan_chat::github_for(state, team_id).await else { return Err("no GitHub installation for the team".into()); }; - let bot = github - .app_bot_login() - .await - .map_err(|e| format!("bot login: {e}"))?; - let since = Utc::now() - Duration::days(ds::BACKFILL_DAYS); + let bot = match github.app_bot_login().await { + Ok(b) => b, + Err(e) => { + return match rate_limited(&*e) { + Some(wait) => Ok(PassEnd::Again(wait)), + None => Err(format!("bot login: {e}")), + } + } + }; + // Below the background share of the budget: wait for the reset before + // spending anything. + if let Some(wait) = github.background_wait() { + info!( + team_id, + wait, "Deploys backfill: leaving GitHub's budget to live work" + ); + progress( + state, + team_id, + &[("resume_at", num(Utc::now().timestamp() + wait as i64))], + ) + .await; + return Ok(PassEnd::Again(wait)); + } + let requests = AtomicUsize::new(0); + let now = Utc::now(); + let since = now - Duration::days(ds::BACKFILL_DAYS); let repos = super::plan::fetch_team_repo_list(state, team_id).await; - let (mut no_access, mut failed) = (Vec::::new(), 0usize); + let total = repos.len(); + let mut read = 0usize; + let mut no_access = Vec::::new(); + let mut not_read = HashMap::::new(); + let mut retry_later = false; + let counts = |read: usize| [("repos_total", num(total)), ("repos_read", num(read))]; for repo in &repos { let Some((owner, name)) = repo.full_name.split_once('/') else { + read += 1; continue; }; - let repo_sk = format!( - "{}{}", - ds::BACKFILL_REPO_PREFIX, - repo.full_name.to_ascii_lowercase() + let sk = repo_sk(&repo.full_name); + let mark = RepoMark::from_item( + state + .dynamo + .get_item() + .table_name(table) + .key("pk", av(team_id)) + .key("sk", av(&sk)) + .send() + .await + .ok() + .and_then(|r| r.item().cloned()) + .as_ref(), ); - let prior = state - .dynamo - .get_item() - .table_name(table) - .key("pk", av(team_id)) - .key("sk", av(&repo_sk)) - .send() - .await - .ok() - .and_then(|r| r.item().cloned()); - if let Some(p) = prior { - if p.get("no_access").and_then(|v| v.as_bool().ok()) == Some(&true) { - no_access.push(repo.full_name.clone()); + match mark.state { + RepoState::Done | RepoState::Gone => { + read += 1; + continue; } - continue; - } - let mut reads = match repo_reads(state, team_id, &github, owner, name, &bot).await { - Ok(r) => r, - Err(e) if crate::clients::github::is_not_found(&*e) => { - // Gone or no longer installed: nothing to read. - mark( - state, - team_id, - &repo_sk, - &[("gone", AttributeValue::Bool(true))], - ) - .await; + RepoState::NoAccess => { + no_access.push(repo.full_name.clone()); + read += 1; continue; } - Err(e) => { - warn!(repo = %repo.full_name, error = %e, "Deploys backfill: could not read the repository"); - failed += 1; + RepoState::NotRead => { + not_read.insert(repo.full_name.clone(), av(&mark.reason)); + read += 1; continue; } + RepoState::New | RepoState::Reading => {} + } + if out_of_time() { + progress(state, team_id, &counts(read)).await; + return Ok(PassEnd::Again(0)); + } + let mut progressed = false; + let outcome = match live_reads(state, team_id, &github, &requests, owner, name, &bot).await + { + Ok(mut reads) => { + backfill_repo( + &mut reads, + Cursor::resume(mark.cursor.as_ref(), since, now), + now, + &out_of_time, + &mut progressed, + ) + .await + } + Err(e) => Err(e), }; - match backfill_repo(state, team_id, &mut reads, since, started).await { - Ok(RepoBackfill::Done) => mark(state, team_id, &repo_sk, &[]).await, + match outcome { + Ok(RepoBackfill::Done) => { + finish_repo(state, team_id, &sk, "done", "").await; + read += 1; + } Ok(RepoBackfill::NoAccess) => { + finish_repo(state, team_id, &sk, "no_access", "").await; no_access.push(repo.full_name.clone()); - mark( - state, - team_id, - &repo_sk, - &[("no_access", AttributeValue::Bool(true))], - ) - .await; + read += 1; } Ok(RepoBackfill::OutOfTime) => { info!( team_id, "Deploys backfill: out of time, continuing in the next pass" ); - queue_next_pass(state, team_id).await; - return Ok(()); + progress(state, team_id, &counts(read)).await; + return Ok(PassEnd::Again(0)); + } + Ok(RepoBackfill::Headroom(wait)) => { + info!( + team_id, + wait, "Deploys backfill: leaving GitHub's budget to live work" + ); + let mut sets = counts(read).to_vec(); + sets.push(("resume_at", num(Utc::now().timestamp() + wait as i64))); + progress(state, team_id, &sets).await; + return Ok(PassEnd::Again(wait)); + } + Ok(RepoBackfill::Capped) => { + info!( + team_id, + requests = requests.load(Ordering::Relaxed), + "Deploys backfill: the pass made its most requests" + ); + progress(state, team_id, &counts(read)).await; + return Ok(PassEnd::Again(CAP_DELAY_SECS)); + } + // Gone or no longer installed: nothing to read. + Err(e) if is_not_found(&*e) => { + finish_repo(state, team_id, &sk, "gone", "").await; + read += 1; } Err(e) => { - warn!(repo = %repo.full_name, error = %e, "Deploys backfill: could not read run history"); - failed += 1; + let message = e.to_string(); + match after_error(rate_limited(&*e), &message, &mark, progressed) { + AfterError::Pause(wait) => { + let pauses = if progressed { 1 } else { mark.pauses + 1 }; + update( + state, + team_id, + &sk, + &[("read_state", av("reading")), ("pauses", num(pauses))], + &[], + ) + .await; + info!(team_id, repo = %repo.full_name, wait, "Deploys backfill: paused by GitHub's rate limit"); + let resume_at = Utc::now().timestamp() + wait as i64; + let mut sets = counts(read).to_vec(); + sets.push(("resume_at", num(resume_at))); + progress(state, team_id, &sets).await; + return Ok(PassEnd::Again(wait)); + } + AfterError::Retry => { + let attempts = if progressed { 1 } else { mark.attempts + 1 }; + warn!(repo = %repo.full_name, attempts, error = %message, "Deploys backfill: could not read run history; trying again"); + update( + state, + team_id, + &sk, + &[ + ("read_state", av("reading")), + ("attempts", num(attempts)), + ("reason", av(&plain_reason(&message))), + ], + &[], + ) + .await; + retry_later = true; + } + AfterError::GiveUp(reason) => { + warn!(repo = %repo.full_name, error = %message, "Deploys backfill: giving up on a repository"); + finish_repo(state, team_id, &sk, "not_read", &reason).await; + not_read.insert(repo.full_name.clone(), av(&reason)); + read += 1; + } + } } } + progress(state, team_id, &counts(read)).await; } - if failed > 0 { - return Err(format!( - "{failed} repositories could not be read; the next request continues" - )); + progress(state, team_id, &counts(read)).await; + if retry_later { + return Ok(PassEnd::Again(RETRY_DELAY_SECS)); } - let mut extra = vec![ - ( - "since", - av(&since.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)), - ), - ("repos", AttributeValue::N(repos.len().to_string())), - ]; + let mut req = state + .dynamo + .put_item() + .table_name(table) + .item("pk", av(team_id)) + .item("sk", av(ds::BACKFILL_MARKER_SK)) + .item("at", av(&Utc::now().to_rfc3339())) + .item("since", av(&secs(since))) + .item("repos", num(total)); if !no_access.is_empty() { - extra.push(("no_access", AttributeValue::Ss(no_access))); + req = req.item("no_access", AttributeValue::Ss(no_access)); + } + if !not_read.is_empty() { + req = req.item("not_read", AttributeValue::M(not_read)); } - mark(state, team_id, ds::BACKFILL_MARKER_SK, &extra).await; - info!(team_id, repos = repos.len(), "Deploys backfill done"); - Ok(()) + req.send() + .await + .map_err(|e| format!("write backfill marker: {e}"))?; + info!(team_id, repos = total, "Deploys backfill done"); + Ok(PassEnd::Finished) } #[cfg(test)] mod tests { use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + + const BOT: &str = "coderhelm[bot]"; + + fn t(s: &str) -> DateTime { + parse_time(s).unwrap() + } #[test] fn the_backfill_reads_the_whole_window_a_week_at_a_time() { - let now = chrono::DateTime::parse_from_rfc3339("2026-11-05T12:00:00Z") - .unwrap() - .with_timezone(&Utc); + let now = t("2026-11-05T12:00:00Z"); let since = now - Duration::days(ds::BACKFILL_DAYS); - let r = created_ranges(since, now); - assert_eq!(r.len(), 26); - assert_eq!(r[0], "2026-05-07T12:00:00Z..2026-05-14T12:00:00Z"); - assert!(r.last().unwrap().ends_with("..2026-11-05T12:00:00Z")); + let mut ranges = Vec::new(); + let mut c = Cursor::first(since, now); + while let Some(x) = c { + ranges.push(x.created()); + c = x.next(now); + } + assert_eq!(ranges.len(), 26); + assert_eq!(ranges[0], "2026-05-07T12:00:00Z..2026-05-14T12:00:00Z"); + assert!(ranges.last().unwrap().ends_with("..2026-11-05T12:00:00Z")); // Each range starts where the last ended: nothing skipped. - for w in r.windows(2) { + for w in ranges.windows(2) { assert_eq!(w[0].split("..").nth(1), w[1].split("..").next()); } - assert!(created_ranges(now, now).is_empty()); + assert!(Cursor::first(now, now).is_none()); + } + + #[test] + fn a_read_resumes_from_its_saved_page() { + let now = t("2026-11-05T12:00:00Z"); + let since = now - Duration::days(ds::BACKFILL_DAYS); + let saved = Cursor { + from: t("2026-08-01T00:00:00Z"), + to: t("2026-08-08T00:00:00Z"), + page: 4, + }; + // The saved page, not the window's start. + assert_eq!( + Cursor::resume(Some(&saved), since, now), + Some(saved.clone()) + ); + // A cursor that fell out of the window starts over at its start. + let old = Cursor { + from: since - Duration::days(30), + to: since - Duration::days(23), + page: 2, + }; + assert_eq!( + Cursor::resume(Some(&old), since, now), + Cursor::first(since, now) + ); + assert_eq!(Cursor::resume(None, since, now), Cursor::first(since, now)); + // Saved and read back from the marker. + let item: Item = HashMap::from([ + ("read_state".to_string(), av("reading")), + ("cursor_from".to_string(), av("2026-08-01T00:00:00Z")), + ("cursor_to".to_string(), av("2026-08-08T00:00:00Z")), + ("cursor_page".to_string(), num(4)), + ("attempts".to_string(), num(1)), + ]); + let m = RepoMark::from_item(Some(&item)); + assert_eq!(m.state, RepoState::Reading); + assert_eq!(m.cursor, Some(saved)); + assert_eq!(m.attempts, 1); + } + + #[test] + fn markers_from_before_the_cursor_still_read_as_finished() { + assert_eq!(RepoMark::from_item(None).state, RepoState::New); + let done: Item = HashMap::from([("at".to_string(), av("x"))]); + assert_eq!(RepoMark::from_item(Some(&done)).state, RepoState::Done); + let no: Item = HashMap::from([("no_access".to_string(), AttributeValue::Bool(true))]); + assert_eq!(RepoMark::from_item(Some(&no)).state, RepoState::NoAccess); + let gone: Item = HashMap::from([("gone".to_string(), AttributeValue::Bool(true))]); + assert_eq!(RepoMark::from_item(Some(&gone)).state, RepoState::Gone); + let given_up: Item = HashMap::from([ + ("read_state".to_string(), av("not_read")), + ("reason".to_string(), av("GitHub answered 502 Bad Gateway")), + ]); + let m = RepoMark::from_item(Some(&given_up)); + assert_eq!(m.state, RepoState::NotRead); + assert_eq!(m.reason, "GitHub answered 502 Bad Gateway"); + } + + #[test] + fn a_range_with_more_runs_than_github_lists_is_halved() { + let c = Cursor { + from: t("2026-08-01T00:00:00Z"), + to: t("2026-08-08T00:00:00Z"), + page: 1, + }; + let h = c.halved().unwrap(); + assert_eq!(h.created(), "2026-08-01T00:00:00Z..2026-08-04T12:00:00Z"); + let hour = Cursor { + from: c.from, + to: c.from + Duration::hours(1), + page: 1, + }; + assert!(hour.halved().is_none()); + } + + #[test] + fn failures_are_bounded_and_rate_limits_pause() { + let fresh = RepoMark::default(); + let msg = "HTTP status server error (502 Bad Gateway) for url (u)"; + // A rate limit is a pause, never a failure. + assert_eq!( + after_error(Some(300), "x", &fresh, false), + AfterError::Pause(300) + ); + assert_eq!(after_error(None, msg, &fresh, false), AfterError::Retry); + let twice = RepoMark { + attempts: MAX_REPO_ATTEMPTS - 1, + ..Default::default() + }; + assert_eq!( + after_error(None, msg, &twice, false), + AfterError::GiveUp("GitHub answered 502 Bad Gateway".into()) + ); + // A pass that read pages before failing starts the count again. + assert_eq!(after_error(None, msg, &twice, true), AfterError::Retry); + let stuck = RepoMark { + pauses: MAX_REPO_PAUSES - 1, + ..Default::default() + }; + assert!(matches!( + after_error(Some(60), "x", &stuck, false), + AfterError::GiveUp(_) + )); + assert_eq!( + after_error(Some(60), "x", &stuck, true), + AfterError::Pause(60) + ); } #[test] @@ -570,7 +1345,291 @@ mod tests { let limited: GhError = "HTTP status client error (403 Forbidden) for url (u): API rate limit exceeded".into(); assert!(!is_no_access(&*limited)); + assert!(rate_limited(&*limited).is_some()); let gone: GhError = "HTTP status client error (404 Not Found) for url (u)".into(); assert!(!is_no_access(&*gone)); } + + /// A fake GitHub: run history by `created` range and page, workflow + /// files by path, and every request it was asked. + #[derive(Default)] + struct Fake { + runs: HashMap<(String, u32), Value>, + workflows: HashMap>, + asked: Mutex>, + workflow_reads: AtomicUsize, + saved: Mutex>, + deploys: AtomicUsize, + /// Requests containing this answer with GitHub's rate limit. + limit_on: Option, + /// The installation's budget as GitHub's last response said (the + /// clock reads 1,000). + budget: Mutex>, + /// Requests the pass made before this repository. + extra_requests: usize, + } + + fn limited() -> GhError { + "HTTP status client error (429 Too Many Requests) for url (u)".into() + } + + #[async_trait::async_trait] + impl Source for &Fake { + async fn get(&self, rest: &str) -> Result { + self.asked.lock().unwrap().push(rest.to_string()); + if self.limit_on.as_deref().is_some_and(|l| rest.contains(l)) { + return Err(limited()); + } + if rest.starts_with("actions/runs?") { + let created = rest + .split("created=") + .nth(1) + .and_then(|s| s.split('&').next()) + .map(|s| urlencoding::decode(s).unwrap().into_owned()) + .unwrap(); + let page: u32 = rest.rsplit("page=").next().unwrap().parse().unwrap(); + return Ok(self + .runs + .get(&(created, page)) + .cloned() + .unwrap_or(json!({"total_count": 0, "workflow_runs": []}))); + } + if rest.contains("/jobs") { + return Ok(json!({"jobs": [{"name": "deploy", "conclusion": "success"}]})); + } + Err("HTTP status client error (404 Not Found) for url (u)".into()) + } + + async fn workflow_jobs(&self, path: &str) -> Result>, GhError> { + self.workflow_reads.fetch_add(1, Ordering::SeqCst); + Ok(self.workflows.get(path).cloned()) + } + + async fn save_deploy(&self, _item: Item) -> bool { + self.deploys.fetch_add(1, Ordering::SeqCst); + true + } + + async fn save_cursor(&self, cursor: &Cursor) { + self.saved.lock().unwrap().push(cursor.clone()); + } + + fn headroom_wait(&self) -> Option { + crate::clients::github::background_wait(*self.budget.lock().unwrap(), 1_000) + } + + fn requests(&self) -> usize { + self.asked.lock().unwrap().len() + self.extra_requests + } + } + + fn bot_run(id: u64, event: &str, branch: &str, name: &str, path: &str) -> Value { + json!({ + "id": id, "event": event, "head_branch": branch, "name": name, + "path": path, "status": "completed", "conclusion": "success", + "head_sha": "abc", "created_at": "2026-10-30T01:02:03Z", + "actor": {"login": BOT, "type": "Bot"}, + "triggering_actor": {"login": BOT, "type": "Bot"}, + }) + } + + fn reads(f: &Fake) -> RepoReads<&Fake> { + RepoReads::new( + f, + "TEAM#t".into(), + "acme/web".into(), + BOT.into(), + "main".into(), + HashMap::new(), + ) + } + + #[tokio::test] + async fn a_run_that_cannot_deploy_costs_no_request_of_its_own() { + let mut f = Fake::default(); + f.workflows.insert( + ".github/workflows/ci.yml".into(), + vec![JobDef { + key: "test".into(), + name: "test".into(), + environment: String::new(), + }], + ); + let mut r = reads(&f); + // CoderHelm's pushes to its own PR branch, a CI workflow: no tag + // lookup, no jobs read, and the workflow file read once. + for id in 0..50 { + let run = bot_run( + id, + "push", + "coderhelm/fix-1", + "CI", + ".github/workflows/ci.yml", + ); + assert_eq!(r.record(&run).await.unwrap(), 0); + } + assert!(f.asked.lock().unwrap().is_empty(), "{:?}", f.asked); + assert_eq!(f.workflow_reads.load(Ordering::SeqCst), 1); + // A person's run is never read further. + let mut person = bot_run(99, "push", "main", "Deploy", "d.yml"); + person["triggering_actor"] = json!({"login": "someone", "type": "User"}); + assert_eq!(r.record(&person).await.unwrap(), 0); + assert_eq!(f.workflow_reads.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn a_deploy_run_is_recorded_and_its_tag_asked_once() { + let f = Fake::default(); + let mut r = reads(&f); + for id in 0..3 { + let run = bot_run(id, "push", "v1.2.3", "Deploy production", "deploy.yml"); + assert_eq!(r.record(&run).await.unwrap(), 1); + } + let asked = f.asked.lock().unwrap().clone(); + assert_eq!( + asked + .iter() + .filter(|a| a.starts_with("git/ref/tags/")) + .count(), + 1 + ); + assert_eq!(asked.iter().filter(|a| a.contains("/jobs")).count(), 3); + assert_eq!(f.deploys.load(Ordering::SeqCst), 3); + } + + #[tokio::test] + async fn a_rate_limit_stops_the_read_with_its_cursor_saved() { + let now = t("2026-11-05T12:00:00Z"); + let start = Cursor { + from: t("2026-10-20T00:00:00Z"), + to: t("2026-10-27T00:00:00Z"), + page: 1, + }; + let full: Vec = (0..100) + .map(|i| bot_run(i, "push", "fix", "CI", "ci.yml")) + .collect(); + let mut f = Fake { + limit_on: Some("page=2".into()), + ..Default::default() + }; + f.runs.insert( + (start.created(), 1), + json!({"total_count": 150, "workflow_runs": full}), + ); + let mut r = reads(&f); + let mut progressed = false; + let e = backfill_repo(&mut r, Some(start.clone()), now, &|| false, &mut progressed) + .await + .unwrap_err(); + // A pause, not a failure: the pass requeues and continues at page 2. + assert!(rate_limited(&*e).is_some()); + assert!(progressed); + let saved = f.saved.lock().unwrap().clone(); + assert_eq!( + saved.last(), + Some(&Cursor { + page: 2, + ..start.clone() + }) + ); + assert_eq!( + after_error( + rate_limited(&*e), + &e.to_string(), + &RepoMark::default(), + true + ), + AfterError::Pause(60) + ); + // The next pass picks up at that page and reads to the end. + let f2 = Fake::default(); + let mut r2 = reads(&f2); + let mut p2 = false; + let resumed = Cursor::resume(saved.last(), now - Duration::days(182), now); + let end = backfill_repo(&mut r2, resumed, now, &|| false, &mut p2) + .await + .unwrap(); + assert_eq!(end, RepoBackfill::Done); + let asked = f2.asked.lock().unwrap().clone(); + assert!(asked[0].contains("page=2"), "{asked:?}"); + assert!(asked[0].contains(&urlencoding::encode(&start.created()).into_owned())); + // Then the weeks after it, up to now. + assert!(asked.len() >= 2); + } + + /// The backfill took an installation's whole hourly budget and every + /// live job failed for an hour. Background reads yield at half. + #[tokio::test] + async fn a_pass_yields_when_the_budget_is_down_to_half() { + use crate::clients::github::Budget; + let now = t("2026-11-05T12:00:00Z"); + let start = Cursor::first(now - Duration::days(30), now).unwrap(); + let f = Fake::default(); + *f.budget.lock().unwrap() = Some(Budget { + remaining: 2_400, + limit: 5_000, + reset: 1_000 + 1_800, + }); + let mut r = reads(&f); + let mut progressed = false; + let end = backfill_repo(&mut r, Some(start.clone()), now, &|| false, &mut progressed) + .await + .unwrap(); + // Not a request spent: wait for the reset. + assert_eq!(end, RepoBackfill::Headroom(1_800)); + assert!(f.asked.lock().unwrap().is_empty()); + assert!(!progressed); + // With headroom it reads. + *f.budget.lock().unwrap() = Some(Budget { + remaining: 2_500, + limit: 5_000, + reset: 2_800, + }); + let end = backfill_repo(&mut r, Some(start), now, &|| false, &mut progressed) + .await + .unwrap(); + assert_eq!(end, RepoBackfill::Done); + assert!(!f.asked.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn a_pass_stops_at_its_most_requests() { + let now = t("2026-11-05T12:00:00Z"); + let start = Cursor::first(now - Duration::days(30), now).unwrap(); + let f = Fake { + extra_requests: MAX_PASS_REQUESTS - 2, + ..Default::default() + }; + let mut r = reads(&f); + let mut progressed = false; + let end = backfill_repo(&mut r, Some(start.clone()), now, &|| false, &mut progressed) + .await + .unwrap(); + assert_eq!(end, RepoBackfill::Capped); + // Two pages read, then it stops with the next one saved. + assert_eq!(f.asked.lock().unwrap().len(), 2); + let next = start.next(now).and_then(|c| c.next(now)).unwrap(); + assert_eq!(f.saved.lock().unwrap().last(), Some(&next)); + } + + #[tokio::test] + async fn out_of_time_keeps_the_cursor_for_the_next_pass() { + let now = t("2026-11-05T12:00:00Z"); + let start = Cursor::first(now - Duration::days(30), now).unwrap(); + let f = Fake::default(); + let mut r = reads(&f); + let calls = AtomicUsize::new(0); + // Time runs out after the first range. + let out = || calls.fetch_add(1, Ordering::SeqCst) >= 1; + let mut progressed = false; + let end = backfill_repo(&mut r, Some(start.clone()), now, &out, &mut progressed) + .await + .unwrap(); + assert_eq!(end, RepoBackfill::OutOfTime); + assert_eq!( + f.saved.lock().unwrap().last(), + start.next(now).as_ref(), + "the next week is where the next pass starts" + ); + } }