cexy 0.1.0-dev.16

Official Rust SDK for the CEXY.io exchange API (REST + WebSocket)
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! Errors: API error responses, local checks, connection failures and WebSocket errors.

use std::collections::BTreeMap;
use std::fmt;
use std::time::Duration;

use reqwest::header::HeaderMap;
use serde_json::Value;

use crate::cancel_all::CancelAllSummary;
use crate::models_gen::ErrorCode;

/// `Result` with this crate's [`Error`].
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Every error the SDK returns.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// An error response from the API (the `{"error": {...}}` envelope), or a 3xx the SDK
    /// refused to follow (code `UNEXPECTED_REDIRECT`).
    #[error("{0}")]
    Api(Box<ApiError>),

    /// An invalid client configuration or call, detected before anything is sent.
    #[error("cexy: {0}")]
    Config(String),

    /// A malformed decimal string in an amount field, detected before sending.
    #[error("cexy: {message}")]
    InvalidAmount {
        /// The field name (empty for [`crate::Amount::new`]).
        field: String,
        /// What is wrong.
        message: String,
    },

    /// The request produced no HTTP response (DNS, TLS, connection reset, or the per-attempt
    /// timeout). Always retryable.
    #[error("{0}")]
    Connection(ConnectionError),

    /// `place_order` failed ambiguously and the lookup by `client_order_id` failed too, or the
    /// server accepted the order but its response could not be decoded (`source` is then a
    /// [`Error::Decode`]). Either way the order may exist: check `order_by_client_id` before
    /// placing it again.
    #[error(
        "cexy: order state unknown for client_order_id {client_order_id}; check order_by_client_id before retrying: {source}"
    )]
    OrderStateUnknown {
        /// The `client_order_id` that was sent.
        client_order_id: String,
        /// The failure of the order request.
        source: Box<Error>,
    },

    /// [`crate::Trading::place_orders`] failed after building its request: the request may have
    /// been sent, so some orders may be live. `client_order_ids` are every id of the request,
    /// generated ones included, in request order: look each one up with
    /// [`crate::Trading::order_by_client_id`], or send the same orders again WITH these ids (the
    /// server refuses an id it already placed as `ALREADY_EXISTS`), before placing anything anew.
    /// `maybe_placed` is false only when every attempt was a definite refusal (a 429, 501, 503 or
    /// another 4xx), so nothing was placed. [`Error::api`] and [`Error::code`] read `source`.
    #[error(
        "cexy: place_orders failed (maybe_placed: {maybe_placed}, {} client_order_ids): {source}",
        .client_order_ids.len()
    )]
    BatchPlace {
        /// Every `client_order_id` sent, in request order.
        client_order_ids: Vec<String>,
        /// Whether any order may have been placed.
        maybe_placed: bool,
        /// The failure: an API error, a connection error or timeout, or a [`Error::Decode`] for an
        /// unusable 200.
        source: Box<Error>,
    },

    /// `cancel_all_until_done` stopped on an error; `summary` holds what the earlier rounds did.
    #[error("cexy: cancel-all interrupted after {} round(s): {source}", .summary.rounds)]
    CancelAllInterrupted {
        /// The error that stopped the loop.
        source: Box<Error>,
        /// The merged result of the rounds before the error.
        summary: Box<CancelAllSummary>,
    },

    /// A WebSocket protocol error, a server error frame, or a local guard.
    #[error("{0}")]
    WebSocket(WsError),

    /// A response that could not be decoded.
    #[error("cexy: {0}")]
    Decode(String),

    /// An iterate-all helper ([`crate::Futures::all_fills`], [`crate::Futures::all_funding`])
    /// kept getting a busy answer for the same cursor, an empty page whose `next_cursor` was the
    /// cursor it had sent or a 503 with `details.reason` `futures_data_unavailable`: the server's
    /// data source is busy. It waited and asked again `retries` times (see
    /// [`crate::Futures::with_max_busy_retries`]), then gave up. Code [`PAGING_STALLED`], a local
    /// error (never sent by the server). Retryable: page again later from `cursor`. The rows
    /// yielded before it are NOT the complete history.
    #[error(
        "cexy: [{PAGING_STALLED}] {operation}: still no rows after {retries} retries of the same cursor; page again later"
    )]
    PagingStalled {
        /// The listing operation, such as `"fills"`.
        operation: &'static str,
        /// The cursor that stalled, exactly as the server gave it (opaque).
        cursor: String,
        /// How many times the same cursor was asked again.
        retries: u32,
        /// The last busy answer, when it was a 503 `futures_data_unavailable` (an [`ApiError`]),
        /// so its `details["reason"]` stays reachable (`std::error::Error::source`, then
        /// `downcast_ref::<ApiError>()`); `None` for an empty same-cursor page.
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// An iterate-all helper got a page WITH rows whose `next_cursor` was the cursor it had just
    /// sent: following it would repeat that page forever. The rows of that page were yielded, then
    /// this. Code [`PAGING_CURSOR_REPEATED`], a local error; not retryable. The rows yielded
    /// before it are NOT the complete history.
    #[error(
        "cexy: [{PAGING_CURSOR_REPEATED}] {operation}: the server repeated a cursor after a page of rows; paging stopped"
    )]
    PagingCursorRepeated {
        /// The listing operation, such as `"fills"`.
        operation: &'static str,
        /// The repeated cursor, exactly as the server gave it (opaque).
        cursor: String,
    },
}

