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