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