polyoxide-core 0.48.0

Core utilities and shared types for the polyoxide venue clients: the HTTP send loop and its hooks, window quotas, capacity buckets and holds, errors and macros
Documentation
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
use std::time::Duration;

use http::header::{HeaderMap, RETRY_AFTER};
use http::StatusCode;
use polyoxide_venue::{class_for_status, parse_retry_after, Class, Classify};
use thiserror::Error;

use crate::hooks::Refused;
use crate::transport::TransportError;

/// An unsuccessful response, read whole: what [`ApiError::Response`] carries.
///
/// The send loop builds one when the client's policy fails a response, and a
/// venue's `From<ApiError>` decodes its own body shape from [`body`](Self::body).
///
/// Its `Debug`, which the `Request failed` ERROR line prints, names the
/// headers without their values and truncates the message and the body.
#[derive(Clone)]
#[non_exhaustive]
pub struct ErrorResponse {
    /// The response's status.
    pub status: StatusCode,
    /// The response's headers.
    pub headers: HeaderMap,
    /// The response's body, verbatim, or `""` when it could not be read.
    pub body: String,
    /// The body's `error` field, else its `message` field, else the body
    /// verbatim: the shape most venue hosts answer with.
    pub message: String,
    /// The response's `Retry-After`, read by
    /// [`polyoxide_venue::parse_retry_after`] with no clamp, since it is
    /// surfaced, never slept on. A zero is `None`.
    pub retry_after: Option<Duration>,
}

impl ErrorResponse {
    /// An unsuccessful response from its parts, its message and `Retry-After`
    /// read from them.
    pub fn new(status: StatusCode, headers: HeaderMap, body: impl Into<String>) -> Self {
        let body = body.into();
        let message = serde_json::from_str::<serde_json::Value>(&body)
            .ok()
            .and_then(|v| {
                v.get("error")
                    .or(v.get("message"))
                    .and_then(|m| m.as_str())
                    .map(String::from)
            })
            .unwrap_or_else(|| body.clone());
        let retry_after = headers
            .get(RETRY_AFTER)
            .and_then(|value| value.to_str().ok())
            .and_then(|value| parse_retry_after(value, Duration::MAX));
        Self {
            status,
            headers,
            body,
            message,
            retry_after,
        }
    }

    /// Read `response` whole. A body that cannot be read is `""`.
    pub async fn read(response: crate::Response) -> Self {
        let status = response.status();
        let headers = response.headers().clone();
        let body = response.text().await.unwrap_or_default();
        tracing::debug!("API error response body: {}", body);
        Self::new(status, headers, body)
    }
}

/// Written by hand so a log line never carries a header's value (a token, a
/// cookie) or an unbounded body.
impl std::fmt::Debug for ErrorResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let header_names: Vec<&str> = self.headers.keys().map(|name| name.as_str()).collect();
        f.debug_struct("ErrorResponse")
            .field("status", &self.status)
            .field("headers", &header_names)
            .field("message", &crate::truncate_for_log(&self.message))
            .field("body", &crate::truncate_for_log(&self.body))
            .field("retry_after", &self.retry_after)
            .finish()
    }
}