/// The code of [`Error::PagingStalled`].
pub const PAGING_STALLED: &str = "PAGING_STALLED";

/// The code of [`Error::PagingCursorRepeated`].
pub const PAGING_CURSOR_REPEATED: &str = "PAGING_CURSOR_REPEATED";

impl Error {
    /// The API error, if this is one (for [`Error::BatchPlace`], its source's).
    pub fn api(&self) -> Option<&ApiError> {
        match self {
            Error::Api(e) => Some(e),
            Error::BatchPlace { source, .. } => source.api(),
            _ => None,
        }
    }

    /// Whether this is an API error of `category` (see [`ApiError::is`]).
    pub fn is(&self, category: ErrorCategory) -> bool {
        self.api().is_some_and(|e| e.is(category))
    }

    /// The machine-readable code: the API error's code, a WebSocket error's code, or
    /// [`PAGING_STALLED`] / [`PAGING_CURSOR_REPEATED`]. `None` for the other local errors.
    pub fn code(&self) -> Option<&str> {
        match self {
            Error::Api(e) => Some(e.code.as_str()),
            Error::BatchPlace { source, .. } => source.code(),
            Error::WebSocket(e) => Some(&e.code),
            Error::PagingStalled { .. } => Some(PAGING_STALLED),
            Error::PagingCursorRepeated { .. } => Some(PAGING_CURSOR_REPEATED),
            _ => None,
        }
    }

    /// Whether an identical retry could succeed: a connection failure, [`Error::PagingStalled`],
    /// or an API error marked retryable (including 409 `CONCURRENT_MODIFICATION`). A 4xx is never retryable except 429
    /// and 409 `CONCURRENT_MODIFICATION`, whatever its body says.
    ///
    /// An error whose server wait (Retry-After) exceeds [`MAX_SERVER_WAIT`] is not retryable:
    /// the SDK fails fast instead of waiting that long. `retry_after` still carries the value.
    pub fn is_retryable(&self) -> bool {
        match self {
            Error::Connection(_) | Error::PagingStalled { .. } => true,
            Error::Api(e) => {
                e.retryable_ignoring_wait() && e.retry_after.is_none_or(|d| d <= MAX_SERVER_WAIT)
            }
            _ => false,
        }
    }

