calmlens 0.38.2

Rust SDK for CalmLens moderation, storage and CDN delivery
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
//! Request execution: transports, retries, timeouts, size limits and error mapping.
use crate::error::{invalid_argument, ErrorCode};
use crate::models::Payload;
use crate::{Error, Result};
use bytes::Bytes;
use futures_util::TryStreamExt;
use http::{HeaderMap, HeaderName, HeaderValue, Method};
use serde_json::{Map, Value};
use std::time::Duration;

/// The default size limit for API responses: larger ones fail with `sdk/response-too-large`.
/// Change it with [`ServerClientBuilder::max_response_bytes`](crate::ServerClientBuilder::max_response_bytes).
pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 32 * 1024 * 1024;
/// The longest `Retry-After` delay the SDK waits for; a longer one returns the error (or, for
/// `cdn().serve`, the response) to the caller instead.
pub const RETRY_AFTER_MAX: Duration = Duration::from_secs(60);
/// The backoff before retry `n` (from 0) is `min(RETRY_MAX_DELAY, RETRY_BASE_DELAY * 2^n)`, of
/// which the client waits half plus a random share of the other half.
pub const RETRY_BASE_DELAY: Duration = Duration::from_millis(500);
/// The longest backoff between attempts.
pub const RETRY_MAX_DELAY: Duration = Duration::from_secs(8);

pub(crate) enum RequestBody {
    Empty,
    Bytes(Bytes),
    /// Read once; requests with a stream body are never retried. The size is sent as
    /// `Content-Length` when known.
    Stream(Option<crate::ByteStream>, Option<u64>),
}

/// Which deadline a request has.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Deadline {
    /// API calls: the client timeout covers the whole exchange, body included.
    Api,
    /// Binary uploads: the upload timeout (none by default) covers the whole exchange.
    Upload,
    /// CDN downloads: the client timeout ends when the response headers arrive, so the body
    /// can stream for as long as it takes.
    Headers,
}

pub(crate) struct Prepared {
    /// The operation, such as `assets.retrieve`, for the attempt hook and logs; `None` for a raw
    /// request.
    pub operation: Option<&'static str>,
    pub method: Method,
    pub url: reqwest::Url,
    pub headers: HeaderMap,
    pub body: RequestBody,
    pub deadline: Deadline,
}

impl Prepared {
    pub fn new(method: Method, url: reqwest::Url) -> Self {
        Self {
            operation: None,
            method,
            url,
            headers: HeaderMap::new(),
            body: RequestBody::Empty,
            deadline: Deadline::Api,
        }
    }
    pub fn header(mut self, name: &'static str, value: &str) -> Result<Self> {
        let value = HeaderValue::from_str(value)
            .map_err(|_| invalid_argument(format!("Invalid {name} header value")))?;
        self.headers.insert(HeaderName::from_static(name), value);
        Ok(self)
    }
    pub fn json(mut self, body: &impl serde::Serialize) -> Result<Self> {
        let bytes = serde_json::to_vec(body)
            .map_err(|cause| invalid_argument(cause.to_string()).with_source(cause))?;
        self.headers.insert(
            http::header::CONTENT_TYPE,
            HeaderValue::from_static("application/json"),
        );
        self.body = RequestBody::Bytes(bytes.into());
        Ok(self)
    }
    /// Sets top-level properties of the JSON object body, or makes one from them when there is
    /// no body. A body that isn't a JSON object (an upload form) refuses them.
    pub fn merge_json(self, fields: &Map<String, Value>) -> Result<Self> {
        let mut object = match &self.body {
            RequestBody::Empty => Map::new(),
            RequestBody::Bytes(bytes) => match serde_json::from_slice::<Value>(bytes) {
                Ok(Value::Object(object)) => object,
                _ => {
                    return Err(invalid_argument(
                        "extra_body needs a JSON object request body",
                    ))
                }
            },
            RequestBody::Stream(..) => {
                return Err(invalid_argument(
                    "extra_body needs a JSON object request body",
                ))
            }
        };
        for (key, value) in fields {
            object.insert(key.clone(), value.clone());
        }
        self.json(&Value::Object(object))
    }
    /// GET and HEAD, and writes carrying an `Idempotency-Key`, can be repeated safely.
    fn retryable(&self) -> bool {
        !matches!(self.body, RequestBody::Stream(..))
            && (matches!(self.method, Method::GET | Method::HEAD)
                || self.headers.contains_key("idempotency-key"))
    }
    fn attempt(&mut self) -> Attempt {
        Attempt {
            method: self.method.clone(),
            url: self.url.clone(),
            headers: self.headers.clone(),
            body: match &mut self.body {
                RequestBody::Empty => AttemptBody::Empty,
                RequestBody::Bytes(bytes) => AttemptBody::Bytes(bytes.clone()),
                RequestBody::Stream(stream, size) => match stream.take() {
                    Some(stream) => AttemptBody::Stream(stream, *size),
                    None => AttemptBody::Empty,
                },
            },
        }
    }
}

