Skip to main content

orch/github/http/
mod.rs

1//! Native `reqwest` HTTP client for the GitHub API — replaces `gh` CLI subprocesses.
2//!
3//! Uses a shared `reqwest::Client` with connection pooling, reads rate-limit
4//! headers proactively, and supports concurrent requests via `tokio::join!`.
5//!
6//! Auth: uses the centralized [`TokenResolver`] which supports:
7//! - `GH_TOKEN` / `GITHUB_TOKEN` environment variables
8//! - `gh.auth.token` config value
9//! - `gh auth token` CLI fallback (default — just run `gh auth login`)
10
11mod checks;
12mod contents;
13mod issues;
14mod pulls;
15
16use super::token;
17use crate::config;
18use crate::cooldown as engine_cooldown;
19use crate::cooldown;
20use anyhow::Context;
21use base64::Engine;
22use base64::engine::general_purpose::STANDARD as BASE64;
23#[cfg(test)]
24pub(crate) use checks::{REQUIRED_CHECK_RULESET_NAME, classify_ruleset_create_error};
25pub(crate) use checks::{RulesetApply, RulesetCreateKind};
26pub use contents::FileFetch;
27pub(crate) use pulls::BaseMergeRefusal;
28pub use pulls::{CommitMeta, PrReviewBatchData};
29use reqwest::{Client, Response, StatusCode, header};
30use serde::de::DeserializeOwned;
31use std::any;
32use std::cmp::Reverse;
33use std::collections::HashMap;
34use std::error::Error as _;
35use std::fmt;
36use std::fmt::Debug;
37use std::fmt::Formatter;
38use std::fmt::Write as _;
39use std::sync::LazyLock;
40use std::sync::{
41    Arc, Mutex, OnceLock,
42    atomic::{AtomicU64, Ordering},
43};
44use std::time as std_time;
45use std::time::SystemTime;
46use std::time::{Duration, Instant};
47use tokio::runtime::Handle;
48use tokio::time;
49use urlencoding;
50
51#[cfg(not(test))]
52const GITHUB_API: &str = "https://api.github.com";
53// Tests that reach a real GhHttp must fail fast here, never send the operator's token to GitHub
54#[cfg(test)]
55const GITHUB_API: &str = "http://127.0.0.1:9";
56
57// Writes keep this. GET and GraphQL queries use READ_TIMEOUT so a dead pooled connection fails inside one tick
58const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
59// GET and GraphQL queries, 10 s in production, 1 s in tests so the silent-peer test stays short
60const READ_TIMEOUT: Duration = Duration::from_secs(if cfg!(test) { 1 } else { 10 });
61const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
62const TCP_KEEPALIVE: Duration = Duration::from_secs(30);
63const POOL_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
64// HTTP/2 ping interval, a dead pooled connection fails its ping in about 20 s and leaves the pool
65const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(15);
66const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(5);
67
68#[derive(Debug, serde::Deserialize)]
69struct BlockedByPayload {
70    #[serde(default)]
71    id: i64,
72    number: i64,
73    #[serde(default)]
74    state: String,
75    #[serde(default)]
76    state_reason: Option<String>,
77    #[serde(default)]
78    repository: Option<BlockedByRepoPayload>,
79}
80
81#[derive(Debug, serde::Deserialize)]
82struct BlockedByRepoPayload {
83    full_name: String,
84}
85
86pub(crate) fn is_full_commit_sha(sha: &str) -> bool {
87    let len = sha.len();
88    (len == 40 || len == 64) && sha.bytes().all(|b| b.is_ascii_hexdigit())
89}
90
91fn graphql_timeout(query: &str) -> Duration {
92    if query.trim_start().starts_with("query") {
93        READ_TIMEOUT
94    } else {
95        REQUEST_TIMEOUT
96    }
97}
98
99fn github_retry_attempts() -> u32 {
100    #[cfg(test)]
101    {
102        let n = TEST_RETRY_ATTEMPTS.load(Ordering::Relaxed);
103        if n > 0 {
104            return u32::try_from(n).unwrap_or(3);
105        }
106    }
107    config::get("gh.5xx.retry_attempts")
108        .ok()
109        .and_then(|v| v.parse::<u32>().ok())
110        .unwrap_or(3)
111}
112
113// Shared gate for every GitHub-posted body so a new call site cannot skip the scan
114/// `owner/repo` from a REST URL such as `https://api.github.com/repos/owner/repo/pulls`
115fn repo_from_url(url: &str) -> Option<String> {
116    let rest = url.split_once("/repos/")?.1;
117    let mut parts = rest.split(['/', '?']);
118    let owner = parts.next().filter(|s| !s.is_empty())?;
119    let name = parts.next().filter(|s| !s.is_empty())?;
120    Some(format!("{owner}/{name}"))
121}
122
123fn merge_pr_body(head_sha: &str) -> serde_json::Value {
124    serde_json::json!({
125        "merge_method": "squash",
126        "sha": head_sha,
127    })
128}
129
130fn parse_positive_issue_number(number: &str) -> anyhow::Result<i64> {
131    let parsed = number
132        .parse::<i64>()
133        .with_context(|| format!("invalid issue number: {number}"))?;
134    if parsed <= 0 {
135        anyhow::bail!("invalid issue number: {number}");
136    }
137    Ok(parsed)
138}
139
140// ── Rate-limit state ─────────────────────────────────────────────────
141
142/// Proactive rate-limit state derived from `X-RateLimit-*` response headers.
143struct RateLimit {
144    /// Remaining requests in the current window.
145    remaining: Option<u32>,
146    /// UTC epoch second when the window resets.
147    reset_at: Option<u64>,
148    /// Hard backoff after a 403/429 (fallback when reset time is absent).
149    backoff_until: Option<Instant>,
150    backoff_delay: Duration,
151    backoff_base: Duration,
152    backoff_max: Duration,
153    /// Stop making calls when remaining drops below this threshold (default 200). The
154    /// reserve is for the dispatched agents, which run `gh` against the same token.
155    throttle_threshold: u32,
156}
157
158impl RateLimit {
159    fn new() -> Self {
160        let base = config::get("gh.backoff.base_seconds")
161            .ok()
162            .and_then(|v| v.parse::<u64>().ok())
163            .unwrap_or(30);
164        let max = config::get("gh.backoff.max_seconds")
165            .ok()
166            .and_then(|v| v.parse::<u64>().ok())
167            .unwrap_or(900);
168        let threshold = config::get("gh.rate_limit.throttle_threshold")
169            .ok()
170            .and_then(|v| v.parse::<u32>().ok())
171            .unwrap_or(200);
172
173        Self {
174            remaining: None,
175            reset_at: None,
176            backoff_until: None,
177            backoff_delay: Duration::ZERO,
178            backoff_base: Duration::from_secs(base),
179            backoff_max: Duration::from_secs(max),
180            throttle_threshold: threshold,
181        }
182    }
183
184    /// Update state from response headers.
185    fn update_from_headers(&mut self, headers: &header::HeaderMap) {
186        if let Some(v) = headers.get("x-ratelimit-remaining") {
187            self.remaining = v.to_str().ok().and_then(|s| s.parse().ok());
188        }
189        if let Some(v) = headers.get("x-ratelimit-reset") {
190            self.reset_at = v.to_str().ok().and_then(|s| s.parse().ok());
191        }
192    }
193
194    /// Record a successful call — reset hard backoff.
195    fn record_success(&mut self) {
196        if self.backoff_delay > Duration::ZERO {
197            tracing::info!("GitHub backoff cleared after successful API call");
198        }
199        self.backoff_delay = Duration::ZERO;
200        self.backoff_until = None;
201    }
202
203    /// Record a 403/429 — use reset_at timestamp if available, else exponential backoff.
204    fn record_rate_limit(&mut self) {
205        METRIC_RATE_LIMIT_HITS.fetch_add(1, Ordering::Relaxed);
206
207        // Prefer reset_at when available — avoids over-waiting with exponential backoff
208        if let Some(reset_epoch) = self.reset_at {
209            match SystemTime::now().duration_since(std_time::UNIX_EPOCH) {
210                Ok(since_epoch) => {
211                    let now_epoch = since_epoch.as_secs();
212                    if reset_epoch > now_epoch {
213                        let wait_secs = reset_epoch - now_epoch + 1;
214                        self.backoff_delay = Duration::from_secs(wait_secs);
215                        self.backoff_until = Some(Instant::now() + self.backoff_delay);
216                        tracing::warn!(
217                            wait_secs,
218                            "GitHub rate limit hit, waiting until reset time"
219                        );
220                        return;
221                    }
222                }
223                Err(e) => {
224                    tracing::error!(
225                        error = %e,
226                        "System clock is before UNIX epoch; ignoring reset_at and falling back to exponential backoff"
227                    );
228                }
229            }
230        }
231
232        // Fall back to exponential backoff when reset time is unknown
233        self.backoff_delay = if self.backoff_delay.is_zero() {
234            self.backoff_base
235        } else {
236            (self.backoff_delay * 2).min(self.backoff_max)
237        };
238        self.backoff_until = Some(Instant::now() + self.backoff_delay);
239        tracing::warn!(
240            delay_secs = self.backoff_delay.as_secs(),
241            "GitHub rate limit hit, backing off (no reset header)"
242        );
243    }
244
245    /// Returns remaining hard-backoff duration (post-403/429), or None.
246    fn backoff_remaining(&self) -> Option<Duration> {
247        if let Some(until) = self.backoff_until {
248            let now = Instant::now();
249            if now < until {
250                return Some(until - now);
251            }
252        }
253        None
254    }
255
256    /// Returns how long until the window resets when the quota is under the reserve.
257    ///
258    /// Returns Some only when:
259    /// - not already in hard backoff,
260    /// - `remaining` is known and below `throttle_threshold`, and
261    /// - `reset_at` is known and in the future.
262    fn proactive_wait_duration(&self) -> Option<Duration> {
263        // Don't double-throttle when already in hard backoff
264        if self.backoff_remaining().is_some() {
265            return None;
266        }
267        if let Some(remaining) = self.remaining
268            && remaining < self.throttle_threshold
269            && let Some(reset_epoch) = self.reset_at
270        {
271            let now_epoch = SystemTime::now()
272                .duration_since(std_time::UNIX_EPOCH)
273                .unwrap_or_default()
274                .as_secs();
275            if now_epoch < reset_epoch {
276                return Some(Duration::from_secs(reset_epoch - now_epoch + 1));
277            }
278        }
279        None
280    }
281
282    /// Combined check: backoff or proactive throttle. Used by engine's is_rate_limited().
283    fn is_active(&self) -> Option<Duration> {
284        self.backoff_remaining()
285            .or_else(|| self.proactive_wait_duration())
286    }
287}
288
289// ── Global state ─────────────────────────────────────────────────────
290
291static REST_RATE_LIMIT: LazyLock<Mutex<RateLimit>> = LazyLock::new(|| Mutex::new(RateLimit::new()));
292
293#[cfg(test)]
294static TEST_RETRY_ATTEMPTS: AtomicU64 = AtomicU64::new(0);
295
296/// Separate rate-limit tracker for the GraphQL endpoint (distinct quota from REST).
297static GRAPHQL_RATE_LIMIT: LazyLock<Mutex<RateLimit>> =
298    LazyLock::new(|| Mutex::new(RateLimit::new()));
299
300// ── Rate-limit metrics ────────────────────────────────────────────────
301
302/// Total 403/429 rate-limit responses received (REST + GraphQL).
303static METRIC_RATE_LIMIT_HITS: AtomicU64 = AtomicU64::new(0);
304/// Calls skipped because the quota was under the reserve threshold or a backoff was active.
305static METRIC_PROACTIVE_THROTTLES: AtomicU64 = AtomicU64::new(0);
306/// Total 5xx server error responses received (REST + GraphQL).
307static METRIC_5XX_HITS: AtomicU64 = AtomicU64::new(0);
308
309// ── Rate-limit generic helpers ────────────────────────────────────────
310
311/**
312 * Fail fast when the limiter is in hard backoff (post-403/429) or the remaining quota is
313 * under the reserve threshold. This must never sleep: the engine runs every tick phase
314 * through these calls, so waiting out a reset here froze the whole tick loop for up to an
315 * hour and tripped the watchdog. Returning an error lets the phase give up and the tick
316 * finish, and the next tick retries once the window resets
317 **/
318fn check_rate_limit_backoff(cell: &Mutex<RateLimit>, api: &str) -> anyhow::Result<()> {
319    let Some(remaining) = cell.lock().ok().and_then(|rl| rl.is_active()) else {
320        return Ok(());
321    };
322    METRIC_PROACTIVE_THROTTLES.fetch_add(1, Ordering::Relaxed);
323    anyhow::bail!(
324        "GitHub {} API rate-limited, skipping call for {}s",
325        api,
326        remaining.as_secs()
327    );
328}
329
330/// API calls since the last drain, keyed by (project, call type), for the per-tick debug report.
331static CALL_COUNTS: LazyLock<Mutex<HashMap<(String, String), u64>>> =
332    LazyLock::new(|| Mutex::new(HashMap::new()));
333
334/// Project is `owner/repo` from a `/repos/` URL and call type is the path segment after it
335/// (`pulls`, `issues`, `check-runs`), so non-repo endpoints land under `-`.
336fn count_api_call(url: &str) {
337    let path = url.split('?').next().unwrap_or(url);
338    let key = match path.split_once("/repos/") {
339        Some((_, rest)) => {
340            let mut parts = rest.split('/');
341            let project = format!(
342                "{}/{}",
343                parts.next().unwrap_or(""),
344                parts.next().unwrap_or("")
345            );
346            (project, parts.next().unwrap_or("repo").to_string())
347        }
348        None if path.ends_with("/graphql") => ("-".to_string(), "graphql".to_string()),
349        None => ("-".to_string(), "other".to_string()),
350    };
351    if let Ok(mut counts) = CALL_COUNTS.lock() {
352        *counts.entry(key).or_insert(0) += 1;
353    }
354}
355
356/// Take the call counts accumulated since the last drain, largest first.
357pub fn drain_call_counts() -> Vec<(String, String, u64)> {
358    let mut rows: Vec<_> = CALL_COUNTS
359        .lock()
360        .map(|mut c| c.drain().map(|((p, k), n)| (p, k, n)).collect())
361        .unwrap_or_default();
362    rows.sort_by_key(|r| Reverse(r.2));
363    rows
364}
365
366// ── Conditional-request cache ─────────────────────────────────────────
367
368/// A stored 200 response, replayed when GitHub answers the next conditional GET with 304.
369struct CachedPage {
370    etag: String,
371    body: String,
372    /// `Link: rel="next"` from the cached response; a 304 does not repeat it.
373    next: Option<String>,
374}
375
376/**
377 * Keyed by the full request URL plus the decoded type, since the body is replayed through
378 * `serde_json` and two call sites can share a URL while wanting different shapes. GitHub
379 * answers a conditional GET with 304 and no body when nothing changed, and that response
380 * does not count against the core quota, so the listing endpoints orch polls every tick
381 * cost one request per hour of quiet instead of one per tick
382 **/
383static PAGE_CACHE: LazyLock<Mutex<HashMap<String, CachedPage>>> =
384    LazyLock::new(|| Mutex::new(HashMap::new()));
385
386/// Distinct cacheable list URLs are few per repo, plus one blocked-by URL per open issue.
387/// The cap only guards a leak. Each entry holds a full page body, so keep it small
388const PAGE_CACHE_MAX: usize = 256;
389
390/// `None` when the request cannot produce a hit, so it is neither sent conditionally nor
391/// stored. A `since` filter is computed from the clock on every call, so its key never
392/// recurs and caching it would only grow the map with page-sized bodies.
393fn page_cache_key<T>(url: &str, query: Option<&[(&str, &str)]>) -> Option<String> {
394    let mut key = String::from(any::type_name::<T>());
395    key.push(' ');
396    key.push_str(url);
397    if let Some(q) = query {
398        for (i, (k, v)) in q.iter().enumerate() {
399            key.push(if i == 0 { '?' } else { '&' });
400            key.push_str(k);
401            key.push('=');
402            key.push_str(v);
403        }
404    }
405    if key.contains("since=") {
406        return None;
407    }
408    Some(key)
409}
410
411fn page_cache_etag(key: &str) -> Option<String> {
412    PAGE_CACHE.lock().ok()?.get(key).map(|c| c.etag.clone())
413}
414
415/// Returns the stored body and `next` link for a 304 reply.
416fn page_cache_hit(key: &str) -> Option<(String, Option<String>)> {
417    let cache = PAGE_CACHE.lock().ok()?;
418    let entry = cache.get(key)?;
419    Some((entry.body.clone(), entry.next.clone()))
420}
421
422fn page_cache_store(key: String, etag: String, body: String, next: Option<String>) {
423    let Ok(mut cache) = PAGE_CACHE.lock() else {
424        return;
425    };
426    // ponytail: clears everything at the cap instead of evicting one entry, switch to an
427    // LRU if the hit rate ever matters more than the bookkeeping
428    if cache.len() >= PAGE_CACHE_MAX && !cache.contains_key(&key) {
429        cache.clear();
430    }
431    cache.insert(key, CachedPage { etag, body, next });
432}
433
434/// Check response body for rate-limit signals on 403 responses.
435/// Not all 403s are rate limits — some are permission errors.
436fn maybe_record_body_rate_limit(cell: &Mutex<RateLimit>, status: StatusCode, body: &str) {
437    if is_forbidden_rate_limit(status, body)
438        && let Ok(mut rl) = cell.lock()
439    {
440        rl.record_rate_limit();
441    }
442}
443
444/// True for a 403 whose body names a primary or secondary rate limit
445fn is_forbidden_rate_limit(status: StatusCode, body: &str) -> bool {
446    if status != StatusCode::FORBIDDEN {
447        return false;
448    }
449    let lower = body.to_lowercase();
450    lower.contains("rate limit")
451        || lower.contains("abuse detection")
452        || lower.contains("secondary rate")
453}
454
455/// Update rate-limit state from response headers/status and detect 5xx errors.
456fn record_response_for_limiter(cell: &Mutex<RateLimit>, resp: &Response) {
457    if let Ok(mut rl) = cell.lock() {
458        rl.update_from_headers(resp.headers());
459        // Only backoff on 429 (always rate limit) — 403 requires body inspection
460        // which is handled in maybe_record_body_rate_limit().
461        if resp.status() == StatusCode::TOO_MANY_REQUESTS {
462            rl.record_rate_limit();
463        } else if resp.status().is_success() || resp.status() == StatusCode::NOT_MODIFIED {
464            rl.record_success();
465        }
466    }
467    // Detect 5xx server errors for the global circuit breaker.
468    let status = resp.status();
469    if status.is_server_error() {
470        METRIC_5XX_HITS.fetch_add(1, Ordering::Relaxed);
471        if Handle::try_current().is_ok() {
472            tokio::spawn(async move {
473                cooldown::record_github_5xx().await;
474            });
475        }
476    }
477}
478
479// ── Shared token resolver ────────────────────────────────────────────
480
481// ── GhHttp client ────────────────────────────────────────────────────
482
483/// Native HTTP client for the GitHub API with connection pooling and
484/// proactive rate-limit avoidance.
485#[derive(Clone)]
486pub struct GhHttp {
487    client: Client,
488    token_resolver: Arc<token::TokenResolver>,
489    // An App only tests set, production calls always use the gh token
490    app: Option<Arc<super::app::AppAuth>>,
491    // Calls the App cannot make, such as `GET /user` and Projects V2 on a personal account
492    owner_only: bool,
493    cached_username: OnceLock<String>,
494    #[cfg(test)]
495    api_base: Option<String>,
496}
497
498impl Debug for GhHttp {
499    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
500        f.debug_struct("GhHttp")
501            .field("owner_only", &self.owner_only)
502            .finish_non_exhaustive()
503    }
504}
505
506/// The error with its full source chain plus the timeout and connect flags, because the
507/// top-level reqwest message alone hides why the request failed
508fn transport_error_detail(e: &reqwest::Error) -> String {
509    let mut out = e.to_string();
510    let mut source = e.source();
511    while let Some(s) = source {
512        let _ = write!(out, ": {s}");
513        source = s.source();
514    }
515    let _ = write!(
516        out,
517        " (is_timeout={}, is_connect={})",
518        e.is_timeout(),
519        e.is_connect()
520    );
521    out
522}
523
524impl GhHttp {
525    /// Create a new client backed by the process-wide shared [`TokenResolver`].
526    ///
527    /// Token is resolved lazily on first request:
528    ///   GH_TOKEN → GITHUB_TOKEN → gh.auth.token config → gh auth token CLI
529    /// The result is cached in the shared resolver for the life of the process,
530    /// so `gh auth token` is only called once regardless of how many instances
531    /// are created.
532    pub fn new() -> anyhow::Result<Self> {
533        let client = Client::builder()
534            .user_agent("orch/0.1 (reqwest)")
535            .pool_max_idle_per_host(4)
536            .timeout(REQUEST_TIMEOUT)
537            .connect_timeout(CONNECT_TIMEOUT)
538            .tcp_keepalive(TCP_KEEPALIVE)
539            .pool_idle_timeout(POOL_IDLE_TIMEOUT)
540            .http2_keep_alive_interval(HTTP2_KEEP_ALIVE_INTERVAL)
541            .http2_keep_alive_timeout(HTTP2_KEEP_ALIVE_TIMEOUT)
542            .http2_keep_alive_while_idle(true)
543            .build()
544            .map_err(|e| anyhow::anyhow!("failed to build HTTP client (TLS init): {e}"))?;
545
546        Ok(Self {
547            client,
548            token_resolver: token::shared(),
549            app: None,
550            owner_only: false,
551            cached_username: OnceLock::new(),
552            #[cfg(test)]
553            api_base: None,
554        })
555    }
556
557    /// A client that always uses the owner token, for calls the App cannot make, such as
558    /// `GET /user` and Projects V2 on a personal account
559    pub fn owner() -> anyhow::Result<Self> {
560        let mut gh = Self::new()?;
561        gh.owner_only = true;
562        Ok(gh)
563    }
564
565    #[cfg(test)]
566    pub(crate) fn for_test(api_base: String, app: Option<Arc<super::app::AppAuth>>) -> Self {
567        Self {
568            client: Client::new(),
569            token_resolver: Arc::new(token::TokenResolver::default_env()),
570            app,
571            owner_only: false,
572            cached_username: OnceLock::new(),
573            api_base: Some(api_base),
574        }
575    }
576
577    #[cfg_attr(
578        not(test),
579        expect(
580            clippy::unused_self,
581            reason = "only the test build reads the api base override"
582        )
583    )]
584    fn api_root(&self) -> &str {
585        #[cfg(test)]
586        if let Some(base) = &self.api_base {
587            return base;
588        }
589        GITHUB_API
590    }
591
592    // ── Rate-limit helpers ────────────────────────────────────────
593
594    /// Check if the REST GitHub API is currently rate-limited (backoff or approaching limit).
595    /// Used by the engine to decide whether to skip a tick.
596    pub fn is_rate_limited() -> Option<Duration> {
597        REST_RATE_LIMIT.lock().ok().and_then(|rl| rl.is_active())
598    }
599
600    /// Fail fast if the REST API is in hard backoff (post-403/429).
601    fn check_backoff(url: &str) -> anyhow::Result<()> {
602        count_api_call(url);
603        check_rate_limit_backoff(&REST_RATE_LIMIT, "REST")
604    }
605
606    /// Fail fast if the GraphQL API is in hard backoff (post-403/429).
607    fn check_graphql_backoff(url: &str) -> anyhow::Result<()> {
608        count_api_call(url);
609        check_rate_limit_backoff(&GRAPHQL_RATE_LIMIT, "GraphQL")
610    }
611
612    fn record_response(resp: &Response) {
613        record_response_for_limiter(&REST_RATE_LIMIT, resp);
614    }
615
616    fn record_graphql_response(resp: &Response) {
617        record_response_for_limiter(&GRAPHQL_RATE_LIMIT, resp);
618    }
619
620    /// Check response body for rate-limit signals on 403 responses (REST).
621    fn maybe_record_rate_limit_from_body(status: StatusCode, body: &str) {
622        maybe_record_body_rate_limit(&REST_RATE_LIMIT, status, body);
623    }
624
625    /// Check response body for rate-limit signals on 403 responses (GraphQL).
626    fn maybe_record_graphql_rate_limit_from_body(status: StatusCode, body: &str) {
627        maybe_record_body_rate_limit(&GRAPHQL_RATE_LIMIT, status, body);
628    }
629
630    fn record_success() {
631        if let Ok(mut rl) = REST_RATE_LIMIT.lock() {
632            rl.record_success();
633        }
634    }
635
636    // ── Low-level HTTP helpers ────────────────────────────────────
637
638    fn app(&self) -> Option<Arc<super::app::AppAuth>> {
639        if self.owner_only {
640            return None;
641        }
642
643        // orch's own calls use the gh token, the App only reviews (src/engine/review/). The App
644        // must not open PRs, GitHub refuses a review from a PR's author
645        self.app.clone()
646    }
647
648    /// The App's token for a repository it is installed on, the owner token for anything else,
649    /// including GraphQL, whose URL names no repository
650    async fn auth_header(&self, url: &str) -> anyhow::Result<String> {
651        if let (Some(app), Some(repo)) = (self.app(), repo_from_url(url)) {
652            match app.token_for_repo(&repo).await {
653                Ok(Some(token)) => return Ok(format!("Bearer {token}")),
654                Ok(None) => {}
655                Err(e) => {
656                    tracing::warn!(error = %e, repo, "GitHub App token unavailable, using the owner token");
657                }
658            }
659        }
660        match self.token_resolver.get_token().await? {
661            Some(token) if !token.is_empty() => Ok(format!("Bearer {token}")),
662            _ => anyhow::bail!("No GitHub token available — run `gh auth login` or set GH_TOKEN"),
663        }
664    }
665
666    /// Generic send wrapper that retries on 5xx server errors with exponential
667    /// backoff and sets a short-lived circuit-breaker in KV when retries fail.
668    async fn send_with_retries<F>(
669        &self,
670        mut make_req: F,
671        is_graphql: bool,
672    ) -> anyhow::Result<Response>
673    where
674        F: FnMut() -> anyhow::Result<reqwest::RequestBuilder>,
675    {
676        // Circuit-breaker: if set, fail fast to avoid wasting work.
677        if engine_cooldown::is_agent_in_cooldown("github:5xx") {
678            if let Some(until) = engine_cooldown::cooldown_until("github:5xx") {
679                let now = chrono::Utc::now().timestamp();
680                let remaining = if until > now { until - now } else { 0 };
681                anyhow::bail!("GitHub API transient 5xx circuit-breaker active for {remaining}s");
682            }
683            anyhow::bail!("GitHub API transient 5xx circuit-breaker active");
684        }
685
686        // Configurable retry params (defaults chosen conservatively)
687        let attempts = github_retry_attempts();
688        let base_secs = config::get("gh.5xx.base_backoff_seconds")
689            .ok()
690            .and_then(|v| v.parse::<u64>().ok())
691            .unwrap_or(1);
692        let max_secs = config::get("gh.5xx.max_backoff_seconds")
693            .ok()
694            .and_then(|v| v.parse::<u64>().ok())
695            .unwrap_or(30);
696        let circuit_cooldown_secs = config::get("gh.5xx.circuit_breaker_cooldown_seconds")
697            .ok()
698            .and_then(|v| v.parse::<u64>().ok())
699            .unwrap_or(300);
700
701        let mut last_err: Option<anyhow::Error> = None;
702        // A cached token can go bad mid-process (revoked, rotated, stale keychain read).
703        // On the first 401 Bad credentials: evict the cache, re-resolve once, resend
704        let mut auth_override: Option<String> = None;
705        let mut auth_retried = false;
706        for attempt in 0..attempts {
707            let mut req = make_req()?;
708            if let Some(auth) = &auth_override {
709                req = req.header(header::AUTHORIZATION, auth.clone());
710            }
711            let resp_result = req.send().await;
712
713            match resp_result {
714                Ok(resp) => {
715                    // Record rate-limit state depending on REST vs GraphQL
716                    if is_graphql {
717                        Self::record_graphql_response(&resp);
718                    } else {
719                        Self::record_response(&resp);
720                    }
721
722                    if resp.status() == StatusCode::UNAUTHORIZED {
723                        let resp_url = resp.url().to_string();
724                        let status = resp.status();
725                        let body = resp.text().await.unwrap_or_default();
726                        if body.contains("Bad credentials") && !auth_retried {
727                            tracing::warn!(
728                                "GitHub API 401 Bad credentials — clearing cached token and re-resolving"
729                            );
730                            self.token_resolver.clear_cache().await;
731                            if let Some(app) = self.app() {
732                                app.invalidate();
733                            }
734                            match self.auth_header(&resp_url).await {
735                                Ok(new_auth) => {
736                                    auth_retried = true;
737                                    auth_override = Some(new_auth);
738                                }
739                                Err(e) => {
740                                    last_err = Some(
741                                        e.context("GitHub token re-resolution failed after 401"),
742                                    );
743                                    break;
744                                }
745                            }
746                            // ponytail: consumes one 5xx-retry slot, attempts default is 3
747                            continue;
748                        }
749                        if auth_retried {
750                            // Fresh token also rejected; leave the cache empty so the next
751                            // call re-resolves and picks up env/config fixes immediately
752                            self.token_resolver.clear_cache().await;
753                            anyhow::bail!(
754                                "GitHub authentication failed ({status}): token re-resolved after cache clear but still rejected"
755                            );
756                        }
757                        anyhow::bail!("GitHub API request failed ({status}): {body}");
758                    }
759
760                    // If server error, treat as transient and retry
761                    if resp.status().is_server_error() {
762                        let status = resp.status();
763                        let headers = resp.headers().clone();
764                        let body = resp.text().await.unwrap_or_default();
765                        let req_id = headers
766                            .get("x-github-request-id")
767                            .and_then(|v| v.to_str().ok())
768                            .unwrap_or("<none>");
769                        let snippet: String = body.chars().take(400).collect();
770                        tracing::warn!(
771                            status = %status,
772                            request_id = %req_id,
773                            attempt,
774                            "GitHub server error (5xx) — attempt {attempt}: {snippet}"
775                        );
776
777                        last_err = Some(anyhow::anyhow!(
778                            "GitHub API server error ({status}) request_id={req_id}: {snippet}"
779                        ));
780
781                        if attempt + 1 < attempts {
782                            // Exponential backoff (2^attempt * base), capped
783                            // Cap exponent at 63 (max valid shift for u64) to prevent overflow
784                            let exp = 1u64.checked_shl(attempt.min(63)).unwrap_or(u64::MAX);
785                            let mut backoff = base_secs.saturating_mul(exp);
786                            if backoff > max_secs {
787                                backoff = max_secs;
788                            }
789                            // Add small linear jitter to avoid synchronized retries
790                            let jitter_ms = u64::from(attempt) * 100;
791                            let sleep_dur = Duration::from_secs(backoff)
792                                + Duration::from_millis(jitter_ms.min(1000));
793                            time::sleep(sleep_dur).await;
794                            continue;
795                        }
796                        // Exhausted attempts — set circuit-breaker and break so last_err is read
797                        tracing::warn!(
798                            "GitHub API 5xx persisted after {} attempts — setting circuit-breaker for {}s",
799                            attempts,
800                            circuit_cooldown_secs
801                        );
802                        engine_cooldown::set_agent_cooldown("github:5xx", circuit_cooldown_secs)
803                            .await;
804                        break;
805                    }
806
807                    // Non-5xx response — return it for caller to handle success/failure
808                    return Ok(resp);
809                }
810                Err(e) => {
811                    // Transport error — the request never reached GitHub (DNS failure,
812                    // connection refused, no route to host, TLS failure, etc). This is a
813                    // local/network condition, not evidence that GitHub itself is unhealthy,
814                    // so unlike the 5xx arm above it must NOT trip the shared "github:5xx"
815                    // circuit breaker: other subsystems (routing-phase skip, cooldown
816                    // throttling) key off that breaker as a signal about GitHub's health.
817                    let detail = transport_error_detail(&e);
818                    tracing::warn!(err = %detail, attempt, "HTTP request failed to send (transport error, GitHub not reached), will retry if attempts remain");
819                    last_err = Some(anyhow::anyhow!(
820                        "HTTP request failed to send (transport error): {detail}"
821                    ));
822                    if attempt + 1 < attempts {
823                        // Cap exponent at 63 (max valid shift for u64) to prevent overflow
824                        let exp = 1u64.checked_shl(attempt.min(63)).unwrap_or(u64::MAX);
825                        let backoff = base_secs.saturating_mul(exp);
826                        let sleep_dur = Duration::from_secs(backoff)
827                            + Duration::from_millis((u64::from(attempt) * 100).min(1000));
828                        time::sleep(sleep_dur).await;
829                        continue;
830                    }
831                    // Exhausted attempts — break so last_err is read. Deliberately does not
832                    // call set_agent_cooldown("github:5xx", ...): GitHub was never reached,
833                    // so its health is unknown and the shared breaker must stay untouched.
834                    tracing::warn!(
835                        "HTTP request failed to send after {} attempts (transport error, GitHub not reached) — not tripping the github:5xx circuit-breaker",
836                        attempts
837                    );
838                    break;
839                }
840            }
841        }
842
843        Err(last_err.unwrap_or_else(|| anyhow::anyhow!("unexpected send_with_retries failure")))
844    }
845
846    /// GET request, returns deserialized JSON.
847    async fn get_json<T: DeserializeOwned>(&self, url: &str) -> anyhow::Result<T> {
848        Self::check_backoff(url)?;
849        let auth = self.auth_header(url).await?;
850        // Use send_with_retries to handle transient 5xx/network failures
851        let make_req = || {
852            Ok(self
853                .client
854                .get(url)
855                .timeout(READ_TIMEOUT)
856                .header(header::AUTHORIZATION, auth.clone())
857                .header(header::ACCEPT, "application/vnd.github+json")
858                .header("X-GitHub-Api-Version", "2022-11-28"))
859        };
860        let resp = self.send_with_retries(make_req, false).await?;
861        let status = resp.status();
862        if !status.is_success() {
863            let body = resp.text().await.unwrap_or_default();
864            Self::maybe_record_rate_limit_from_body(status, &body);
865            anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
866        }
867        let body = resp.text().await?;
868        serde_json::from_str(&body)
869            .with_context(|| format!("failed to parse GitHub API response from GET {url}: {body}"))
870    }
871
872    /// GET raw bytes (for endpoints that return non-JSON or we parse manually).
873    async fn get_bytes(&self, url: &str) -> anyhow::Result<Vec<u8>> {
874        Self::check_backoff(url)?;
875        let auth = self.auth_header(url).await?;
876        let make_req = || {
877            Ok(self
878                .client
879                .get(url)
880                .timeout(READ_TIMEOUT)
881                .header(header::AUTHORIZATION, auth.clone())
882                .header(header::ACCEPT, "application/vnd.github+json")
883                .header("X-GitHub-Api-Version", "2022-11-28"))
884        };
885        let resp = self.send_with_retries(make_req, false).await?;
886        let status = resp.status();
887        if !status.is_success() {
888            let body = resp.text().await.unwrap_or_default();
889            Self::maybe_record_rate_limit_from_body(status, &body);
890            anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
891        }
892        Ok(resp.bytes().await?.to_vec())
893    }
894
895    /// GET with query params, returns deserialized JSON.
896    async fn get_with_query<T: DeserializeOwned>(
897        &self,
898        url: &str,
899        query: &[(&str, &str)],
900    ) -> anyhow::Result<T> {
901        Self::check_backoff(url)?;
902        let auth = self.auth_header(url).await?;
903        let make_req = || {
904            Ok(self
905                .client
906                .get(url)
907                .timeout(READ_TIMEOUT)
908                .query(query)
909                .header(header::AUTHORIZATION, auth.clone())
910                .header(header::ACCEPT, "application/vnd.github+json")
911                .header("X-GitHub-Api-Version", "2022-11-28"))
912        };
913        let resp = self.send_with_retries(make_req, false).await?;
914        let status = resp.status();
915        if !status.is_success() {
916            let body = resp.text().await.unwrap_or_default();
917            Self::maybe_record_rate_limit_from_body(status, &body);
918            anyhow::bail!("GitHub API GET {url} failed ({status}): {body}");
919        }
920        let body = resp.text().await?;
921        serde_json::from_str(&body)
922            .with_context(|| format!("failed to parse GitHub API response from GET {url}: {body}"))
923    }
924
925    /// POST with JSON body, returns raw response text.
926    async fn post_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
927        Self::check_backoff(url)?;
928        let auth = self.auth_header(url).await?;
929        let make_req = || {
930            Ok(self
931                .client
932                .post(url)
933                .json(body)
934                .header(header::AUTHORIZATION, auth.clone())
935                .header(header::ACCEPT, "application/vnd.github+json")
936                .header("X-GitHub-Api-Version", "2022-11-28"))
937        };
938        let resp = self.send_with_retries(make_req, false).await?;
939        let status = resp.status();
940        let text_res = resp.text().await;
941        if !status.is_success() {
942            let text = text_res.unwrap_or_default();
943            Self::maybe_record_rate_limit_from_body(status, &text);
944            anyhow::bail!("GitHub API POST {url} failed ({status}): {text}");
945        }
946        let text = text_res?;
947        Ok(text)
948    }
949
950    /// POST with JSON body, returns deserialized JSON.
951    async fn post_json<T: DeserializeOwned>(
952        &self,
953        url: &str,
954        body: &serde_json::Value,
955    ) -> anyhow::Result<T> {
956        let text = self.post_json_raw(url, body).await?;
957        Ok(serde_json::from_str(&text)?)
958    }
959
960    /// PATCH with JSON body, returns raw response.
961    async fn patch_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
962        Self::check_backoff(url)?;
963        let auth = self.auth_header(url).await?;
964        let make_req = || {
965            Ok(self
966                .client
967                .patch(url)
968                .json(body)
969                .header(header::AUTHORIZATION, auth.clone())
970                .header(header::ACCEPT, "application/vnd.github+json")
971                .header("X-GitHub-Api-Version", "2022-11-28"))
972        };
973        let resp = self.send_with_retries(make_req, false).await?;
974        let status = resp.status();
975        let text_res = resp.text().await;
976        if !status.is_success() {
977            let text = text_res.unwrap_or_default();
978            Self::maybe_record_rate_limit_from_body(status, &text);
979            anyhow::bail!("GitHub API PATCH {url} failed ({status}): {text}");
980        }
981        let text = text_res?;
982        Ok(text)
983    }
984
985    /// Create or replace one file on a branch with a commit, the way the GitHub web editor does
986    pub async fn put_file(
987        &self,
988        repo: &str,
989        path: &str,
990        branch: &str,
991        message: &str,
992        content: &str,
993    ) -> anyhow::Result<()> {
994        let encoded_path = path
995            .split('/')
996            .map(|segment| urlencoding::encode(segment).into_owned())
997            .collect::<Vec<_>>()
998            .join("/");
999        let url = format!("{}/repos/{repo}/contents/{encoded_path}", self.api_root());
1000        // Replacing a file needs the blob it replaces, a new file has none
1001        let current = self
1002            .get_json::<serde_json::Value>(&format!("{url}?ref={}", urlencoding::encode(branch)))
1003            .await
1004            .ok()
1005            .and_then(|v| v.get("sha").and_then(|s| s.as_str()).map(str::to_string));
1006        let mut body = serde_json::json!({
1007            "message": message,
1008            "content": BASE64.encode(content),
1009            "branch": branch,
1010        });
1011        if let Some(sha) = current {
1012            body["sha"] = serde_json::Value::String(sha);
1013        }
1014        self.put_json_raw(&url, &body).await.map(|_| ())
1015    }
1016
1017    /// PUT with JSON body, returns raw response.
1018    async fn put_json_raw(&self, url: &str, body: &serde_json::Value) -> anyhow::Result<String> {
1019        Self::check_backoff(url)?;
1020        let auth = self.auth_header(url).await?;
1021        let make_req = || {
1022            Ok(self
1023                .client
1024                .put(url)
1025                .json(body)
1026                .header(header::AUTHORIZATION, auth.clone())
1027                .header(header::ACCEPT, "application/vnd.github+json")
1028                .header("X-GitHub-Api-Version", "2022-11-28"))
1029        };
1030        let resp = self.send_with_retries(make_req, false).await?;
1031        let status = resp.status();
1032        let text_res = resp.text().await;
1033        if !status.is_success() {
1034            let text = text_res.unwrap_or_default();
1035            Self::maybe_record_rate_limit_from_body(status, &text);
1036            anyhow::bail!("GitHub API PUT {url} failed ({status}): {text}");
1037        }
1038        let text = text_res?;
1039        Ok(text)
1040    }
1041
1042    /// DELETE request.
1043    async fn delete(&self, url: &str) -> anyhow::Result<StatusCode> {
1044        Self::check_backoff(url)?;
1045        let auth = self.auth_header(url).await?;
1046        let make_req = || {
1047            Ok(self
1048                .client
1049                .delete(url)
1050                .header(header::AUTHORIZATION, auth.clone())
1051                .header(header::ACCEPT, "application/vnd.github+json")
1052                .header("X-GitHub-Api-Version", "2022-11-28"))
1053        };
1054        let resp = self.send_with_retries(make_req, false).await?;
1055        let status = resp.status();
1056        if !status.is_success() && status != StatusCode::NOT_FOUND {
1057            let body = resp.text().await.unwrap_or_default();
1058            Self::maybe_record_rate_limit_from_body(status, &body);
1059            anyhow::bail!("GitHub API DELETE {url} failed ({status}): {body}");
1060        }
1061        Ok(status)
1062    }
1063
1064    /// Paginated GET — follows Link: <next> headers, with conditional requests.
1065    ///
1066    /// Each page is sent with `If-None-Match` when a prior ETag is known; GitHub's 304
1067    /// reply is free of quota and the stored body is replayed.
1068    async fn get_all_pages<T: DeserializeOwned>(
1069        &self,
1070        url: &str,
1071        query: &[(&str, &str)],
1072    ) -> anyhow::Result<Vec<T>> {
1073        const MAX_JSON_DECODE_RETRIES: u32 = 2;
1074        const JSON_DECODE_RETRY_BACKOFF_MS: u64 = 200;
1075        Self::check_backoff(url)?;
1076        let mut all: Vec<T> = Vec::new();
1077        let mut next_url: Option<String> = None;
1078        let mut is_first = true;
1079
1080        loop {
1081            let (request_url, request_query) = if is_first {
1082                is_first = false;
1083                (url, Some(query))
1084            } else {
1085                let Some(u) = next_url.as_ref() else { break };
1086                (u.as_str(), None)
1087            };
1088
1089            let cache_key = page_cache_key::<T>(request_url, request_query);
1090            let mut cached_etag = cache_key.as_deref().and_then(page_cache_etag);
1091            let mut decode_attempt = 0;
1092            let (page, next) = loop {
1093                let auth = self.auth_header(request_url).await?;
1094                let mut req = self
1095                    .client
1096                    .get(request_url)
1097                    .timeout(READ_TIMEOUT)
1098                    .header(header::AUTHORIZATION, auth)
1099                    .header(header::ACCEPT, "application/vnd.github+json")
1100                    .header("X-GitHub-Api-Version", "2022-11-28");
1101                if let Some(q) = request_query {
1102                    req = req.query(q);
1103                }
1104                if let Some(etag) = &cached_etag {
1105                    req = req.header(header::IF_NONE_MATCH, etag.clone());
1106                }
1107
1108                let make_req = || {
1109                    req.try_clone()
1110                        .ok_or_else(|| anyhow::anyhow!("request clone failed"))
1111                };
1112                let resp = self.send_with_retries(make_req, false).await?;
1113                let status = resp.status();
1114                let next_from_headers = parse_link_next(resp.headers());
1115                let etag = resp
1116                    .headers()
1117                    .get(header::ETAG)
1118                    .and_then(|v| v.to_str().ok())
1119                    .map(ToString::to_string);
1120                let content_type = resp
1121                    .headers()
1122                    .get(header::CONTENT_TYPE)
1123                    .and_then(|v| v.to_str().ok())
1124                    .map_or_else(|| "<missing>".to_string(), ToString::to_string);
1125
1126                if status == StatusCode::NOT_MODIFIED {
1127                    if let Some((body, next)) = cache_key.as_deref().and_then(page_cache_hit) {
1128                        break (serde_json::from_str::<Vec<T>>(&body)?, next);
1129                    }
1130                    // The entry is normally there, since If-None-Match is only sent
1131                    // when it is, but the size cap can clear the map in between.
1132                    // Dropping the ETag makes the retry unconditional, so the loop
1133                    // cannot see a second 304
1134                    cached_etag = None;
1135                    continue;
1136                }
1137
1138                if !status.is_success() {
1139                    let body = resp.text().await.unwrap_or_default();
1140                    Self::maybe_record_rate_limit_from_body(status, &body);
1141                    anyhow::bail!("GitHub API GET (paginated) failed ({status}): {body}");
1142                }
1143
1144                let text = resp.text().await?;
1145                match serde_json::from_str::<Vec<T>>(&text) {
1146                    Ok(page) => {
1147                        if let (Some(key), Some(etag)) = (cache_key.clone(), etag) {
1148                            page_cache_store(key, etag, text, next_from_headers.clone());
1149                        }
1150                        break (page, next_from_headers);
1151                    }
1152                    Err(err) => {
1153                        let snippet: String = text.chars().take(200).collect();
1154                        let decode_error = anyhow::anyhow!(
1155                            "GitHub API GET (paginated) JSON decode failed ({status}, content-type={content_type}): {snippet}"
1156                        )
1157                        .context(err);
1158                        if decode_attempt < MAX_JSON_DECODE_RETRIES {
1159                            decode_attempt += 1;
1160                            tracing::warn!(
1161                                attempt = decode_attempt,
1162                                max_attempts = MAX_JSON_DECODE_RETRIES,
1163                                status = %status,
1164                                content_type,
1165                                err = %decode_error,
1166                                "json decode failed; retrying paginated GET"
1167                            );
1168                            time::sleep(Duration::from_millis(
1169                                JSON_DECODE_RETRY_BACKOFF_MS * u64::from(decode_attempt),
1170                            ))
1171                            .await;
1172                            continue;
1173                        }
1174                        return Err(decode_error);
1175                    }
1176                }
1177            };
1178
1179            next_url = next;
1180            all.extend(page);
1181
1182            if next_url.is_none() {
1183                break;
1184            }
1185        }
1186
1187        Ok(all)
1188    }
1189
1190    /// Paginated GET for GitHub endpoints that return a wrapper object instead of a raw
1191    /// array.  Each page is expected to look like `{ "<array_field>": [...], ... }`.
1192    /// The function extracts `array_field` from every page and appends the elements
1193    /// to the accumulated result, following `Link: <next>` headers until exhausted.
1194    ///
1195    /// This is necessary for endpoints such as `/commits/{sha}/check-runs` which
1196    /// return `{ "total_count": N, "check_runs": [...] }` rather than a bare `[...]`
1197    /// array.  Using `get_all_pages` on those endpoints would fail at the
1198    /// `serde_json::from_str::<Vec<T>>` step because the body is an object, not an
1199    /// array.
1200    async fn get_all_pages_from_wrapper<T: DeserializeOwned>(
1201        &self,
1202        url: &str,
1203        array_field: &str,
1204    ) -> anyhow::Result<Vec<T>> {
1205        Self::check_backoff(url)?;
1206        let mut all: Vec<T> = Vec::new();
1207        let mut current_url: String = url.to_string();
1208
1209        loop {
1210            let auth = self.auth_header(&current_url).await?;
1211            let make_req = || {
1212                self.client
1213                    .get(&current_url)
1214                    .timeout(READ_TIMEOUT)
1215                    .header(header::AUTHORIZATION, auth.clone())
1216                    .header(header::ACCEPT, "application/vnd.github+json")
1217                    .header("X-GitHub-Api-Version", "2022-11-28")
1218                    .try_clone()
1219                    .ok_or_else(|| anyhow::anyhow!("request clone failed"))
1220            };
1221            let resp = self.send_with_retries(make_req, false).await?;
1222            let status = resp.status();
1223            let next = parse_link_next(resp.headers());
1224
1225            if !status.is_success() {
1226                let body = resp.text().await.unwrap_or_default();
1227                Self::maybe_record_rate_limit_from_body(status, &body);
1228                anyhow::bail!(
1229                    "GitHub API GET (wrapped paginated) {current_url} failed ({status}): {body}"
1230                );
1231            }
1232
1233            let body = resp.text().await?;
1234            let wrapper: serde_json::Value = serde_json::from_str(&body).with_context(|| {
1235                format!("failed to parse wrapper response from {current_url}: {body}")
1236            })?;
1237            let items = wrapper
1238                .get(array_field)
1239                .and_then(|v| v.as_array())
1240                .cloned()
1241                .unwrap_or_default();
1242
1243            for item in items {
1244                match serde_json::from_value::<T>(item) {
1245                    Ok(v) => all.push(v),
1246                    Err(e) => {
1247                        tracing::warn!(
1248                            field = array_field,
1249                            err = %e,
1250                            "skipping item that failed to deserialize in wrapped pagination"
1251                        );
1252                    }
1253                }
1254            }
1255
1256            match next {
1257                Some(next_url) => current_url = next_url,
1258                None => break,
1259            }
1260        }
1261
1262        Ok(all)
1263    }
1264
1265    /// POST to the GraphQL endpoint. Uses separate rate-limit tracking from REST.
1266    async fn graphql_request(
1267        &self,
1268        query: &str,
1269        extra_headers: &[(&str, &str)],
1270        variables: Option<serde_json::Value>,
1271    ) -> anyhow::Result<serde_json::Value> {
1272        self.graphql_request_to_url(
1273            &format!("{GITHUB_API}/graphql"),
1274            query,
1275            extra_headers,
1276            variables,
1277        )
1278        .await
1279    }
1280
1281    async fn graphql_request_to_url(
1282        &self,
1283        url: &str,
1284        query: &str,
1285        extra_headers: &[(&str, &str)],
1286        variables: Option<serde_json::Value>,
1287    ) -> anyhow::Result<serde_json::Value> {
1288        Self::check_graphql_backoff(url)?;
1289        let body = if let Some(vars) = variables {
1290            serde_json::json!({ "query": query, "variables": vars })
1291        } else {
1292            serde_json::json!({ "query": query })
1293        };
1294        let auth = self.auth_header(url).await?;
1295        let mut req = self
1296            .client
1297            .post(url)
1298            .timeout(graphql_timeout(query))
1299            .json(&body)
1300            .header(header::AUTHORIZATION, auth)
1301            .header(header::ACCEPT, "application/vnd.github+json")
1302            .header("X-GitHub-Api-Version", "2022-11-28");
1303
1304        for (k, v) in extra_headers {
1305            req = req.header(*k, *v);
1306        }
1307
1308        // Use send_with_retries wrapper for GraphQL (is_graphql = true)
1309        let make_req = || {
1310            req.try_clone()
1311                .ok_or_else(|| anyhow::anyhow!("graphql request clone failed"))
1312        };
1313        let resp = self.send_with_retries(make_req, true).await?;
1314        let status = resp.status();
1315        let text_res = resp.text().await;
1316        if !status.is_success() {
1317            let text = text_res.unwrap_or_default();
1318            Self::maybe_record_graphql_rate_limit_from_body(status, &text);
1319            anyhow::bail!("GitHub GraphQL failed ({status}): {text}");
1320        }
1321        let text = text_res?;
1322        let json: serde_json::Value = serde_json::from_str(&text)?;
1323        // GraphQL always returns 200 even for errors; check the errors field explicitly.
1324        if let Some(errors) = json.get("errors").and_then(|e| e.as_array())
1325            && !errors.is_empty()
1326        {
1327            let messages: Vec<&str> = errors
1328                .iter()
1329                .filter_map(|e| e.get("message").and_then(|m| m.as_str()))
1330                .collect();
1331            if json.get("data").is_none() || json["data"].is_null() {
1332                // No data at all — surface the errors as a proper error.
1333                anyhow::bail!("GitHub GraphQL errors: {}", messages.join("; "));
1334            }
1335            // Partial data alongside errors — log and continue.
1336            tracing::warn!(errors = ?messages, "GitHub GraphQL returned partial errors");
1337        }
1338        Ok(json)
1339    }
1340
1341    // ── Public API (mirrors GhCli) ───────────────────────────────
1342
1343    pub async fn graphql_with_vars(
1344        &self,
1345        query: &str,
1346        variables: serde_json::Value,
1347    ) -> anyhow::Result<serde_json::Value> {
1348        self.graphql_request(query, &[], Some(variables)).await
1349    }
1350
1351    pub async fn graphql_with_headers(
1352        &self,
1353        query: &str,
1354        headers: &[&str],
1355    ) -> anyhow::Result<serde_json::Value> {
1356        // Convert "Key:Value" strings to (&str, &str) tuples.
1357        let pairs: Vec<(&str, &str)> = headers.iter().filter_map(|h| h.split_once(':')).collect();
1358        self.graphql_request(query, &pairs, None).await
1359    }
1360
1361    pub async fn graphql_with_headers_and_vars(
1362        &self,
1363        query: &str,
1364        headers: &[&str],
1365        variables: serde_json::Value,
1366    ) -> anyhow::Result<serde_json::Value> {
1367        let pairs: Vec<(&str, &str)> = headers.iter().filter_map(|h| h.split_once(':')).collect();
1368        self.graphql_request(query, &pairs, Some(variables)).await
1369    }
1370}
1371
1372/// A branch protection read that means "no protection": 404 "Branch not protected", or the 403
1373/// True when `text` carries the HTTP status in the `failed (404 ...)` form that every request error
1374/// here uses, or `HTTP 404` from the CLI. The status code sits apart from the URL, so an issue
1375/// number such as 1404 does not match
1376pub fn has_status(text: &str, status: u16) -> bool {
1377    text.contains(&format!("failed ({status}")) || text.contains(&format!("HTTP {status}"))
1378}
1379
1380fn sanitize_github_issue_numbers(issue_numbers: &[u64]) -> (Vec<u64>, Vec<u64>) {
1381    let mut valid = Vec::with_capacity(issue_numbers.len());
1382    let mut invalid = Vec::new();
1383    for &issue_number in issue_numbers {
1384        if issue_number == 0 {
1385            invalid.push(issue_number);
1386        } else {
1387            valid.push(issue_number);
1388        }
1389    }
1390    (valid, invalid)
1391}
1392
1393// ── Public metrics ───────────────────────────────────────────────────
1394
1395/// Snapshot of GitHub API rate-limit metrics.
1396#[derive(Debug, Clone)]
1397pub struct RateLimitMetrics {
1398    /// Total 403/429 rate-limit responses received (REST + GraphQL combined).
1399    pub hits: u64,
1400    /// Calls skipped because the quota was low or a backoff was active.
1401    pub skipped_calls: u64,
1402    /// Current REST remaining quota (None if not yet observed).
1403    pub rest_remaining: Option<u32>,
1404    /// UTC epoch second when the REST window resets (None if not yet observed).
1405    pub rest_reset_at: Option<u64>,
1406    /// Current GraphQL remaining quota (None if not yet observed).
1407    pub graphql_remaining: Option<u32>,
1408    /// Total 5xx server error responses received (REST + GraphQL combined).
1409    pub five_xx_hits: u64,
1410}
1411
1412/// Return a snapshot of GitHub API rate-limit metrics.
1413pub fn rate_limit_metrics() -> RateLimitMetrics {
1414    let (rest_remaining, rest_reset_at) = REST_RATE_LIMIT
1415        .lock()
1416        .ok()
1417        .map_or((None, None), |rl| (rl.remaining, rl.reset_at));
1418    let graphql_remaining = GRAPHQL_RATE_LIMIT.lock().ok().and_then(|rl| rl.remaining);
1419    RateLimitMetrics {
1420        hits: METRIC_RATE_LIMIT_HITS.load(Ordering::Relaxed),
1421        skipped_calls: METRIC_PROACTIVE_THROTTLES.load(Ordering::Relaxed),
1422        rest_remaining,
1423        rest_reset_at,
1424        graphql_remaining,
1425        five_xx_hits: METRIC_5XX_HITS.load(Ordering::Relaxed),
1426    }
1427}
1428
1429// ── Link header parser ───────────────────────────────────────────────
1430
1431/// Parse the `Link` header to find the `rel="next"` URL.
1432fn parse_link_next(headers: &header::HeaderMap) -> Option<String> {
1433    let link = headers.get("link")?.to_str().ok()?;
1434    for part in link.split(',') {
1435        let part = part.trim();
1436        if part.contains("rel=\"next\"") {
1437            // Extract URL between < and >
1438            let start = part.find('<')? + 1;
1439            let end = part.find('>')?;
1440            if start >= end {
1441                return None;
1442            }
1443            return Some(part[start..end].to_string());
1444        }
1445    }
1446    None
1447}
1448
1449/// Return the hex color string for a given `status:*` label.
1450pub fn status_label_color(label: &str) -> &'static str {
1451    match label {
1452        "status:new" => "0e8a16",
1453        "status:routed" => "1d76db",
1454        "status:in_progress" => "fbca04",
1455        "status:done" => "6f42c1",
1456        "status:blocked" => "d73a4a",
1457        "status:in_review" => "0075ca",
1458        "status:approved" => "2ea44f",
1459        "status:needs_review" => "e4e669",
1460        "status:waiting" => "5319e7",
1461        _ => "c5def5",
1462    }
1463}
1464
1465// ── Batch GraphQL helpers ─────────────────────────────────────────────
1466
1467#[cfg(test)]
1468mod tests;