    /// The server asked for a wait longer than [`MAX_SERVER_WAIT`].
    pub(crate) fn server_wait_too_long(&self) -> bool {
        self.api()
            .and_then(|e| e.retry_after)
            .is_some_and(|d| d > MAX_SERVER_WAIT)
    }

    /// A failure after which it is unknown whether a mutation took effect.
    pub(crate) fn is_ambiguous(&self) -> bool {
        match self {
            Error::Connection(_) => true,
            Error::Api(e) => e.status >= 500,
            _ => false,
        }
    }

    pub(crate) fn config(msg: impl Into<String>) -> Error {
        Error::Config(msg.into())
    }
}

impl From<ApiError> for Error {
    fn from(e: ApiError) -> Error {
        Error::Api(Box::new(e))
    }
}

impl From<WsError> for Error {
    fn from(e: WsError) -> Error {
        Error::WebSocket(e)
    }
}

/// The category of an API error. An error matches at most one, except that
/// `JurisdictionBlocked` also matches `Forbidden`. An error with a code this SDK does not know
/// matches none: check [`ApiError::code`] instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorCategory {
    /// 400.
    Validation,
    /// 401: missing or invalid credentials.
    Authentication,
    /// 403: the key lacks a scope, or the route is session-only (and 451).
    Forbidden,
    /// 451 `JURISDICTION_BLOCKED`: not available in the caller's jurisdiction.
    JurisdictionBlocked,
    /// 404.
    NotFound,
    /// 409.
    Conflict,
    /// 422: refused by a business rule.
    Unprocessable,
    /// 429.
    RateLimited,
    /// 5xx.
    Server,
    /// 3xx: the SDK never follows redirects.
    UnexpectedRedirect,
}

/// An error response from the API.
#[derive(Clone)]
pub struct ApiError {
    /// HTTP status.
    pub status: u16,
    /// Machine-readable code. Branch on it, never on the message. A code missing from
    /// `errors.yaml` arrives as `ErrorCode::Other`; a response without the envelope (a proxy
    /// error page) gets `HTTP_<status>`.
    pub code: ErrorCode,
    /// Human-readable; may change between releases. Credentials are redacted from it.
    pub message: String,
    /// Structured context. String values have credentials redacted.
    pub details: BTreeMap<String, Value>,
    /// Per-field validation messages (400), with credentials redacted.
    pub fields: BTreeMap<String, String>,
    /// Quote it in support requests.
    pub request_id: Option<String>,
    /// Whether an identical retry could succeed.
    pub retryable: bool,
    /// How long the server asked to wait (Retry-After or `details.retry_after_seconds`).
    pub retry_after: Option<Duration>,
    /// The Retry-After header alone (`retry_after` also takes `details.retry_after_seconds`).
    header_wait: Option<Duration>,
    category: Option<ErrorCategory>,
}

impl ApiError {
    /// Marked retryable (or 409 `CONCURRENT_MODIFICATION`), and not a 4xx other than 429 and
    /// 409 `CONCURRENT_MODIFICATION`; the server's wait is not considered.
    pub(crate) fn retryable_ignoring_wait(&self) -> bool {
        let concurrent = self.code == ErrorCode::ConcurrentModification;
        if (400..500).contains(&self.status)
            && self.status != 429
            && !(self.status == 409 && concurrent)
        {
            return false;
        }
        self.retryable || concurrent
    }

    /// A 503 whose `details.reason` is `futures_data_unavailable`: the futures provider is busy.
    pub(crate) fn is_futures_busy(&self) -> bool {
        self.status == 503
            && self.details.get("reason").and_then(Value::as_str)
                == Some("futures_data_unavailable")
    }

    /// The wait the server hinted, for the futures history helpers: the Retry-After header, else
    /// `details.retry_after_seconds`. A missing, unparseable or non-positive hint is skipped.
    pub(crate) fn busy_hint(&self) -> Option<Duration> {
        self.header_wait
            .or_else(|| details_wait(&self.details).and_then(server_secs))
    }