/// One attempt at a request, as handed to a transport.
pub(crate) struct Attempt {
    pub method: Method,
    pub url: reqwest::Url,
    pub headers: HeaderMap,
    pub body: AttemptBody,
}
pub(crate) enum AttemptBody {
    Empty,
    Bytes(Bytes),
    Stream(crate::ByteStream, Option<u64>),
}

pub(crate) enum ResponseBody {
    Http(reqwest::Response),
    #[cfg(feature = "testing")]
    Mock(Bytes),
}
pub(crate) struct Exchange {
    pub status: u16,
    pub headers: HeaderMap,
    pub body: ResponseBody,
}
impl Exchange {
    /// Reads the whole body, failing with `sdk/response-too-large` as soon as it (or the
    /// declared `Content-Length`) exceeds `limit` bytes.
    pub async fn read(self, limit: usize) -> Result<Bytes> {
        let declared = self
            .headers
            .get(http::header::CONTENT_LENGTH)
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.trim().parse::<u64>().ok());
        if declared.is_some_and(|length| length > limit as u64) {
            return Err(too_large(limit, self.status, &self.headers));
        }
        match self.body {
            #[cfg(feature = "testing")]
            ResponseBody::Mock(bytes) if bytes.len() > limit => {
                Err(too_large(limit, self.status, &self.headers))
            }
            #[cfg(feature = "testing")]
            ResponseBody::Mock(bytes) => Ok(bytes),
            ResponseBody::Http(mut response) => {
                let mut body = Vec::new();
                while let Some(chunk) = response.chunk().await.map_err(transport_error)? {
                    if body.len() + chunk.len() > limit {
                        return Err(too_large(limit, self.status, &self.headers));
                    }
                    body.extend_from_slice(&chunk);
                }
                Ok(body.into())
            }
        }
    }
    /// The body as a stream, for CDN responses.
    pub fn stream(self) -> crate::ByteStream {
        match self.body {
            #[cfg(feature = "testing")]
            ResponseBody::Mock(bytes) => Box::pin(futures_util::stream::once(async move {
                Ok::<_, Box<dyn std::error::Error + Send + Sync>>(bytes)
            })),
            ResponseBody::Http(response) => Box::pin(
                response
                    .bytes_stream()
                    .map_err(|error| Box::new(error) as _),
            ),
        }
    }
}
fn too_large(limit: usize, status: u16, headers: &HeaderMap) -> Error {
    with_response(
        Error::new(
            ErrorCode::ResponseTooLarge,
            format!("Response body exceeds {limit} bytes"),
        ),
        status,
        headers,
    )
}

pub(crate) enum Transport {
    Http(reqwest::Client),
    #[cfg(feature = "testing")]
    Mock(std::sync::Arc<crate::testing::MockTransport>),
}

