1mod checks;
12mod issues;
13mod pulls;
14
15use super::token;
16use crate::config;
17use crate::engine::cooldown as engine_cooldown;
18use crate::engine::cooldown;
19use crate::security;
20use anyhow::Context;
21use base64::Engine;
22use base64::engine::general_purpose::STANDARD as BASE64;
23pub(crate) use checks::{
24 REQUIRED_CHECK_RULESET_NAME, RulesetCreateKind, classify_ruleset_create_error,
25};
26pub use pulls::{CommitMeta, PrReviewBatchData};
27use reqwest::{Client, Response, StatusCode, header};
28use serde::de::DeserializeOwned;
29use std::any;
30use std::cmp::Reverse;
31use std::collections::HashMap;
32use std::error::Error as _;
33use std::fmt;
34use std::fmt::Debug;
35use std::fmt::Formatter;
36use std::fmt::Write as _;
37use std::sync::LazyLock;
38use std::sync::{
39 Arc, Mutex, OnceLock,
40 atomic::{AtomicU64, Ordering},
41};
42use std::time as std_time;
43use std::time::SystemTime;
44use std::time::{Duration, Instant};
45use tokio::runtime::Handle;
46use tokio::time;
47use urlencoding;
48
49#[cfg(not(test))]
50const GITHUB_API: &str = "https://api.github.com";
51#[cfg(test)]
53const GITHUB_API: &str = "http://127.0.0.1:9";
54
55const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
57const READ_TIMEOUT: Duration = Duration::from_secs(if cfg!(test) { 1 } else { 10 });
59const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
60const TCP_KEEPALIVE: Duration = Duration::from_secs(30);
61const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
62const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(15);
64const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(5);
65
66#[derive(Debug, serde::Deserialize)]
67struct BlockedByPayload {
68 #[serde(default)]
69 id: i64,
70 number: i64,
71 #[serde(default)]
72 state: String,
73 #[serde(default)]
74 state_reason: Option<String>,
75 #[serde(default)]
76 repository: Option<BlockedByRepoPayload>,
77}
78
79#[derive(Debug, serde::Deserialize)]
80struct BlockedByRepoPayload {
81 full_name: String,
82}
83
84pub(crate) fn is_full_commit_sha(sha: &str) -> bool {
85 let len = sha.len();
86 (len == 40 || len == 64) && sha.bytes().all(|b| b.is_ascii_hexdigit())
87}
88
89fn graphql_timeout(query: &str) -> Duration {
90 if query.trim_start().starts_with("query") {
91 READ_TIMEOUT
92 } else {
93 REQUEST_TIMEOUT
94 }
95}
96
97fn github_retry_attempts() -> u32 {
98 #[cfg(test)]
99 {
100 let n = TEST_RETRY_ATTEMPTS.load(Ordering::Relaxed);
101 if n > 0 {
102 return u32::try_from(n).unwrap_or(3);
103 }
104 }
105 config::get("gh.5xx.retry_attempts")
106 .ok()
107 .and_then(|v| v.parse::<u32>().ok())
108 .unwrap_or(3)
109}
110
111fn repo_from_url(url: &str) -> Option<String> {
114 let rest = url.split_once("/repos/")?.1;
115 let mut parts = rest.split(['/', '?']);
116 let owner = parts.next().filter(|s| !s.is_empty())?;
117 let name = parts.next().filter(|s| !s.is_empty())?;
118 Some(format!("{owner}/{name}"))
119}
120
121pub(crate) fn redact_posted_body(body: &str) -> String {
122 if !security::has_leaks(body) {
123 return body.to_string();
124 }
125 let leaks = security::scan(body);
126 let rules: Vec<&str> = leaks.iter().map(|leak| leak.rule).collect();
127 let warning = format!(
128 "\n\n> ⚠️ **Security Notice**: {} potential secret(s) detected and redacted: {}",
129 leaks.len(),
130 rules.join(", ")
131 );
132 format!("{}{warning}", security::redact(body))
133}
134
135fn merge_pr_body(head_sha: &str) -> serde_json::Value {
136 serde_json::json!({
137 "merge_method": "squash",
138 "sha": head_sha,
139 })
140}
141
142fn parse_positive_issue_number(number: &str) -> anyhow::Result<i64> {
143 let parsed = number
144 .parse::<i64>()
145 .with_context(|| format!("invalid issue number: {number}"))?;
146 if parsed <= 0 {
147 anyhow::bail!("invalid issue number: {number}");
148 }
149 Ok(parsed)
150}
151
152struct RateLimit {
156 remaining: Option<u32>,
158 reset_at: Option<u64>,
160 backoff_until: Option<Instant>,
162 backoff_delay: Duration,
163 backoff_base: Duration,
164 backoff_max: Duration,
165 throttle_threshold: u32,
168}
169
170impl RateLimit {
171 fn new() -> Self {
172 let base = config::get("gh.backoff.base_seconds")
173 .ok()
174 .and_then(|v| v.parse::<u64>().ok())
175 .unwrap_or(30);
176 let max = config::get("gh.backoff.max_seconds")
177 .ok()
178 .and_then(|v| v.parse::<u64>().ok())
179 .unwrap_or(900);
180 let threshold = config::get("gh.rate_limit.throttle_threshold")
181 .ok()
182 .and_then(|v| v.parse::<u32>().ok())
183 .unwrap_or(200);
184
185 Self {
186 remaining: None,
187 reset_at: None,
188 backoff_until: None,
189 backoff_delay: Duration::ZERO,
190 backoff_base: Duration::from_secs(base),
191 backoff_max: Duration::from_secs(max),
192 throttle_threshold: threshold,
193 }
194 }
195
196 fn update_from_headers(&mut self, headers: &header::HeaderMap) {
198 if let Some(v) = headers.get("x-ratelimit-remaining") {
199 self.remaining = v.to_str().ok().and_then(|s| s.parse().ok());
200 }
201 if let Some(v) = headers.get("x-ratelimit-reset") {
202 self.reset_at = v.to_str().ok().and_then(|s| s.parse().ok());
203 }
204 }
205
206 fn record_success(&mut self) {
208 if self.backoff_delay > Duration::ZERO {
209 tracing::info!("GitHub backoff cleared after successful API call");
210 }
211 self.backoff_delay = Duration::ZERO;
212 self.backoff_until = None;
213 }
214
215 fn record_rate_limit(&mut self) {
217 METRIC_RATE_LIMIT_HITS.fetch_add(1, Ordering::Relaxed);
218
219 if let Some(reset_epoch) = self.reset_at {
221 match SystemTime::now().duration_since(std_time::UNIX_EPOCH) {
222 Ok(since_epoch) => {
223 let now_epoch = since_epoch.as_secs();
224 if reset_epoch > now_epoch {
225 let wait_secs = reset_epoch - now_epoch + 1;
226 self.backoff_delay = Duration::from_secs(wait_secs);
227 self.backoff_until = Some(Instant::now() + self.backoff_delay);
228 tracing::warn!(
229 wait_secs,
230 "GitHub rate limit hit, waiting until reset time"
231 );
232 return;
233 }
234 }
235 Err(e) => {
236 tracing::error!(
237 error = %e,
238 "System clock is before UNIX epoch; ignoring reset_at and falling back to exponential backoff"
239 );
240 }
241 }
242 }
243
244 self.backoff_delay = if self.backoff_delay.is_zero() {
246 self.backoff_base
247 } else {
248 (self.backoff_delay * 2).min(self.backoff_max)
249 };
250 self.backoff_until = Some(Instant::now() + self.backoff_delay);
251 tracing::warn!(
252 delay_secs = self.backoff_delay.as_secs(),
253 "GitHub rate limit hit, backing off (no reset header)"
254 );
255 }
256
257 fn backoff_remaining(&self) -> Option<Duration> {
259 if let Some(until) = self.backoff_until {
260 let now = Instant::now();
261 if now < until {
262 return Some(until - now);
263 }
264 }
265 None
266 }
267
268 fn proactive_wait_duration(&self) -> Option<Duration> {
275 if self.backoff_remaining().is_some() {
277 return None;
278 }
279 if let Some(remaining) = self.remaining
280 && remaining < self.throttle_threshold
281 && let Some(reset_epoch) = self.reset_at
282 {
283 let now_epoch = SystemTime::now()
284 .duration_since(std_time::UNIX_EPOCH)
285 .unwrap_or_default()
286 .as_secs();
287 if now_epoch < reset_epoch {
288 return Some(Duration::from_secs(reset_epoch - now_epoch + 1));
289 }
290 }
291 None
292 }
293
294 fn is_active(&self) -> Option<Duration> {
296 self.backoff_remaining()
297 .or_else(|| self.proactive_wait_duration())
298 }
299}
300
301static REST_RATE_LIMIT: LazyLock<Mutex<RateLimit>> = LazyLock::new(|| Mutex::new(RateLimit::new()));
304
305#[cfg(test)]
306static TEST_RETRY_ATTEMPTS: AtomicU64 = AtomicU64::new(0);
307
308static GRAPHQL_RATE_LIMIT: LazyLock<Mutex<RateLimit>> =
310 LazyLock::new(|| Mutex::new(RateLimit::new()));
311
312static METRIC_RATE_LIMIT_HITS: AtomicU64 = AtomicU64::new(0);
316static METRIC_PROACTIVE_THROTTLES: AtomicU64 = AtomicU64::new(0);
318static METRIC_5XX_HITS: AtomicU64 = AtomicU64::new(0);
320
321fn check_rate_limit_backoff(cell: &Mutex<RateLimit>, api: &str) -> anyhow::Result<()> {
331 let Some(remaining) = cell.lock().ok().and_then(|rl| rl.is_active()) else {
332 return Ok(());
333 };
334 METRIC_PROACTIVE_THROTTLES.fetch_add(1, Ordering::Relaxed);
335 anyhow::bail!(
336 "GitHub {} API rate-limited, skipping call for {}s",
337 api,
338 remaining.as_secs()
339 );
340}
341
342static CALL_COUNTS: LazyLock<Mutex<HashMap<(String, String), u64>>> =
344 LazyLock::new(|| Mutex::new(HashMap::new()));
345
346fn count_api_call(url: &str) {
349 let path = url.split('?').next().unwrap_or(url);
350 let key = match path.split_once("/repos/") {
351 Some((_, rest)) => {
352 let mut parts = rest.split('/');
353 let project = format!(
354 "{}/{}",
355 parts.next().unwrap_or(""),
356 parts.next().unwrap_or("")
357 );
358 (project, parts.next().unwrap_or("repo").to_string())
359 }
360 None if path.ends_with("/graphql") => ("-".to_string(), "graphql".to_string()),
361 None => ("-".to_string(), "other".to_string()),
362 };
363 if let Ok(mut counts) = CALL_COUNTS.lock() {
364 *counts.entry(key).or_insert(0) += 1;
365 }
366}
367
368pub fn drain_call_counts() -> Vec<(String, String, u64)> {
370 let mut rows: Vec<_> = CALL_COUNTS
371 .lock()
372 .map(|mut c| c.drain().map(|((p, k), n)| (p, k, n)).collect())
373 .unwrap_or_default();
374 rows.sort_by_key(|r| Reverse(r.2));
375 rows
376}
377
378struct CachedPage {
382 etag: String,
383 body: String,
384 next: Option<String>,
386}
387
388static PAGE_CACHE: LazyLock<Mutex<HashMap<String, CachedPage>>> =
396 LazyLock::new(|| Mutex::new(HashMap::new()));
397
398const PAGE_CACHE_MAX: usize = 256;
401
402fn page_cache_key<T>(url: &str, query: Option<&[(&str, &str)]>) -> Option<String> {
406 let mut key = String::from(any::type_name::<T>());
407 key.push(' ');
408 key.push_str(url);
409 if let Some(q) = query {
410 for (i, (k, v)) in q.iter().enumerate() {
411 key.push(if i == 0 { '?' } else { '&' });
412 key.push_str(k);
413 key.push('=');
414 key.push_str(v);
415 }
416 }
417 if key.contains("since=") {
418 return None;
419 }
420 Some(key)
421}
422
423fn page_cache_etag(key: &str) -> Option<String> {
424 PAGE_CACHE.lock().ok()?.get(key).map(|c| c.etag.clone())
425}
426
427fn page_cache_hit(key: &str) -> Option<(String, Option<String>)> {
429 let cache = PAGE_CACHE.lock().ok()?;
430 let entry = cache.get(key)?;
431 Some((entry.body.clone(), entry.next.clone()))
432}
433
434fn page_cache_store(key: String, etag: String, body: String, next: Option<String>) {
435 let Ok(mut cache) = PAGE_CACHE.lock() else {
436 return;
437 };
438 if cache.len() >= PAGE_CACHE_MAX && !cache.contains_key(&key) {
441 cache.clear();
442 }
443 cache.insert(key, CachedPage { etag, body, next });
444}
445
446fn maybe_record_body_rate_limit(cell: &Mutex<RateLimit>, status: StatusCode, body: &str) {
449 if is_forbidden_rate_limit(status, body)
450 && let Ok(mut rl) = cell.lock()
451 {
452 rl.record_rate_limit();
453 }
454}
455
456fn is_forbidden_rate_limit(status: StatusCode, body: &str) -> bool {
458 if status != StatusCode::FORBIDDEN {
459 return false;
460 }
461 let lower = body.to_lowercase();
462 lower.contains("rate limit")
463 || lower.contains("abuse detection")
464 || lower.contains("secondary rate")
465}
466
467fn record_response_for_limiter(cell: &Mutex<RateLimit>, resp: &Response) {
469 if let Ok(mut rl) = cell.lock() {
470 rl.update_from_headers(resp.headers());
471 if resp.status() == StatusCode::TOO_MANY_REQUESTS {
474 rl.record_rate_limit();
475 } else if resp.status().is_success() || resp.status() == StatusCode::NOT_MODIFIED {
476 rl.record_success();
477 }
478 }
479 let status = resp.status();
481 if status.is_server_error() {
482 METRIC_5XX_HITS.fetch_add(1, Ordering::Relaxed);
483 if Handle::try_current().is_ok() {
484 tokio::spawn(async move {
485 cooldown::record_github_5xx().await;
486 });
487 }
488 }
489}
490
491#[derive(Clone)]
498pub struct GhHttp {
499 client: Client,
500 token_resolver: Arc<token::TokenResolver>,
501 app: Option<Arc<super::app::AppAuth>>,
503 owner_only: bool,
505 cached_username: OnceLock<String>,
506 #[cfg(test)]
507 api_base: Option<String>,
508}
509
510impl Debug for GhHttp {
511 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
512 f.debug_struct("GhHttp")
513 .field("owner_only", &self.owner_only)
514 .finish_non_exhaustive()
515 }
516}
517
518fn transport_error_detail(e: &reqwest::Error) -> String {
521 let mut out = e.to_string();
522 let mut source = e.source();
523 while let Some(s) = source {
524 let _ = write!(out, ": {s}");
525 source = s.source();
526 }
527 let _ = write!(
528 out,
529 " (is_timeout={}, is_connect={})",
530 e.is_timeout(),
531 e.is_connect()
532 );
533 out
534}
535
536impl GhHttp {
537 pub fn new() -> anyhow::Result<Self> {
545 let client = Client::builder()
546 .user_agent("orch/0.1 (reqwest)")
547 .pool_max_idle_per_host(4)
548 .timeout(REQUEST_TIMEOUT)
549 .connect_timeout(CONNECT_TIMEOUT)
550 .tcp_keepalive(TCP_KEEPALIVE)
551 .pool_idle_timeout(POOL_IDLE_TIMEOUT)
552 .http2_keep_alive_interval(HTTP2_KEEP_ALIVE_INTERVAL)
553 .http2_keep_alive_timeout(HTTP2_KEEP_ALIVE_TIMEOUT)
554 .http2_keep_alive_while_idle(true)
555 .build()
556 .map_err(|e| anyhow::anyhow!("failed to build HTTP client (TLS init): {e}"))?;
557
558 Ok(Self {
559 client,
560 token_resolver: token::shared(),
561 app: None,
562 owner_only: false,
563 cached_username: OnceLock::new(),
564 #[cfg(test)]
565 api_base: None,
566 })
567 }
568
569 pub fn owner() -> anyhow::Result<Self> {
572 let mut gh = Self::new()?;
573 gh.owner_only = true;
574 Ok(gh)
575 }
576
577 #[cfg(test)]
578 pub(crate) fn for_test(api_base: String, app: Option<Arc<super::app::AppAuth>>) -> Self {
579 Self {
580 client: Client::new(),
581 token_resolver: Arc::new(token::TokenResolver::default_env()),
582 app,
583 owner_only: false,
584 cached_username: OnceLock::new(),
585 api_base: Some(api_base),
586 }
587 }
588
589 #[cfg_attr(
590 not(test),
591 expect(
592 clippy::unused_self,
593 reason = "only the test build reads the api base override"
594 )
595 )]
596 fn api_root(&self) -> &str {
597 #[cfg(test)]
598 if let Some(base) = &self.api_base {
599 return base;
600 }
601 GITHUB_API
602 }
603
604 pub fn is_rate_limited() -> Option<Duration> {
609 REST_RATE_LIMIT.lock().ok().and_then(|rl| rl.is_active())
610 }
611
612 fn check_backoff(url: &str) -> anyhow::Result<()> {
614 count_api_call(url);
615 check_rate_limit_backoff(&REST_RATE_LIMIT, "REST")
616 }
617
618 fn check_graphql_backoff(url: &str) -> anyhow::Result<()> {
620 count_api_call(url);
621 check_rate_limit_backoff(&GRAPHQL_RATE_LIMIT, "GraphQL")
622 }
623
624 fn record_response(resp: &Response) {
625 record_response_for_limiter(&REST_RATE_LIMIT, resp);
626 }
627
628 fn record_graphql_response(resp: &Response) {
629 record_response_for_limiter(&GRAPHQL_RATE_LIMIT, resp);
630 }
631
632 fn maybe_record_rate_limit_from_body(status: StatusCode, body: &str) {
634 maybe_record_body_rate_limit(&REST_RATE_LIMIT, status, body);
635 }
636
637 fn maybe_record_graphql_rate_limit_from_body(status: StatusCode, body: &str) {
639 maybe_record_body_rate_limit(&GRAPHQL_RATE_LIMIT, status, body);
640 }
641
642 fn record_success() {
643 if let Ok(mut rl) = REST_RATE_LIMIT.lock() {
644 rl.record_success();
645 }
646 }
647
648 fn app(&self) -> Option<Arc<super::app::AppAuth>> {
651 if self.owner_only {
652 return None;
653 }
654
655 self.app.clone()
658 }
659
660 async fn auth_header(&self, url: &str) -> anyhow::Result<String> {
663 if let (Some(app), Some(repo)) = (self.app(), repo_from_url(url)) {
664 match app.token_for_repo(&repo).await {
665 Ok(Some(token)) => return Ok(format!("Bearer {token}")),
666 Ok(None) => {}
667 Err(e) => {
668 tracing::warn!(error = %e, repo, "GitHub App token unavailable, using the owner token");
669 }
670 }
671 }
672 match self.token_resolver.get_token().await? {
673 Some(token) if !token.is_empty() => Ok(format!("Bearer {token}")),
674 _ => anyhow::bail!("No GitHub token available — run `gh auth login` or set GH_TOKEN"),
675 }
676 }
677
678 async fn send_with_retries<F>(
681 &self,
682 mut make_req: F,
683 is_graphql: bool,
684 ) -> anyhow::Result<Response>
685 where
686 F: FnMut() -> anyhow::Result<reqwest::RequestBuilder>,
687 {
688 if engine_cooldown::is_agent_in_cooldown("github:5xx") {
690 if let Some(until) = engine_cooldown::cooldown_until("github:5xx") {
691 let now = chrono::Utc::now().timestamp();
692 let remaining = if until > now { until - now } else { 0 };
693 anyhow::bail!("GitHub API transient 5xx circuit-breaker active for {remaining}s");
694 }
695 anyhow::bail!("GitHub API transient 5xx circuit-breaker active");
696 }
697
698 let attempts = github_retry_attempts();
700 let base_secs = config::get("gh.5xx.base_backoff_seconds")
701 .ok()
702 .and_then(|v| v.parse::<u64>().ok())
703 .unwrap_or(1);
704 let max_secs = config::get("gh.5xx.max_backoff_seconds")
705 .ok()
706 .and_then(|v| v.parse::<u64>().ok())
707 .unwrap_or(30);
708 let circuit_cooldown_secs = config::get("gh.5xx.circuit_breaker_cooldown_seconds")
709 .ok()
710 .and_then(|v| v.parse::<u64>().ok())
711 .unwrap_or(300);
712
713 let mut last_err: Option<anyhow::Error> = None;
714 let mut auth_override: Option<String> = None;
717 let mut auth_retried = false;
718 for attempt in 0..attempts {
719 let mut req = make_req()?;
720 if let Some(auth) = &auth_override {
721 req = req.header(header::AUTHORIZATION, auth.clone());
722 }
723 let resp_result = req.send().await;
724
725 match resp_result {
726 Ok(resp) => {
727 if is_graphql {
729 Self::record_graphql_response(&resp);
730 } else {
731 Self::record_response(&resp);
732 }
733
734 if resp.status() == StatusCode::UNAUTHORIZED {
735 let resp_url = resp.url().to_string();
736 let status = resp.status();
737 let body = resp.text().await.unwrap_or_default();
738 if body.contains("Bad credentials") && !auth_retried {
739 tracing::warn!(
740 "GitHub API 401 Bad credentials — clearing cached token and re-resolving"
741 );
742 self.token_resolver.clear_cache().await;
743 if let Some(app) = self.app() {
744 app.invalidate();
745 }
746 match self.auth_header(&resp_url).await {
747 Ok(new_auth) => {
748 auth_retried = true;
749 auth_override = Some(new_auth);
750 }
751 Err(e) => {
752 last_err = Some(
753 e.context("GitHub token re-resolution failed after 401"),
754 );
755 break;
756 }
757 }
758 continue;
760 }
761 if auth_retried {
762 self.token_resolver.clear_cache().await;
765 anyhow::bail!(
766 "GitHub authentication failed ({status}): token re-resolved after cache clear but still rejected"
767 );
768 }
769 anyhow::bail!("GitHub API request failed ({status}): {body}");
770 }
771
772 if resp.status().is_server_error() {
774 let status = resp.status();
775 let headers = resp.headers().clone();
776 let body = resp.text().await.unwrap_or_default();
777 let req_id = headers
778 .get("x-github-request-id")
779 .and_then(|v| v.to_str().ok())
780 .unwrap_or("<none>");
781 let snippet: String = body.chars().take(400).collect();
782 tracing::warn!(
783 status = %status,
784 request_id = %req_id,
785 attempt,
786 "GitHub server error (5xx) — attempt {attempt}: {snippet}"
787 );
788
789 last_err = Some(anyhow::anyhow!(
790 "GitHub API server error ({status}) request_id={req_id}: {snippet}"
791 ));
792
793 if attempt + 1 < attempts {
794 let exp = 1u64.checked_shl(attempt.min(63)).unwrap_or(u64::MAX);
797 let mut backoff = base_secs.saturating_mul(exp);
798 if backoff > max_secs {
799 backoff = max_secs;
800 }
801 let jitter_ms = u64::from(attempt) * 100;
803 let sleep_dur = Duration::from_secs(backoff)
804 + Duration::from_millis(jitter_ms.min(1000));
805 time::sleep(sleep_dur).await;
806 continue;
807 }
808 tracing::warn!(
810 "GitHub API 5xx persisted after {} attempts — setting circuit-breaker for {}s",
811 attempts,
812 circuit_cooldown_secs
813 );
814 engine_cooldown::set_agent_cooldown("github:5xx", circuit_cooldown_secs)
815 .await;
816 break;
817 }
818
819 return Ok(resp);
821 }
822 Err(e) => {
823 let detail = transport_error_detail(&e);
830 tracing::warn!(err = %detail, attempt, "HTTP request failed to send (transport error, GitHub not reached), will retry if attempts remain");
831 last_err = Some(anyhow::anyhow!(
832 "HTTP request failed to send (transport error): {detail}"
833 ));
834 if attempt + 1 < attempts {
835 let exp = 1u64.checked_shl(attempt.min(63)).unwrap_or(u64::MAX);
837 let backoff = base_secs.saturating_mul(exp);
838 let sleep_dur = Duration::from_secs(backoff)
839 + Duration::from_millis((u64::from(attempt) * 100).min(1000));
840 time::sleep(sleep_dur).await;
841 continue;
842 }
843 tracing::warn!(
847 "HTTP request failed to send after {} attempts (transport error, GitHub not reached) — not tripping the github:5xx circuit-breaker",
848 attempts
849 );
850 break;
851 }
852 }
853 }
854
855 Err(last_err.unwrap_or_else(|| anyhow::anyhow!("unexpected send_with_retries failure")))
856 }
857
858 async fn get_json<T: DeserializeOwned>(&self, url: &str) -> anyhow::Result<T> {
860 Self::check_backoff(url)?;
861 let auth = self.auth_header(url).await?;
862 let make_req = || {
864 Ok(self
865 .client
866 .get(url)
867 .timeout(READ_TIMEOUT)
868 .header(header::AUTHORIZATION, auth.clone())
869 .header(header::ACCEPT, "application/vnd.github+json")
870 .header("X-GitHub-Api-Version", "2022-11-28"))
871 };
872 let resp = self.send_with_retries(make_req, false).await?;
873 let status = resp.status();
874 if !status.is_success() {
875 let body = resp.text().await.unwrap_or_default();
876 Self::maybe_record_rate_limit_from_body(status, &body);
877 anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
878 }
879 let body = resp.text().await?;
880 serde_json::from_str(&body)
881 .with_context(|| format!("failed to parse GitHub API response from GET {url}: {body}"))
882 }
883
884 async fn get_bytes(&self, url: &str) -> anyhow::Result<Vec<u8>> {
886 Self::check_backoff(url)?;
887 let auth = self.auth_header(url).await?;
888 let make_req = || {
889 Ok(self
890 .client
891 .get(url)
892 .timeout(READ_TIMEOUT)
893 .header(header::AUTHORIZATION, auth.clone())
894 .header(header::ACCEPT, "application/vnd.github+json")
895 .header("X-GitHub-Api-Version", "2022-11-28"))
896 };
897 let resp = self.send_with_retries(make_req, false).await?;
898 let status = resp.status();
899 if !status.is_success() {
900 let body = resp.text().await.unwrap_or_default();
901 Self::maybe_record_rate_limit_from_body(status, &body);
902 anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
903 }
904 Ok(resp.bytes().await?.to_vec())
905 }
906
907 async fn get_with_query<T: DeserializeOwned>(
909 &self,
910 url: &str,
911 query: &[(&str, &str)],
912 ) -> anyhow::Result<T> {
913 Self::check_backoff(url)?;
914 let auth = self.auth_header(url).await?;
915 let make_req = || {
916 Ok(self
917 .client
918 .get(url)
919 .timeout(READ_TIMEOUT)
920 .query(query)
921 .header(header::AUTHORIZATION, auth.clone())
922 .header(header::ACCEPT, "application/vnd.github+json")
923 .header("X-GitHub-Api-Version", "2022-11-28"))
924 };
925 let resp = self.send_with_retries(make_req, false).await?;
926 let status = resp.status();
927 if !status.is_success() {
928 let body = resp.text().await.unwrap_or_default();
929 Self::maybe_record_rate_limit_from_body(status, &body);
930 anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
931 }
932 let body = resp.text().await?;
933 serde_json::from_str(&body)
934 .with_context(|| format!("failed to parse GitHub API response from GET {url}: {body}"))
935 }
936
937 async fn post_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
939 Self::check_backoff(url)?;
940 let auth = self.auth_header(url).await?;
941 let make_req = || {
942 Ok(self
943 .client
944 .post(url)
945 .json(body)
946 .header(header::AUTHORIZATION, auth.clone())
947 .header(header::ACCEPT, "application/vnd.github+json")
948 .header("X-GitHub-Api-Version", "2022-11-28"))
949 };
950 let resp = self.send_with_retries(make_req, false).await?;
951 let status = resp.status();
952 let text_res = resp.text().await;
953 if !status.is_success() {
954 let text = text_res.unwrap_or_default();
955 Self::maybe_record_rate_limit_from_body(status, &text);
956 anyhow::bail!("GitHub API POST {url} failed ({status}): {text}");
957 }
958 let text = text_res?;
959 Ok(text)
960 }
961
962 async fn post_json<T: DeserializeOwned>(
964 &self,
965 url: &str,
966 body: &serde_json::Value,
967 ) -> anyhow::Result<T> {
968 let text = self.post_json_raw(url, body).await?;
969 Ok(serde_json::from_str(&text)?)
970 }
971
972 async fn patch_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
974 Self::check_backoff(url)?;
975 let auth = self.auth_header(url).await?;
976 let make_req = || {
977 Ok(self
978 .client
979 .patch(url)
980 .json(body)
981 .header(header::AUTHORIZATION, auth.clone())
982 .header(header::ACCEPT, "application/vnd.github+json")
983 .header("X-GitHub-Api-Version", "2022-11-28"))
984 };
985 let resp = self.send_with_retries(make_req, false).await?;
986 let status = resp.status();
987 let text_res = resp.text().await;
988 if !status.is_success() {
989 let text = text_res.unwrap_or_default();
990 Self::maybe_record_rate_limit_from_body(status, &text);
991 anyhow::bail!("GitHub API PATCH {url} failed ({status}): {text}");
992 }
993 let text = text_res?;
994 Ok(text)
995 }
996
997 pub async fn put_file(
999 &self,
1000 repo: &str,
1001 path: &str,
1002 branch: &str,
1003 message: &str,
1004 content: &str,
1005 ) -> anyhow::Result<()> {
1006 let encoded_path = path
1007 .split('/')
1008 .map(|segment| urlencoding::encode(segment).into_owned())
1009 .collect::<Vec<_>>()
1010 .join("/");
1011 let url = format!("{}/repos/{repo}/contents/{encoded_path}", self.api_root());
1012 let current = self
1014 .get_json::<serde_json::Value>(&format!("{url}?ref={}", urlencoding::encode(branch)))
1015 .await
1016 .ok()
1017 .and_then(|v| v.get("sha").and_then(|s| s.as_str()).map(str::to_string));
1018 let mut body = serde_json::json!({
1019 "message": message,
1020 "content": BASE64.encode(content),
1021 "branch": branch,
1022 });
1023 if let Some(sha) = current {
1024 body["sha"] = serde_json::Value::String(sha);
1025 }
1026 self.put_json_raw(&url, &body).await.map(|_| ())
1027 }
1028
1029 async fn put_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
1031 Self::check_backoff(url)?;
1032 let auth = self.auth_header(url).await?;
1033 let make_req = || {
1034 Ok(self
1035 .client
1036 .put(url)
1037 .json(body)
1038 .header(header::AUTHORIZATION, auth.clone())
1039 .header(header::ACCEPT, "application/vnd.github+json")
1040 .header("X-GitHub-Api-Version", "2022-11-28"))
1041 };
1042 let resp = self.send_with_retries(make_req, false).await?;
1043 let status = resp.status();
1044 let text_res = resp.text().await;
1045 if !status.is_success() {
1046 let text = text_res.unwrap_or_default();
1047 Self::maybe_record_rate_limit_from_body(status, &text);
1048 anyhow::bail!("GitHub API PUT {url} failed ({status}): {text}");
1049 }
1050 let text = text_res?;
1051 Ok(text)
1052 }
1053
1054 async fn delete(&self, url: &str) -> anyhow::Result<StatusCode> {
1056 Self::check_backoff(url)?;
1057 let auth = self.auth_header(url).await?;
1058 let make_req = || {
1059 Ok(self
1060 .client
1061 .delete(url)
1062 .header(header::AUTHORIZATION, auth.clone())
1063 .header(header::ACCEPT, "application/vnd.github+json")
1064 .header("X-GitHub-Api-Version", "2022-11-28"))
1065 };
1066 let resp = self.send_with_retries(make_req, false).await?;
1067 let status = resp.status();
1068 if !status.is_success() && status != StatusCode::NOT_FOUND {
1069 let body = resp.text().await.unwrap_or_default();
1070 Self::maybe_record_rate_limit_from_body(status, &body);
1071 anyhow::bail!("GitHub API DELETE {url} failed ({status}): {body}");
1072 }
1073 Ok(status)
1074 }
1075
1076 async fn get_all_pages<T: DeserializeOwned>(
1081 &self,
1082 url: &str,
1083 query: &[(&str, &str)],
1084 ) -> anyhow::Result<Vec<T>> {
1085 const MAX_JSON_DECODE_RETRIES: u32 = 2;
1086 const JSON_DECODE_RETRY_BACKOFF_MS: u64 = 200;
1087 Self::check_backoff(url)?;
1088 let mut all: Vec<T> = Vec::new();
1089 let mut next_url: Option<String> = None;
1090 let mut is_first = true;
1091
1092 loop {
1093 let (request_url, request_query) = if is_first {
1094 is_first = false;
1095 (url, Some(query))
1096 } else {
1097 let Some(u) = next_url.as_ref() else { break };
1098 (u.as_str(), None)
1099 };
1100
1101 let cache_key = page_cache_key::<T>(request_url, request_query);
1102 let mut cached_etag = cache_key.as_deref().and_then(page_cache_etag);
1103 let mut decode_attempt = 0;
1104 let (page, next) = loop {
1105 let auth = self.auth_header(request_url).await?;
1106 let mut req = self
1107 .client
1108 .get(request_url)
1109 .timeout(READ_TIMEOUT)
1110 .header(header::AUTHORIZATION, auth)
1111 .header(header::ACCEPT, "application/vnd.github+json")
1112 .header("X-GitHub-Api-Version", "2022-11-28");
1113 if let Some(q) = request_query {
1114 req = req.query(q);
1115 }
1116 if let Some(etag) = &cached_etag {
1117 req = req.header(header::IF_NONE_MATCH, etag.clone());
1118 }
1119
1120 let make_req = || {
1121 req.try_clone()
1122 .ok_or_else(|| anyhow::anyhow!("request clone failed"))
1123 };
1124 let resp = self.send_with_retries(make_req, false).await?;
1125 let status = resp.status();
1126 let next_from_headers = parse_link_next(resp.headers());
1127 let etag = resp
1128 .headers()
1129 .get(header::ETAG)
1130 .and_then(|v| v.to_str().ok())
1131 .map(ToString::to_string);
1132 let content_type = resp
1133 .headers()
1134 .get(header::CONTENT_TYPE)
1135 .and_then(|v| v.to_str().ok())
1136 .map_or_else(|| "<missing>".to_string(), ToString::to_string);
1137
1138 if status == StatusCode::NOT_MODIFIED {
1139 if let Some((body, next)) = cache_key.as_deref().and_then(page_cache_hit) {
1140 break (serde_json::from_str::<Vec<T>>(&body)?, next);
1141 }
1142 cached_etag = None;
1147 continue;
1148 }
1149
1150 if !status.is_success() {
1151 let body = resp.text().await.unwrap_or_default();
1152 Self::maybe_record_rate_limit_from_body(status, &body);
1153 anyhow::bail!("GitHub API GET (paginated) failed ({status}): {body}");
1154 }
1155
1156 let text = resp.text().await?;
1157 match serde_json::from_str::<Vec<T>>(&text) {
1158 Ok(page) => {
1159 if let (Some(key), Some(etag)) = (cache_key.clone(), etag) {
1160 page_cache_store(key, etag, text, next_from_headers.clone());
1161 }
1162 break (page, next_from_headers);
1163 }
1164 Err(err) => {
1165 let snippet: String = text.chars().take(200).collect();
1166 let decode_error = anyhow::anyhow!(
1167 "GitHub API GET (paginated) JSON decode failed ({status}, content-type={content_type}): {snippet}"
1168 )
1169 .context(err);
1170 if decode_attempt < MAX_JSON_DECODE_RETRIES {
1171 decode_attempt += 1;
1172 tracing::warn!(
1173 attempt = decode_attempt,
1174 max_attempts = MAX_JSON_DECODE_RETRIES,
1175 status = %status,
1176 content_type,
1177 err = %decode_error,
1178 "json decode failed; retrying paginated GET"
1179 );
1180 time::sleep(Duration::from_millis(
1181 JSON_DECODE_RETRY_BACKOFF_MS * u64::from(decode_attempt),
1182 ))
1183 .await;
1184 continue;
1185 }
1186 return Err(decode_error);
1187 }
1188 }
1189 };
1190
1191 next_url = next;
1192 all.extend(page);
1193
1194 if next_url.is_none() {
1195 break;
1196 }
1197 }
1198
1199 Ok(all)
1200 }
1201
1202 async fn get_all_pages_from_wrapper<T: DeserializeOwned>(
1213 &self,
1214 url: &str,
1215 array_field: &str,
1216 ) -> anyhow::Result<Vec<T>> {
1217 Self::check_backoff(url)?;
1218 let mut all: Vec<T> = Vec::new();
1219 let mut current_url: String = url.to_string();
1220
1221 loop {
1222 let auth = self.auth_header(¤t_url).await?;
1223 let make_req = || {
1224 self.client
1225 .get(¤t_url)
1226 .timeout(READ_TIMEOUT)
1227 .header(header::AUTHORIZATION, auth.clone())
1228 .header(header::ACCEPT, "application/vnd.github+json")
1229 .header("X-GitHub-Api-Version", "2022-11-28")
1230 .try_clone()
1231 .ok_or_else(|| anyhow::anyhow!("request clone failed"))
1232 };
1233 let resp = self.send_with_retries(make_req, false).await?;
1234 let status = resp.status();
1235 let next = parse_link_next(resp.headers());
1236
1237 if !status.is_success() {
1238 let body = resp.text().await.unwrap_or_default();
1239 Self::maybe_record_rate_limit_from_body(status, &body);
1240 anyhow::bail!(
1241 "GitHub API GET (wrapped paginated) {current_url} failed ({status}): {body}"
1242 );
1243 }
1244
1245 let body = resp.text().await?;
1246 let wrapper: serde_json::Value = serde_json::from_str(&body).with_context(|| {
1247 format!("failed to parse wrapper response from {current_url}: {body}")
1248 })?;
1249 let items = wrapper
1250 .get(array_field)
1251 .and_then(|v| v.as_array())
1252 .cloned()
1253 .unwrap_or_default();
1254
1255 for item in items {
1256 match serde_json::from_value::<T>(item) {
1257 Ok(v) => all.push(v),
1258 Err(e) => {
1259 tracing::warn!(
1260 field = array_field,
1261 err = %e,
1262 "skipping item that failed to deserialize in wrapped pagination"
1263 );
1264 }
1265 }
1266 }
1267
1268 match next {
1269 Some(next_url) => current_url = next_url,
1270 None => break,
1271 }
1272 }
1273
1274 Ok(all)
1275 }
1276
1277 async fn graphql_request(
1279 &self,
1280 query: &str,
1281 extra_headers: &[(&str, &str)],
1282 variables: Option<serde_json::Value>,
1283 ) -> anyhow::Result<serde_json::Value> {
1284 self.graphql_request_to_url(
1285 &format!("{GITHUB_API}/graphql"),
1286 query,
1287 extra_headers,
1288 variables,
1289 )
1290 .await
1291 }
1292
1293 async fn graphql_request_to_url(
1294 &self,
1295 url: &str,
1296 query: &str,
1297 extra_headers: &[(&str, &str)],
1298 variables: Option<serde_json::Value>,
1299 ) -> anyhow::Result<serde_json::Value> {
1300 Self::check_graphql_backoff(url)?;
1301 let body = if let Some(vars) = variables {
1302 serde_json::json!({ "query": query, "variables": vars })
1303 } else {
1304 serde_json::json!({ "query": query })
1305 };
1306 let auth = self.auth_header(url).await?;
1307 let mut req = self
1308 .client
1309 .post(url)
1310 .timeout(graphql_timeout(query))
1311 .json(&body)
1312 .header(header::AUTHORIZATION, auth)
1313 .header(header::ACCEPT, "application/vnd.github+json")
1314 .header("X-GitHub-Api-Version", "2022-11-28");
1315
1316 for (k, v) in extra_headers {
1317 req = req.header(*k, *v);
1318 }
1319
1320 let make_req = || {
1322 req.try_clone()
1323 .ok_or_else(|| anyhow::anyhow!("graphql request clone failed"))
1324 };
1325 let resp = self.send_with_retries(make_req, true).await?;
1326 let status = resp.status();
1327 let text_res = resp.text().await;
1328 if !status.is_success() {
1329 let text = text_res.unwrap_or_default();
1330 Self::maybe_record_graphql_rate_limit_from_body(status, &text);
1331 anyhow::bail!("GitHub GraphQL failed ({status}): {text}");
1332 }
1333 let text = text_res?;
1334 let json: serde_json::Value = serde_json::from_str(&text)?;
1335 if let Some(errors) = json.get("errors").and_then(|e| e.as_array())
1337 && !errors.is_empty()
1338 {
1339 let messages: Vec<&str> = errors
1340 .iter()
1341 .filter_map(|e| e.get("message").and_then(|m| m.as_str()))
1342 .collect();
1343 if json.get("data").is_none() || json["data"].is_null() {
1344 anyhow::bail!("GitHub GraphQL errors: {}", messages.join("; "));
1346 }
1347 tracing::warn!(errors = ?messages, "GitHub GraphQL returned partial errors");
1349 }
1350 Ok(json)
1351 }
1352
1353 pub async fn graphql_with_vars(
1356 &self,
1357 query: &str,
1358 variables: serde_json::Value,
1359 ) -> anyhow::Result<serde_json::Value> {
1360 self.graphql_request(query, &[], Some(variables)).await
1361 }
1362
1363 pub async fn graphql_with_headers(
1364 &self,
1365 query: &str,
1366 headers: &[&str],
1367 ) -> anyhow::Result<serde_json::Value> {
1368 let pairs: Vec<(&str, &str)> = headers.iter().filter_map(|h| h.split_once(':')).collect();
1370 self.graphql_request(query, &pairs, None).await
1371 }
1372
1373 pub async fn graphql_with_headers_and_vars(
1374 &self,
1375 query: &str,
1376 headers: &[&str],
1377 variables: serde_json::Value,
1378 ) -> anyhow::Result<serde_json::Value> {
1379 let pairs: Vec<(&str, &str)> = headers.iter().filter_map(|h| h.split_once(':')).collect();
1380 self.graphql_request(query, &pairs, Some(variables)).await
1381 }
1382}
1383
1384pub fn has_status(text: &str, status: u16) -> bool {
1389 text.contains(&format!("failed ({status}")) || text.contains(&format!("HTTP {status}"))
1390}
1391
1392fn sanitize_github_issue_numbers(issue_numbers: &[u64]) -> (Vec<u64>, Vec<u64>) {
1393 let mut valid = Vec::with_capacity(issue_numbers.len());
1394 let mut invalid = Vec::new();
1395 for &issue_number in issue_numbers {
1396 if issue_number == 0 {
1397 invalid.push(issue_number);
1398 } else {
1399 valid.push(issue_number);
1400 }
1401 }
1402 (valid, invalid)
1403}
1404
1405#[derive(Debug, Clone)]
1409pub struct RateLimitMetrics {
1410 pub hits: u64,
1412 pub skipped_calls: u64,
1414 pub rest_remaining: Option<u32>,
1416 pub rest_reset_at: Option<u64>,
1418 pub graphql_remaining: Option<u32>,
1420 pub five_xx_hits: u64,
1422}
1423
1424pub fn rate_limit_metrics() -> RateLimitMetrics {
1426 let (rest_remaining, rest_reset_at) = REST_RATE_LIMIT
1427 .lock()
1428 .ok()
1429 .map_or((None, None), |rl| (rl.remaining, rl.reset_at));
1430 let graphql_remaining = GRAPHQL_RATE_LIMIT.lock().ok().and_then(|rl| rl.remaining);
1431 RateLimitMetrics {
1432 hits: METRIC_RATE_LIMIT_HITS.load(Ordering::Relaxed),
1433 skipped_calls: METRIC_PROACTIVE_THROTTLES.load(Ordering::Relaxed),
1434 rest_remaining,
1435 rest_reset_at,
1436 graphql_remaining,
1437 five_xx_hits: METRIC_5XX_HITS.load(Ordering::Relaxed),
1438 }
1439}
1440
1441fn parse_link_next(headers: &header::HeaderMap) -> Option<String> {
1445 let link = headers.get("link")?.to_str().ok()?;
1446 for part in link.split(',') {
1447 let part = part.trim();
1448 if part.contains("rel=\"next\"") {
1449 let start = part.find('<')? + 1;
1451 let end = part.find('>')?;
1452 if start >= end {
1453 return None;
1454 }
1455 return Some(part[start..end].to_string());
1456 }
1457 }
1458 None
1459}
1460
1461pub fn status_label_color(label: &str) -> &'static str {
1463 match label {
1464 "status:new" => "0e8a16",
1465 "status:routed" => "1d76db",
1466 "status:in_progress" => "fbca04",
1467 "status:done" => "6f42c1",
1468 "status:blocked" => "d73a4a",
1469 "status:in_review" => "0075ca",
1470 "status:approved" => "2ea44f",
1471 "status:needs_review" => "e4e669",
1472 "status:waiting" => "5319e7",
1473 _ => "c5def5",
1474 }
1475}
1476
1477#[cfg(test)]
1480mod tests;