    /// The category, or `None` for a code this SDK does not know.
    pub fn category(&self) -> Option<ErrorCategory> {
        self.category
    }

    /// Whether the error belongs to `category`. `JurisdictionBlocked` also matches `Forbidden`.
    pub fn is(&self, category: ErrorCategory) -> bool {
        match self.category {
            Some(c) if c == category => true,
            Some(ErrorCategory::JurisdictionBlocked) => category == ErrorCategory::Forbidden,
            _ => false,
        }
    }
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "cexy: [{} {}] {}", self.status, self.code, self.message)?;
        if let Some(rid) = &self.request_id {
            write!(f, " (request_id {rid})")?;
        }
        Ok(())
    }
}

impl std::error::Error for ApiError {}

impl fmt::Debug for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ApiError")
            .field("status", &self.status)
            .field("code", &self.code)
            .field("message", &self.message)
            .field("details", &self.details)
            .field("fields", &self.fields)
            .field("request_id", &self.request_id)
            .field("retryable", &self.retryable)
            .field("retry_after", &self.retry_after)
            .finish()
    }
}

/// The `error` object of one item in a batch result ([`crate::BatchOrderResult`],
/// [`crate::CancelBatchResult`]), as the server sent it. A whole response's error is an
/// [`ApiError`] instead.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ErrorBody {
    /// Machine-readable code. Branch on it, never on the message.
    pub code: ErrorCode,
    /// Human-readable; may change between releases.
    pub message: String,
    /// Whether an identical retry could succeed.
    #[serde(default)]
    pub retryable: bool,
    /// Structured context: for `ALREADY_EXISTS`, the `order_id` and `status` of the order that
    /// took the `client_order_id`.
    #[serde(default)]
    pub details: BTreeMap<String, Value>,
    /// Per-field validation messages.
    #[serde(default)]
    pub fields: BTreeMap<String, String>,
    /// Quote it in support requests.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
}

impl ErrorBody {
    /// A string in `details`, if present and not empty.
    pub fn detail_str(&self, name: &str) -> Option<&str> {
        self.details
            .get(name)
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty())
    }
}

/// The request produced no HTTP response.
#[derive(Debug, Clone)]
pub struct ConnectionError {
    /// HTTP method.
    pub method: String,
    /// Path template of the operation.
    pub path: String,
    /// True when the per-attempt timeout expired.
    pub timeout: bool,
    /// What happened (credentials redacted).
    pub message: String,
}

impl fmt::Display for ConnectionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.timeout {
            write!(f, "cexy: {} {} timed out", self.method, self.path)
        } else {
            write!(
                f,
                "cexy: {} {} failed: {}",
                self.method, self.path, self.message
            )
        }
    }
}

/// A WebSocket protocol error, a server error frame (`from_server`), or a local guard.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct WsError {
    /// Such as `NOT_CONNECTED`, `TIMEOUT`, `LOCAL_RATE_LIMIT`, or the server's code.
    pub code: String,
    /// What happened.
    pub message: String,
    /// True when it came from a server error frame.
    pub from_server: bool,
    /// The channel a server error frame names (such as a refused subscribe); `None` when the
    /// frame has none and for local errors.
    pub channel: Option<String>,
    /// The frame's `details` object; empty when absent, not an object, and for local errors.
    pub details: BTreeMap<String, Value>,
    /// The wait the frame asked for (`details.retry_after_seconds`); `None` when absent, not a
    /// positive number, and for local errors. The SDK does not retry on it: it is for the caller.
    pub retry_after: Option<Duration>,
}

impl WsError {
    pub(crate) fn local(code: &str, message: impl Into<String>) -> WsError {
        WsError {
            code: code.to_string(),
            message: message.into(),
            from_server: false,
            channel: None,
            details: BTreeMap::new(),
            retry_after: None,
        }
    }

