ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
Documentation
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::time::{Duration, SystemTime, UNIX_EPOCH};

use reqwest::StatusCode;
use reqwest::header::HeaderMap;

/// Statuses worth an inline retry. Each maps to a transient `LlmErrorKind`
/// (via `http_status_to_kind`), so a budget that runs out hands off to the
/// caller-level retry instead of dead-ending. 425 TOO_EARLY is absent: it
/// classifies as `InvalidRequest`, and no LLM provider emits it.
const DEFAULT_RETRY_STATUSES: &[StatusCode] = &[
    StatusCode::TOO_MANY_REQUESTS,
    StatusCode::REQUEST_TIMEOUT,
    StatusCode::BAD_GATEWAY,
    StatusCode::SERVICE_UNAVAILABLE,
    StatusCode::GATEWAY_TIMEOUT,
    StatusCode::INTERNAL_SERVER_ERROR,
];

/// Budget for the quiet, per-request retry loop inside
/// [`Client`](crate::client::Client): a couple of fast retries that
/// absorb connection blips, not outages. Persistence belongs to caller-level
/// retries, which surface sustained failures
/// quickly, show the wait to the user, and can be cancelled.
#[derive(Debug, Clone)]
pub struct RetryPolicy {
    pub max_count: u32,
    pub base_delay: Duration,
    /// Cap on a single inline delay, and the longest `Retry-After` this layer
    /// honors: a longer wait is not truncated; the attempt is given up and
    /// the wait rides out on the classified error for the caller-level retry.
    pub max_delay: Duration,
    pub retry_on_statuses: &'static [StatusCode],
}

impl Default for RetryPolicy {
    fn default() -> Self {
        RetryPolicy {
            max_count: 2,
            base_delay: Duration::from_millis(250),
            max_delay: Duration::from_secs(2),
            retry_on_statuses: DEFAULT_RETRY_STATUSES,
        }
    }
}

impl RetryPolicy {
    pub(crate) fn should_retry_status(&self, status: StatusCode) -> bool {
        self.retry_on_statuses.contains(&status)
    }

    /// Transient transport failures. `is_decode` covers errors surfaced while
    /// reading the response body after a success status (e.g. a connection
    /// reset mid-body, which reqwest reports as a decode error wrapping a
    /// body error).
    pub(crate) fn should_retry_error(&self, err: &reqwest::Error) -> bool {
        err.is_timeout() || err.is_connect() || err.is_request() || err.is_body() || err.is_decode()
    }

    pub(crate) fn next_delay(&self, attempt: u32) -> Duration {
        // Exponential growth: base * 2^attempt, capped at max
        let exp = 1u32 << attempt.min(24);
        let mut delay = self.base_delay.checked_mul(exp).unwrap_or(self.max_delay);
        if delay > self.max_delay {
            delay = self.max_delay;
        }

        // Full jitter in [0, delay]
        let delay_ms = delay.as_millis();
        if delay_ms == 0 {
            return delay;
        }
        let now_ns = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or(Duration::from_millis(0))
            .as_nanos();
        let jitter_ms = (now_ns % (delay_ms + 1)) as u64;
        Duration::from_millis(jitter_ms)
    }
}

pub(crate) fn retry_after_header(headers: &HeaderMap) -> Option<Duration> {
    let value = headers.get("Retry-After")?.to_str().ok()?;
    parse_retry_after(value, chrono::Utc::now())
}

/// RFC 7231 `Retry-After`: either delay-seconds or an HTTP-date (IMF-fixdate,
/// which RFC 2822 parsing accepts). A date in the past means "retry now".
/// `None` falls back to exponential backoff.
fn parse_retry_after(value: &str, now: chrono::DateTime<chrono::Utc>) -> Option<Duration> {
    let value = value.trim();
    if let Ok(secs) = value.parse::<u64>() {
        return Some(Duration::from_secs(secs));
    }
    let date = chrono::DateTime::parse_from_rfc2822(value).ok()?;
    Some(date.signed_duration_since(now).to_std().unwrap_or(Duration::ZERO))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn now() -> chrono::DateTime<chrono::Utc> {
        chrono::DateTime::parse_from_rfc3339("2026-06-09T12:00:00Z").unwrap().to_utc()
    }

    #[test]
    fn parse_retry_after_integer_seconds() {
        assert_eq!(parse_retry_after("30", now()), Some(Duration::from_secs(30)));
        assert_eq!(parse_retry_after(" 5 ", now()), Some(Duration::from_secs(5)));
    }

    #[test]
    fn parse_retry_after_http_date() {
        let delay = parse_retry_after("Tue, 09 Jun 2026 12:00:42 GMT", now());
        assert_eq!(delay, Some(Duration::from_secs(42)));
        // A date in the past means retry now.
        let delay = parse_retry_after("Tue, 09 Jun 2026 11:59:00 GMT", now());
        assert_eq!(delay, Some(Duration::ZERO));
    }

    #[test]
    fn parse_retry_after_garbage_is_none() {
        assert_eq!(parse_retry_after("soonish", now()), None);
        assert_eq!(parse_retry_after("", now()), None);
    }
}