impl Transport {
    /// Whether the client leaves multipart size checks to the API: only the in-memory mock's
    /// does, so its API answers them in the API's order.
    pub(crate) fn defers_upload_checks(&self) -> bool {
        match self {
            #[cfg(feature = "testing")]
            Transport::Mock(mock) => mock.defers_upload_checks(),
            Transport::Http(_) => false,
        }
    }
    /// The clock waits are measured with: the mock's virtual clock, or Tokio's.
    pub(crate) fn now(&self) -> tokio::time::Instant {
        match self {
            #[cfg(feature = "testing")]
            Transport::Mock(mock) => mock.now(),
            Transport::Http(_) => tokio::time::Instant::now(),
        }
    }
    /// Waits for `duration`; the mock only advances its virtual clock.
    pub(crate) async fn sleep(&self, duration: Duration) {
        match self {
            #[cfg(feature = "testing")]
            Transport::Mock(mock) => mock.sleep(duration).await,
            Transport::Http(_) => tokio::time::sleep(duration).await,
        }
    }
    async fn exchange(
        &self,
        attempt: Attempt,
        timeout: Option<Duration>,
        deadline: Deadline,
    ) -> Result<Exchange> {
        match self {
            #[cfg(feature = "testing")]
            Transport::Mock(mock) => mock.exchange(attempt, timeout).await,
            Transport::Http(client) => {
                let mut request = client
                    .request(attempt.method, attempt.url)
                    .headers(attempt.headers);
                request = match attempt.body {
                    AttemptBody::Empty => request,
                    AttemptBody::Bytes(bytes) => request.body(bytes),
                    AttemptBody::Stream(stream, Some(size)) => request
                        .header(http::header::CONTENT_LENGTH, size)
                        .body(reqwest::Body::wrap_stream(stream)),
                    AttemptBody::Stream(stream, None) => {
                        request.body(reqwest::Body::wrap_stream(stream))
                    }
                };
                let response = match (timeout, deadline) {
                    (Some(timeout), Deadline::Headers) => {
                        tokio::time::timeout(timeout, request.send())
                            .await
                            .map_err(|_| {
                                Error::new(
                                    ErrorCode::Timeout,
                                    format!("No response headers within {timeout:?}"),
                                )
                            })?
                    }
                    (Some(timeout), _) => request.timeout(timeout).send().await,
                    (None, _) => request.send().await,
                }
                .map_err(transport_error)?;
                Ok(Exchange {
                    status: response.status().as_u16(),
                    headers: response.headers().clone(),
                    body: ResponseBody::Http(response),
                })
            }
        }
    }
}

/// Retry, timeout and size settings for one call.
#[derive(Clone, Copy, Debug)]
pub(crate) struct CallOptions {
    pub timeout: Duration,
    pub upload_timeout: Option<Duration>,
    pub timeout_override: Option<Duration>,
    pub max_retries: u32,
    pub max_response_bytes: usize,
    /// When the call's [`RequestOptions::deadline`](crate::RequestOptions::deadline) passes: no
    /// attempt starts after it, an attempt's timeout ends at it and no retry waits up to it.
    pub deadline_at: Option<tokio::time::Instant>,
}

const RETRYABLE_STATUSES: [u16; 5] = [429, 500, 502, 503, 504];