    /// A server error frame: `channel` and `details` are optional and never an error to decode.
    pub(crate) fn from_frame(
        code: &str,
        message: &str,
        frame: &serde_json::Map<String, Value>,
    ) -> WsError {
        let details: BTreeMap<String, Value> = frame
            .get("details")
            .and_then(Value::as_object)
            .map(|o| o.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
            .unwrap_or_default();
        WsError {
            code: code.to_string(),
            message: message.to_string(),
            from_server: true,
            channel: frame
                .get("channel")
                .and_then(Value::as_str)
                .map(str::to_string),
            retry_after: details
                .get("retry_after_seconds")
                .and_then(Value::as_f64)
                .and_then(server_secs),
            details,
        }
    }
}

impl fmt::Display for WsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "cexy websocket: [{}] {}", self.code, self.message)
    }
}

impl std::error::Error for WsError {}

fn default_retryable(status: u16) -> bool {
    matches!(status, 429 | 500 | 502 | 503 | 504)
}

/// Builds the API error for an error response. A known code maps by HTTP status; an unknown
/// code keeps no category (never a crash); a body without the envelope maps by status with the
/// code `HTTP_<status>`.
pub(crate) fn error_from_response(
    status: u16,
    body: &[u8],
    headers: &HeaderMap,
    redact: &dyn Fn(&str) -> String,
) -> ApiError {
    let header_rid = header(headers, "x-request-id");
    let mut e = ApiError {
        status,
        code: ErrorCode::Other(format!("HTTP_{status}")),
        message: format!("HTTP {status}"),
        details: BTreeMap::new(),
        fields: BTreeMap::new(),
        request_id: header_rid,
        retryable: default_retryable(status),
        retry_after: None,
        header_wait: None,
        category: None,
    };
    let env: Option<Value> = serde_json::from_slice(body).ok();
    let err_obj = env
        .as_ref()
        .and_then(|v| v.get("error"))
        .and_then(Value::as_object);
    let code = err_obj.and_then(|o| o.get("code")).and_then(Value::as_str);
    let has_envelope = code.is_some();
    if let (Some(o), Some(code)) = (err_obj, code) {
        e.code = ErrorCode::from(code);
        e.message = o
            .get("message")
            .and_then(Value::as_str)
            .unwrap_or(code)
            .to_string();
        if let Some(d) = o.get("details").and_then(Value::as_object) {
            // The server may echo request values back, at any depth and even as keys: keep
            // credentials out of all of them.
            for (k, v) in d {
                e.details.insert(redact(k), redact_json(v, redact));
            }
        }
        if let Some(fl) = o.get("fields").and_then(Value::as_object) {
            for (k, v) in fl {
                if let Some(s) = v.as_str() {
                    e.fields.insert(redact(k), redact(s));
                }
            }
        }
        if let Some(rid) = o
            .get("request_id")
            .and_then(Value::as_str)
            .filter(|s| !s.is_empty())
        {
            e.request_id = Some(redact(rid));
        }
        if let Some(r) = o.get("retryable").and_then(Value::as_bool) {
            e.retryable = r;
        }
    }
    e.message = redact(&e.message);
    e.header_wait = header_wait(headers);
    e.retry_after = retry_after(headers, &e.details);
    e.category = if status == 429 || e.code == ErrorCode::RateLimited {
        Some(ErrorCategory::RateLimited)
    } else if e.code == ErrorCode::JurisdictionBlocked {
        Some(ErrorCategory::JurisdictionBlocked)
    } else if has_envelope && !e.code.is_known() {
        None
    } else if status >= 500 {
        Some(ErrorCategory::Server)
    } else {
        match status {
            400 => Some(ErrorCategory::Validation),
            401 => Some(ErrorCategory::Authentication),
            403 => Some(ErrorCategory::Forbidden),
            404 => Some(ErrorCategory::NotFound),
            409 => Some(ErrorCategory::Conflict),
            422 => Some(ErrorCategory::Unprocessable),
            451 => Some(ErrorCategory::JurisdictionBlocked),
            _ => None,
        }
    };
    e
}