/// Core API error types shared across Polyoxide clients
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum ApiError {
    /// The server answered with an unsuccessful status. Its class is the
    /// status's.
    #[error("API error: {} - {}", .0.status.as_u16(), .0.message)]
    Response(Box<ErrorResponse>),

    /// The client refused the request before sending it: bad input, or
    /// missing configuration.
    #[error("Validation error: {0}")]
    Validation(String),

    /// The transport failed: no response arrived, or its body could not be
    /// read. Its class is its kind's.
    #[error("Transport error: {0}")]
    Transport(#[from] TransportError),

    /// JSON serialization/deserialization error
    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    /// URL parsing error
    #[error("URL error: {0}")]
    Url(#[from] url::ParseError),

    /// The throttle refused a cost no layer can ever hold, and nothing was
    /// sent.
    #[error("Refused before sending: {0}")]
    Refused(#[from] Refused),

    /// An [`Authenticator`](crate::Authenticator) could not sign the request,
    /// and nothing was sent. Carries the venue's own error, which the venue's
    /// `From<ApiError>` takes back out.
    #[error("Signing failed: {0}")]
    Sign(Box<dyn std::error::Error + Send + Sync>),
}

impl ApiError {
    /// Read an unsuccessful response whole, as [`ApiError::Response`].
    pub async fn from_response(response: crate::Response) -> Self {
        ErrorResponse::read(response).await.into()
    }
}

impl From<ErrorResponse> for ApiError {
    fn from(response: ErrorResponse) -> Self {
        Self::Response(Box::new(response))
    }
}

/// The status rule, with any status outside 400–599 a [`Class::Decode`].
fn status_class(status: u16) -> Class {
    class_for_status(status).unwrap_or(Class::Decode)
}

/// The class each variant reports.
///
/// [`ApiError::Response`] follows the status rule, with any status outside
/// 400–599 a [`Class::Decode`] (a 2xx that a caller found wanting, such as a
/// ping whose body says it is not ok), and a `429`'s wait its `Retry-After`.
/// A 451 is not a fault: the venue does not serve the caller's region, as
/// designed. [`ApiError::Validation`] and [`ApiError::Sign`] are a
/// [`Class::InvalidRequest`]: the client refused the request, or could not
/// sign it, and nothing was sent.
///
/// [`Classify::retry_after`] is a response's `Retry-After` whatever its
/// status, and `None` for every other variant.
impl Classify for ApiError {
    fn class(&self) -> Class {
        match self {
            Self::Response(response) => {
                status_class(response.status.as_u16()).with_retry_after(response.retry_after)
            }
            Self::Validation(_) => Class::InvalidRequest,
            Self::Transport(err) => err.class(),
            Self::Serialization(_) => Class::Decode,
            Self::Url(_) => Class::InvalidRequest,
            Self::Refused(refused) => refused.class(),
            Self::Sign(_) => Class::InvalidRequest,
        }
    }

    fn is_fault(&self) -> bool {
        !matches!(self, Self::Response(response)
            if response.status == StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS)
    }

    fn retry_after(&self) -> Option<Duration> {
        match self {
            Self::Response(response) => response.retry_after,
            _ => None,
        }
    }
}

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

    /// A response with `status`, `body` and, when given, a `Retry-After`.
    fn response(status: u16, body: &str, retry_after: Option<&str>) -> ErrorResponse {
        let mut headers = HeaderMap::new();
        if let Some(value) = retry_after {
            headers.insert(RETRY_AFTER, value.parse().unwrap());
        }
        ErrorResponse::new(StatusCode::from_u16(status).unwrap(), headers, body)
    }

    fn api(status: u16) -> ApiError {
        response(status, "", None).into()
    }

    /// A transport failure of `kind`, caused by `source`.
    fn transport(
        kind: TransportKind,
        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
    ) -> ApiError {
        ApiError::Transport(TransportError::new(kind, source))
    }

    #[test]
    fn test_rate_limit_error_carries_message() {
        let err = ApiError::from(response(
            429,
            r#"{"error":"too many requests, retry after 5s"}"#,
            None,
        ));
        let display = format!("{}", err);
        assert!(
            display.contains("too many requests"),
            "A 429's display should contain the message: {}",
            display
        );
    }

    #[test]
    fn test_rate_limit_error_display_format() {
        let err = ApiError::from(response(429, r#"{"error":"slow down"}"#, None));
        assert_eq!(format!("{}", err), "API error: 429 - slow down");
    }

    // ── ErrorResponse ───────────────────────────────────────────

    #[test]
    fn test_error_response_reads_error_then_message() {
        let bad = response(400, r#"{"error":"bad limit"}"#, None);
        assert_eq!(bad.message, "bad limit");
        assert_eq!(bad.body, r#"{"error":"bad limit"}"#);
        assert_eq!(response(503, r#"{"message":"down"}"#, None).message, "down");
        assert_eq!(
            response(503, r#"{"error":"first","message":"second"}"#, None).message,
            "first"
        );
    }

    #[test]
    fn test_error_response_keeps_a_non_json_body_verbatim() {
        // Cloudflare's IP block is plain text, not JSON.
        let blocked = response(429, "error code: 1015", None);
        assert_eq!(blocked.message, "error code: 1015");
        assert_eq!(blocked.status, StatusCode::TOO_MANY_REQUESTS);
    }

    #[test]
    fn test_error_response_reads_retry_after_unclamped() {
        let at = |value| response(429, "", Some(value)).retry_after;
        assert_eq!(at("7"), Some(Duration::from_secs(7)));
        assert_eq!(at("1.5"), Some(Duration::from_millis(1500)));
        // Surfaced, never slept on, so a week stays a week.
        assert_eq!(at("604800"), Some(Duration::from_secs(604_800)));
        // A zero is no wait (DRIFT R4), and junk is none.
        for junk in ["0", "0.0", "-1", "soon", "Wed, 21 Oct 2026 07:28:00 GMT"] {
            assert_eq!(at(junk), None, "{junk:?}");
        }
        assert_eq!(response(429, "", None).retry_after, None);
    }

    #[test]
    fn test_error_response_debug_is_bounded_and_names_headers_only() {
        let mut headers = HeaderMap::new();
        headers.insert("authorization", "Bearer s3cr3t-t0ken".parse().unwrap());
        headers.insert("set-cookie", "session=c00kie-value".parse().unwrap());
        // Not JSON, so the message is the body too.
        let body = "x".repeat(10_000);
        let response = ErrorResponse::new(StatusCode::BAD_GATEWAY, headers, body);

        let debug = format!("{:?}", ApiError::from(response));
        assert!(
            debug.len() < 1_500,
            "{} bytes of Debug for a 10 kB body",
            debug.len()
        );
        assert!(debug.contains("authorization") && debug.contains("set-cookie"));
        assert!(
            !debug.contains("s3cr3t-t0ken") && !debug.contains("c00kie-value"),
            "{debug}"
        );
        assert!(debug.starts_with("Response(ErrorResponse { status: 502,"));
    }

    #[test]
    fn test_response_display_is_the_status_and_message() {
        let err = ApiError::from(response(503, r#"{"error":"bad gateway"}"#, None));
        assert_eq!(err.to_string(), "API error: 503 - bad gateway");
        assert_eq!(
            ApiError::Validation("bad request".into()).to_string(),
            "Validation error: bad request"
        );
    }

    // ── retriability, through the class ─────────────────────────

    #[test]
    fn test_retriable_transient_failures() {
        assert!(Classify::is_retriable(&api(429)));
        assert!(Classify::is_retriable(&api(408)));
        for status in [500u16, 502, 503, 504] {
            assert!(
                Classify::is_retriable(&api(status)),
                "{status} should be retriable"
            );
        }
    }

    #[test]
    fn test_retriable_425_too_early() {
        // A venue returns 425 while its matching engine restarts and documents
        // it as "retry with exponential backoff".
        assert!(Classify::is_retriable(&api(425)));
    }

    #[test]
    fn test_not_retriable_deterministic_failures() {
        assert!(!Classify::is_retriable(&ApiError::Validation(
            "bad payload".into()
        )));
        assert!(!Classify::is_retriable(&api(400)));
        assert!(!Classify::is_retriable(&api(401)));
        for status in [404u16, 409, 418] {
            assert!(
                !Classify::is_retriable(&api(status)),
                "{status} should not be retriable"
            );
        }
    }

    #[test]
    fn test_not_retriable_local_encode_decode_failures() {
        let json_err = serde_json::from_str::<String>("not json").unwrap_err();
        assert!(!Classify::is_retriable(&ApiError::Serialization(json_err)));
        let url_err = url::Url::parse("://bad").unwrap_err();
        assert!(!Classify::is_retriable(&ApiError::Url(url_err)));
    }

    // ── Classify ────────────────────────────────────────────────

    /// The source text of a transport failure of each kind a transport
    /// reports. The names stay as the baseline's, whose items held real
    /// reqwest errors; a `TransportError` only displays its source.
    struct ReqwestErrors {
        builder: &'static str,
        cut_off: &'static str,
        connect: &'static str,
        timeout: &'static str,
    }

    fn reqwest_errors() -> ReqwestErrors {
        ReqwestErrors {
            builder: "not a url",
            cut_off: "connection closed before the body ended",
            connect: "connection refused",
            timeout: "operation timed out",
        }
    }

    #[test]
    fn every_variant_classifies() {
        let reqwest = reqwest_errors();
        let json = serde_json::from_str::<String>("not json").unwrap_err();
        let url = url::Url::parse("://bad").unwrap_err();
        let unavailable = Class::Unavailable { code: None };
        let refusal = Class::VenueRefusal { code: None };
        let secs = |n| Some(Duration::from_secs(n));

        // (error, class, is_fault, retry_after()). The status decides a
        // response's class, as it did for the variants it replaced.
        let rows = [
            (api(200), Class::Decode, true, None),
            (api(302), Class::Decode, true, None),
            (api(400), refusal.clone(), true, None),
            (api(401), Class::Unauthorized, true, None),
            (api(403), Class::Unauthorized, true, None),
            (api(404), refusal.clone(), true, None),
            (api(408), unavailable.clone(), true, None),
            (api(418), Class::Restricted, true, None),
            (api(425), unavailable.clone(), true, None),
            (
                api(429),
                Class::RateLimited { retry_after: None },
                true,
                None,
            ),
            // A region block is the venue answering as designed.
            (api(451), Class::Restricted, false, None),
            (api(500), unavailable.clone(), true, None),
            (api(503), unavailable.clone(), true, None),
            (api(600), Class::Decode, true, None),
            // Was `Authentication`, built from a 401 or 403.
            (
                response(403, r#"{"error":"no"}"#, None).into(),
                Class::Unauthorized,
                true,
                None,
            ),
            // Was `Validation`, for a server 400 or a local refusal. A local
            // refusal is now `InvalidRequest`, and a server 400 the status's.
            (
                ApiError::Validation("bad".into()),
                Class::InvalidRequest,
                true,
                None,
            ),
            (
                response(400, r#"{"error":"bad"}"#, None).into(),
                refusal.clone(),
                true,
                None,
            ),
            // Was `RateLimit`, which kept no Retry-After. A zero is no wait.
            (
                response(429, "slow", Some("7")).into(),
                Class::RateLimited {
                    retry_after: secs(7),
                },
                true,
                secs(7),
            ),
            (
                response(429, "slow", Some("0")).into(),
                Class::RateLimited { retry_after: None },
                true,
                None,
            ),
            // Any status reports its wait, though only a 429's class has one.
            (
                response(503, "down", Some("5")).into(),
                unavailable.clone(),
                true,
                secs(5),
            ),
            // Was `Timeout`, built only from a 408.
            (
                response(408, "slow", None).into(),
                unavailable.clone(),
                true,
                None,
            ),
            (
                transport(TransportKind::Request, reqwest.builder),
                Class::InvalidRequest,
                true,
                None,
            ),
            // A body that broke off is a failure in transit, so `Network`, though reqwest
            // labels it a decode error.
            (
                transport(TransportKind::Body, reqwest.cut_off),
                Class::Network,
                true,
                None,
            ),
            (
                transport(TransportKind::Connect, reqwest.connect),
                Class::Network,
                true,
                None,
            ),
            (
                transport(TransportKind::Timeout, reqwest.timeout),
                Class::Network,
                true,
                None,
            ),
            (
                transport(TransportKind::Other, "no answer"),
                Class::Network,
                true,
                None,
            ),
            (ApiError::Serialization(json), Class::Decode, true, None),
            (ApiError::Url(url), Class::InvalidRequest, true, None),
            (
                ApiError::Refused(Refused {
                    layer: crate::LayerId("order"),
                    units: 2_000,
                    capacity: 120,
                }),
                Class::InvalidRequest,
                true,
                None,
            ),
            (
                ApiError::Sign("no key to sign with".into()),
                Class::InvalidRequest,
                true,
                None,
            ),
        ];
        for (err, class, fault, wait) in rows {
            assert_eq!(err.class(), class, "{err:?}");
            assert_eq!(err.is_fault(), fault, "{err:?}");
            assert_eq!(Classify::retry_after(&err), wait, "{err:?}");
            assert_eq!(
                Classify::is_retriable(&err),
                class.is_retriable(),
                "{err:?}"
            );
        }
    }
}