/// Sends `request`, retrying transport failures, timeouts, `429`, `500`, `502`, `503`, `504` and
/// `idempotency/request-in-progress` with jittered backoff (or the `Retry-After` the server
/// sent) when the request is repeatable. A redirect is never followed: it fails with
/// `sdk/http-error`. With `api_errors`, an unsuccessful status is returned as an [`Error`];
/// without it (CDN requests) the final response is returned whatever its status.
pub(crate) async fn execute(
    transport: &Transport,
    mut request: Prepared,
    options: CallOptions,
    api_errors: bool,
    observer: &crate::observe::Observer,
) -> Result<Exchange> {
    let max_retries = if request.retryable() {
        options.max_retries
    } else {
        0
    };
    let timeout = options.timeout_override.or(match request.deadline {
        Deadline::Api | Deadline::Headers => Some(options.timeout),
        Deadline::Upload => options.upload_timeout,
    });
    let mut retry = 0;
    let path = crate::observe::redacted_path(request.url.path());
    // Whether a retry after `delay` would still start before the call's deadline.
    let starts_in_time = |delay: Duration| {
        options
            .deadline_at
            .is_none_or(|deadline_at| transport.now() + delay < deadline_at)
    };
    loop {
        let can_retry = retry < max_retries;
        // The attempt's timeout ends at the call's deadline, if that comes first.
        let remaining = options
            .deadline_at
            .map(|deadline_at| deadline_at.saturating_duration_since(transport.now()));
        let timeout = match remaining {
            Some(Duration::ZERO) => {
                return Err(Error::new(ErrorCode::Timeout, "The call's deadline passed"))
            }
            Some(remaining) => Some(timeout.map_or(remaining, |timeout| timeout.min(remaining))),
            None => timeout,
        };
        let started = transport.now();
        let result = transport
            .exchange(request.attempt(), timeout, request.deadline)
            .await;
        let duration = transport.now().saturating_duration_since(started);
        let (status, request_id) = match &result {
            Ok(exchange) => (
                http::StatusCode::from_u16(exchange.status).ok(),
                exchange
                    .headers
                    .get("x-request-id")
                    .and_then(|value| value.to_str().ok())
                    .map(str::to_owned),
            ),
            Err(_) => (None, None),
        };
        let report = |retry_delay: Option<Duration>, error: Option<&Error>| {
            observer.attempt(crate::observe::AttemptEvent {
                operation: request.operation,
                method: request.method.clone(),
                path: path.clone(),
                attempt: retry + 1,
                retry_delay,
                status,
                request_id: request_id.clone(),
                error_code: error.map(|error| error.code().clone()),
                duration,
            });
        };
        let failure = match result {
            Err(error) => error,
            Ok(exchange) if (300..400).contains(&exchange.status) => with_response(
                Error::new(
                    ErrorCode::HttpError,
                    format!("Unexpected redirect (HTTP {})", exchange.status),
                ),
                exchange.status,
                &exchange.headers,
            ),
            Ok(exchange) if (200..300).contains(&exchange.status) => {
                report(None, None);
                return Ok(exchange);
            }
            Ok(exchange) if !api_errors => {
                let delay = retry_after(&exchange.headers).unwrap_or_else(|| backoff(retry));
                if !can_retry
                    || !RETRYABLE_STATUSES.contains(&exchange.status)
                    || delay > RETRY_AFTER_MAX
                    || !starts_in_time(delay)
                {
                    report(None, None);
                    return Ok(exchange);
                }
                report(Some(delay), None);
                transport.sleep(delay).await;
                retry += 1;
                continue;
            }
            Ok(exchange) => {
                let status = exchange.status;
                let headers = exchange.headers.clone();
                match exchange.read(options.max_response_bytes).await {
                    Ok(body) => api_error(status, &headers, &body),
                    Err(error) => error,
                }
            }
        };
        let delay = failure.retry_after().unwrap_or_else(|| backoff(retry));
        if !can_retry
            || delay > RETRY_AFTER_MAX
            || !failure.is_retryable()
            || !starts_in_time(delay)
        {
            report(None, Some(&failure));
            return Err(failure);
        }
        report(Some(delay), Some(&failure));
        transport.sleep(delay).await;
        retry += 1;
    }
}

/// Exponential backoff with jitter: 0.5s, 1s, 2s, ... capped at 8s, of which half is fixed and
/// half random.
fn backoff(retry: u32) -> Duration {
    let delay = RETRY_BASE_DELAY
        .saturating_mul(1 << retry.min(16))
        .min(RETRY_MAX_DELAY)
        .as_millis() as u64;
    let half = delay / 2;
    Duration::from_millis(half + random_u64() % (delay - half + 1))
}

pub(crate) fn random_u64() -> u64 {
    let mut bytes = [0; 8];
    let _ = getrandom::getrandom(&mut bytes);
    u64::from_le_bytes(bytes)
}

