1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
//! 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<u16>,
pub message: String,
pub retry_after: Option<f64>,
}
impl PdsError {
pub fn new(kind: PdsErrorKind, message: impl Into<String>) -> 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<u16>,
headers: &HashMap<String, String>,
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<u16>,
headers: &HashMap<String, String>,
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<f64> {
let value = value.trim();
if let Ok(seconds) = value.parse::<f64>() {
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<String, String>,
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<String, String>,
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<String, String>, name: &str) -> Option<String> {
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<String, String>, name: &str) -> Option<i64> {
header_value(headers, name).and_then(|value| value.trim().parse::<i64>().ok())
}
fn now_unix() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_secs_f64())
.unwrap_or(0.0)
}