/// The API error for a 3xx response. `details["location"]` holds the Location header, if any.
pub(crate) fn redirect_error(
    status: u16,
    headers: &HeaderMap,
    redact: &dyn Fn(&str) -> String,
) -> ApiError {
    let loc = header(headers, "location").map(|l| redact(&l));
    let mut message =
        format!("unexpected redirect (HTTP {status}); the SDK does not follow redirects");
    let mut details = BTreeMap::new();
    if let Some(l) = &loc {
        message.push_str(&format!(" (Location: {l})"));
        details.insert("location".to_string(), Value::String(l.clone()));
    }
    ApiError {
        status,
        code: ErrorCode::UnexpectedRedirect,
        message,
        details,
        fields: BTreeMap::new(),
        request_id: header(headers, "x-request-id"),
        retryable: false,
        retry_after: None,
        header_wait: None,
        category: Some(ErrorCategory::UnexpectedRedirect),
    }
}

/// `v` with credentials redacted from every string and object key, at any depth.
fn redact_json(v: &Value, redact: &dyn Fn(&str) -> String) -> Value {
    match v {
        Value::String(s) => Value::String(redact(s)),
        Value::Array(a) => Value::Array(a.iter().map(|x| redact_json(x, redact)).collect()),
        Value::Object(o) => Value::Object(
            o.iter()
                .map(|(k, x)| (redact(k), redact_json(x, redact)))
                .collect(),
        ),
        other => other.clone(),
    }
}

pub(crate) fn header(headers: &HeaderMap, name: &str) -> Option<String> {
    headers
        .get(name)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// The longest wait the SDK accepts from a server hint (Retry-After,
/// `details.retry_after_seconds`, `X-RateLimit-Reset`). A longer hint is not waited: the call
/// fails with the error, and the client-side limiter never blocks longer than this.
pub const MAX_SERVER_WAIT: Duration = Duration::from_secs(120);

/// A server-supplied number of seconds as a wait. Unparseable, non-finite, zero or negative
/// values are ignored (`None`); values too large for a `Duration` saturate to `Duration::MAX`
/// (never a panic).
pub(crate) fn server_secs(secs: f64) -> Option<Duration> {
    if !secs.is_finite() || secs <= 0.0 {
        return None;
    }
    Some(Duration::try_from_secs_f64(secs).unwrap_or(Duration::MAX))
}

/// Reads Retry-After (seconds or an HTTP date) and `details.retry_after_seconds`; the larger wins.
/// Both are untrusted: garbage is ignored and nothing here can panic.
fn retry_after(headers: &HeaderMap, details: &BTreeMap<String, Value>) -> Option<Duration> {
    let mut best = header_wait(headers);
    if let Some(d) = details_wait(details).and_then(server_secs)
        && best.is_none_or(|b| d > b)
    {
        best = Some(d);
    }
    best
}

/// The Retry-After header as a wait (seconds or an HTTP date); garbage gives `None`.
fn header_wait(headers: &HeaderMap) -> Option<Duration> {
    let v = header(headers, "retry-after")?;
    if let Ok(secs) = v.parse::<f64>() {
        return server_secs(secs);
    }
    let at = chrono::DateTime::parse_from_rfc2822(&v).ok()?;
    let d = (at.with_timezone(&chrono::Utc) - chrono::Utc::now())
        .to_std()
        .ok()?;
    (!d.is_zero()).then_some(d)
}

/// `details.retry_after_seconds` as a number of seconds, if it is one.
fn details_wait(details: &BTreeMap<String, Value>) -> Option<f64> {
    match details.get("retry_after_seconds") {
        Some(Value::Number(n)) => n.as_f64(),
        Some(Value::String(s)) => s.parse::<f64>().ok(),
        _ => None,
    }
}