/// A new ID like the API's: `prefix`, `_` and 20 base62 characters, drawn without modulo bias
/// (bytes 248 to 255 are redrawn).
#[cfg(feature = "testing")]
pub(crate) fn new_id(prefix: &str) -> String {
    const ALPHABET: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    let mut id = String::with_capacity(prefix.len() + 21);
    id.push_str(prefix);
    id.push('_');
    let mut count = 0;
    while count < 20 {
        let mut bytes = [0u8; 40];
        if getrandom::getrandom(&mut bytes).is_err() {
            bytes.copy_from_slice(
                &[
                    random_u64(),
                    random_u64(),
                    random_u64(),
                    random_u64(),
                    random_u64(),
                ]
                .map(u64::to_le_bytes)
                .concat(),
            );
        }
        for byte in bytes.into_iter().filter(|byte| *byte < 248) {
            if count == 20 {
                break;
            }
            id.push(ALPHABET[usize::from(byte % 62)] as char);
            count += 1;
        }
    }
    id
}

/// A random (version 4) UUID, used as an `Idempotency-Key`.
pub(crate) fn uuid() -> String {
    let mut bytes = [0u8; 16];
    let _ = getrandom::getrandom(&mut bytes);
    if bytes == [0; 16] {
        bytes[..8].copy_from_slice(&random_u64().to_le_bytes());
    }
    bytes[6] = (bytes[6] & 0x0f) | 0x40;
    bytes[8] = (bytes[8] & 0x3f) | 0x80;
    let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
    format!(
        "{}-{}-{}-{}-{}",
        &hex[..8],
        &hex[8..12],
        &hex[12..16],
        &hex[16..20],
        &hex[20..]
    )
}

/// The `Retry-After` delay: whole seconds, or an HTTP date (rounded up to whole seconds from
/// now, and zero once it has passed).
fn retry_after(headers: &HeaderMap) -> Option<Duration> {
    let value = headers
        .get(http::header::RETRY_AFTER)?
        .to_str()
        .ok()?
        .trim();
    if !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit()) {
        return Some(Duration::from_secs(value.parse().unwrap_or(u64::MAX)));
    }
    let date = parse_http_date(value)?;
    let now = std::time::SystemTime::now();
    Some(match date.duration_since(now) {
        Ok(ahead) => Duration::from_secs(ahead.as_secs() + u64::from(ahead.subsec_nanos() > 0)),
        Err(_) => Duration::ZERO,
    })
}

/// Parses an IMF-fixdate such as `Wed, 21 Oct 2015 07:28:00 GMT`, the HTTP date format.
fn parse_http_date(value: &str) -> Option<std::time::SystemTime> {
    let (_, rest) = value.split_once(", ")?;
    let parts: Vec<&str> = rest.split(' ').collect();
    let [day, month, year, time, "GMT"] = parts.as_slice() else {
        return None;
    };
    const MONTHS: [&str; 12] = [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
    ];
    let month = MONTHS.iter().position(|name| name == month)? as i64 + 1;
    let day: i64 = day.parse().ok()?;
    let year: i64 = year.parse().ok()?;
    let clock: Vec<i64> = time
        .split(':')
        .map(|part| part.parse().ok())
        .collect::<Option<_>>()?;
    let [hours, minutes, seconds] = clock.as_slice() else {
        return None;
    };
    if !(1..=31).contains(&day) || *hours > 23 || *minutes > 59 || *seconds > 60 {
        return None;
    }
    // Days from the civil date (Howard Hinnant's algorithm).
    let (y, m) = if month <= 2 {
        (year - 1, month + 9)
    } else {
        (year, month - 3)
    };
    let era = y.div_euclid(400);
    let year_of_era = y - era * 400;
    let day_of_year = (153 * m + 2) / 5 + day - 1;
    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
    let days = era * 146_097 + day_of_era - 719_468;
    let seconds = days * 86_400 + hours * 3600 + minutes * 60 + seconds;
    let seconds = u64::try_from(seconds).ok()?;
    std::time::UNIX_EPOCH.checked_add(Duration::from_secs(seconds))
}

/// Adds the response's status, request ID, `Retry-After` and headers to `error`.
pub(crate) fn with_response(mut error: Error, status: u16, headers: &HeaderMap) -> Error {
    error = error.with_http_status(status).with_headers(headers.clone());
    if let Some(id) = headers.get("x-request-id").and_then(|v| v.to_str().ok()) {
        error = error.with_request_id(id);
    }
    if let Some(delay) = retry_after(headers) {
        error = error.with_retry_after(delay);
    }
    error
}

