//! PDS error classification. //! //! Raw XRPC responses keep their status, headers and body, so every failure is //! classified here instead of by an exception type: a `401` on a write is an //! expired access token worth refreshing, a `500` naming `too large` is a //! record that must be skipped, and a `429` carries the delay before the next //! attempt. use std::collections::HashMap; use std::time::{SystemTime, UNIX_EPOCH}; use serde_json::{Value, json}; use thiserror::Error; use crate::constants::{RATE_LIMIT_BACKOFF_MAX, RATE_LIMIT_BACKOFF_START}; use crate::log::Logger; use crate::metrics::round3; use crate::time::Time; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PdsErrorKind { Transient, RateLimited, Unauthorized, TooLarge, NotFound, AlreadyExists, Other, } #[derive(Debug, Clone, Error)] #[error("{message}")] pub struct PdsError { pub kind: PdsErrorKind, pub status: Option, pub message: String, pub retry_after: Option, } impl PdsError { pub fn new(kind: PdsErrorKind, message: impl Into) -> Self { Self { kind, status: None, message: message.into(), retry_after: None, } } } /// Classify one XRPC answer (or a transport failure, when `status` is `None`). /// /// `body_text` is the response body decoded as text; it is never logged. The /// HTTP-date form of `Retry-After` is resolved against the current wall clock; /// [`classify_at`] takes the clock explicitly for deterministic tests. pub fn classify( status: Option, headers: &HashMap, body_text: &str, transport_error: Option<&str>, ) -> PdsError { classify_at(status, headers, body_text, transport_error, now_unix()) } /// [`classify`] with an explicit "now" for `Retry-After` HTTP dates. pub fn classify_at( status: Option, headers: &HashMap, body_text: &str, transport_error: Option<&str>, now_unix: f64, ) -> PdsError { let Some(status) = status else { return PdsError { kind: PdsErrorKind::Transient, status: None, message: transport_error.unwrap_or("transport error").to_owned(), retry_after: None, }; }; let text = body_text.trim(); let lowered = text.to_ascii_lowercase(); let message = if text.is_empty() { format!("HTTP {status}") } else { text.to_owned() }; let kind = if matches!(status, 401 | 403) || (status == 400 && mentions_token_problem(&lowered)) { PdsErrorKind::Unauthorized } else if matches!(status, 400 | 413 | 500) && (lowered.contains("too large") || lowered.contains("max 65536")) { PdsErrorKind::TooLarge } else if matches!(status, 400 | 404) && (lowered.contains("recordnotfound") || lowered.contains("could not locate record") || lowered.contains("not found")) { PdsErrorKind::NotFound } else if matches!(status, 400 | 409) && (lowered.contains("recordalreadyexists") || lowered.contains("already exists") || lowered.contains("record key already") || lowered.contains("invalidswap")) { PdsErrorKind::AlreadyExists } else if status == 429 { PdsErrorKind::RateLimited } else if status >= 500 { PdsErrorKind::Transient } else { PdsErrorKind::Other }; let retry_after = if kind == PdsErrorKind::RateLimited { header_value(headers, "retry-after").and_then(|value| parse_retry_after(&value, now_unix)) } else { None }; PdsError { kind, status: Some(status), message, retry_after, } } fn mentions_token_problem(lowered: &str) -> bool { (lowered.contains("expired") || lowered.contains("invalid")) && lowered.contains("token") } /// Parse `Retry-After`: a numeric number of seconds first, else an HTTP date. pub fn parse_retry_after(value: &str, now_unix: f64) -> Option { let value = value.trim(); if let Ok(seconds) = value.parse::() { return Some(seconds.max(0.0)); } let retry_at = httpdate::parse_http_date(value).ok()?; let retry_at = retry_at .duration_since(UNIX_EPOCH) .map(|d| d.as_secs_f64()) .unwrap_or(0.0); Some((retry_at - now_unix).max(0.0)) } /// Backoff for a rate-limited attempt: `Retry-After`, else 60s doubling with /// jitter, capped at 1800s. /// /// `RateLimit-Reset` needs the headers, so the publisher uses /// [`rate_limit_delay_from_headers`], which also honours it. pub fn rate_limit_delay(error: &PdsError, attempt: u32, time: &dyn Time) -> f64 { if let Some(delay) = error.retry_after { return delay; } backoff(attempt) + time.jitter(5.0) } /// `Retry-After` first, else `RateLimit-Reset` (epoch seconds) plus jitter, /// else the exponential backoff plus jitter. pub fn rate_limit_delay_from_headers( error: &PdsError, headers: &HashMap, attempt: u32, time: &dyn Time, ) -> f64 { if let Some(delay) = error.retry_after { return delay; } if let Some(reset) = header_int(headers, "ratelimit-reset") { return (reset as f64 - time.now_unix()).max(0.0) + time.jitter(5.0); } backoff(attempt) + time.jitter(5.0) } fn backoff(attempt: u32) -> f64 { let exponent = attempt.saturating_sub(1).min(31) as i32; (RATE_LIMIT_BACKOFF_START * 2f64.powi(exponent)).min(RATE_LIMIT_BACKOFF_MAX) } /// Log one `pds_rate_limited` event. Bodies are never included. #[allow(clippy::too_many_arguments)] pub fn log_rate_limited( logger: &Logger, error: &PdsError, headers: &HashMap, op: &str, cve: Option<&str>, slug: Option<&str>, delay: f64, attempt: u32, ) { let now = now_unix(); logger.warn( "pds_rate_limited", None, json!({ "op": op, "status": error.status.unwrap_or(429), "retry_after": header_value(headers, "retry-after") .and_then(|value| parse_retry_after(&value, now)) .map(Value::from) .unwrap_or(Value::Null), "remaining": header_int(headers, "ratelimit-remaining").map(Value::from).unwrap_or(Value::Null), "reset": header_int(headers, "ratelimit-reset").map(Value::from).unwrap_or(Value::Null), "limit": header_int(headers, "ratelimit-limit").map(Value::from).unwrap_or(Value::Null), "attempt": attempt, "sleep_seconds": round3(delay), "cve": cve, "slug": slug, }), ); } /// Case-insensitive header lookup (real responses arrive lowercased; fakes in /// tests may not be). pub fn header_value(headers: &HashMap, name: &str) -> Option { if let Some(value) = headers.get(name) { return Some(value.clone()); } headers .iter() .find(|(key, _)| key.eq_ignore_ascii_case(name)) .map(|(_, value)| value.clone()) } pub fn header_int(headers: &HashMap, name: &str) -> Option { header_value(headers, name).and_then(|value| value.trim().parse::().ok()) } fn now_unix() -> f64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|duration| duration.as_secs_f64()) .unwrap_or(0.0) }