/// The [`Error`] for an unsuccessful API response: its `code`, `message`, `details` and request
/// ID (the `X-Request-Id` header, or the body's `requestId` without one), or `sdk/http-error`
/// when the body is not a CalmLens error.
pub(crate) fn api_error(status: u16, headers: &HeaderMap, body: &[u8]) -> Error {
    let parsed = serde_json::from_slice::<Value>(body);
    let api_code = match &parsed {
        Ok(Value::Object(object)) => object.get("code").and_then(Value::as_str),
        _ => None,
    };
    let error = match (api_code, &parsed) {
        (Some(code), Ok(Value::Object(object))) => {
            let details: Map<String, Value> = object
                .get("details")
                .and_then(Value::as_object)
                .cloned()
                .unwrap_or_default();
            let error = Error::new(
                code,
                object
                    .get("message")
                    .and_then(Value::as_str)
                    .unwrap_or(code)
                    .to_owned(),
            )
            .with_details(details);
            match object.get("requestId").and_then(Value::as_str) {
                Some(id) => error.with_request_id(id),
                None => error,
            }
        }
        _ => {
            let error = Error::new(ErrorCode::HttpError, format!("HTTP {status}"));
            match parsed {
                Err(cause) if !body.is_empty() => error.with_source(cause),
                _ => error,
            }
        }
    };
    with_response(error.with_raw_body(body), status, headers)
}

/// Decodes a successful JSON response.
pub(crate) fn decode<T: serde::de::DeserializeOwned>(
    status: u16,
    headers: &HeaderMap,
    body: &[u8],
) -> Result<T> {
    serde_json::from_slice(body).map_err(|cause| {
        with_response(
            Error::new(
                ErrorCode::InvalidResponse,
                format!("Invalid JSON response (HTTP {status}): {cause}"),
            )
            .with_source(cause),
            status,
            headers,
        )
    })
}

/// The [`LastResponse`](crate::models::LastResponse) of a response.
pub(crate) fn last_response(
    status: u16,
    headers: &HeaderMap,
    idempotency_key: Option<String>,
) -> crate::models::LastResponse {
    crate::models::LastResponse {
        idempotency_key,
        status: http::StatusCode::from_u16(status).unwrap_or(http::StatusCode::OK),
        request_id: headers
            .get("x-request-id")
            .and_then(|value| value.to_str().ok())
            .map(str::to_owned),
        headers: headers.clone(),
    }
}

pub(crate) fn transport_error(error: reqwest::Error) -> Error {
    let code = if is_timeout(&error) {
        ErrorCode::Timeout
    } else {
        ErrorCode::TransportError
    };
    Error::new(code, error.to_string()).with_source(error)
}

fn is_timeout(error: &reqwest::Error) -> bool {
    if error.is_timeout() {
        return true;
    }
    let mut source = std::error::Error::source(error);
    while let Some(cause) = source {
        if cause
            .downcast_ref::<std::io::Error>()
            .is_some_and(|io| io.kind() == std::io::ErrorKind::TimedOut)
        {
            return true;
        }
        source = cause.source();
    }
    false
}

/// Maps a failed streaming read to `sdk/timeout` or `sdk/transport-error`.
pub(crate) fn stream_error(error: Box<dyn std::error::Error + Send + Sync>) -> Error {
    match error.downcast::<reqwest::Error>() {
        Ok(error) => transport_error(*error),
        Err(error) => {
            let timed_out = error
                .downcast_ref::<std::io::Error>()
                .is_some_and(|io| io.kind() == std::io::ErrorKind::TimedOut);
            Error::new(
                if timed_out {
                    ErrorCode::Timeout
                } else {
                    ErrorCode::TransportError
                },
                error.to_string(),
            )
            .with_source(error)
        }
    }
}

/// The request body for an upload payload, and its size when it is known before sending.
pub(crate) fn upload_body(
    payload: Payload,
    multipart: bool,
    declared_size: Option<u64>,
) -> Result<(RequestBody, Option<u64>)> {
    use base64::{engine::general_purpose::STANDARD, Engine};
    let (body, size) = match payload {
        Payload::Text(text) => {
            let size = text.len() as u64;
            (RequestBody::Bytes(Bytes::from(text)), size)
        }
        Payload::Bytes(bytes) => {
            let size = bytes.len() as u64;
            (RequestBody::Bytes(bytes), size)
        }
        Payload::Base64(encoded) => {
            let mut encoded: String = encoded
                .rsplit(";base64,")
                .next()
                .unwrap_or("")
                .chars()
                .filter(|c| !c.is_whitespace())
                .collect();
            if multipart && !encoded.len().is_multiple_of(4) {
                return Err(crate::error::invalid_payload(
                    "Split bytes before base64-encoding each part",
                ));
            }
            encoded.push_str(&"=".repeat((4 - encoded.len() % 4) % 4));
            let bytes = STANDARD
                .decode(encoded)
                .map_err(|_| crate::error::invalid_payload("Invalid base64"))?;
            let size = bytes.len() as u64;
            (RequestBody::Bytes(bytes.into()), size)
        }
        Payload::Reader { reader, size } => (
            RequestBody::Stream(Some(reader_stream(reader)), Some(size)),
            size,
        ),
        Payload::File { path, size } => {
            let file = std::fs::File::open(&path).map_err(|cause| {
                crate::error::invalid_payload(format!("Could not open {}: {cause}", path.display()))
                    .with_source(cause)
            })?;
            (
                RequestBody::Stream(Some(reader_stream(Box::new(file))), Some(size)),
                size,
            )
        }
        Payload::Stream { stream, size } => (RequestBody::Stream(Some(stream), Some(size)), size),
        Payload::UnsizedStream(stream) => {
            return Ok((
                RequestBody::Stream(Some(stream), declared_size),
                declared_size,
            ))
        }
    };
    if declared_size.is_some_and(|declared| declared != size) {
        return Err(crate::error::invalid_payload(
            "sizeInBytes must match the payload byte length",
        ));
    }
    Ok((body, Some(size)))
}

/// Reads `length` bytes of the file at `path` from `offset`, on Tokio's blocking thread pool.
pub(crate) async fn read_file_range(
    path: std::path::PathBuf,
    offset: u64,
    length: usize,
) -> Result<Bytes> {
    tokio::task::spawn_blocking(move || {
        use std::io::{Read, Seek, SeekFrom};
        let mut file = std::fs::File::open(&path)?;
        file.seek(SeekFrom::Start(offset))?;
        let mut buffer = vec![0; length];
        file.read_exact(&mut buffer)?;
        Ok::<_, std::io::Error>(Bytes::from(buffer))
    })
    .await
    .map_err(std::io::Error::other)
    .and_then(|read| read)
    .map_err(|cause| {
        crate::error::invalid_payload(format!("Could not read the file being uploaded: {cause}"))
            .with_source(cause)
    })
}

/// Reads a blocking reader in 64 KiB chunks on Tokio's blocking thread pool.
fn reader_stream(reader: Box<dyn std::io::Read + Send>) -> crate::ByteStream {
    let stream = futures_util::stream::try_unfold(Some(reader), |state| async move {
        let Some(mut reader) = state else {
            return Ok(None);
        };
        let (reader, chunk) = tokio::task::spawn_blocking(move || {
            let mut buffer = vec![0; 64 * 1024];
            let read = reader.read(&mut buffer)?;
            buffer.truncate(read);
            Ok::<_, std::io::Error>((reader, buffer))
        })
        .await
        .map_err(std::io::Error::other)??;
        if chunk.is_empty() {
            Ok::<_, std::io::Error>(None)
        } else {
            Ok(Some((Bytes::from(chunk), Some(reader))))
        }
    });
    Box::pin(stream.map_err(|error| Box::new(error) as _))
}

/// Collects a request stream, for mocks.
#[cfg(feature = "testing")]
pub(crate) async fn collect(stream: crate::ByteStream) -> Result<Vec<u8>> {
    use futures_util::StreamExt;
    let mut body = Vec::new();
    let mut stream = stream;
    while let Some(chunk) = stream.next().await {
        body.extend_from_slice(&chunk.map_err(stream_error)?);
    }
    Ok(body)
}