videosdk-server-sdk 0.1.0

Rust server SDK for the VideoSDK v2 REST APIs
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! The HTTP client: authentication, retries, and response decoding.

use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use reqwest::header::{HeaderMap, HeaderName, HeaderValue, ACCEPT, AUTHORIZATION, USER_AGENT};
use reqwest::{Method, StatusCode};
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};

use crate::builder::{ClientBuilder, Config, TokenOptions};
use crate::error::{normalize_api_error, Error, Result};
use crate::token::{
    decode_token, generate_token, verify_token, AccessTokenBuilder, GenerateTokenParams,
    TokenClaims,
};

/// The production API endpoint.
pub const DEFAULT_BASE_URL: &str = "https://api.videosdk.live";

/// This SDK's version, reported in the `User-Agent` header of every request.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

const USER_AGENT_VALUE: &str = concat!("videosdk-rs/", env!("CARGO_PKG_VERSION"));

/// Regenerate a cached token once it is within this window of expiring.
const TOKEN_REFRESH_BUFFER: i64 = 60;
const MAX_BACKOFF: Duration = Duration::from_secs(8);

pub(crate) type BackoffFn = Arc<dyn Fn(u32) -> Duration + Send + Sync>;

/// What the caller expects the response body to be.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Expect {
    /// A JSON body. The default.
    #[default]
    Json,
    /// A raw text body, e.g. a CSV export.
    Text,
    /// No body; anything sent is discarded.
    None,
}

/// A request body.
pub(crate) enum Body {
    Json(Value),
    /// A pre-encoded body sent verbatim, e.g. an SDP offer. Reachable through
    /// [`RawRequest::raw_body`].
    Raw(Vec<u8>),
}

/// One request the SDK issues internally.
#[derive(Default)]
pub(crate) struct CallOptions {
    pub(crate) query: Vec<(String, String)>,
    pub(crate) body: Option<Body>,
    pub(crate) headers: Vec<(String, String)>,
    pub(crate) expect: Expect,
}

impl CallOptions {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    pub(crate) fn json(body: impl serde::Serialize) -> Result<Self> {
        let body = serde_json::to_value(body).map_err(|e| Error::Encode { source: e })?;
        Ok(Self {
            body: Some(Body::Json(body)),
            ..Default::default()
        })
    }

    pub(crate) fn query(mut self, query: Vec<(String, String)>) -> Self {
        self.query = query;
        self
    }

    pub(crate) fn expect(mut self, expect: Expect) -> Self {
        self.expect = expect;
        self
    }
}

#[derive(Default)]
pub(crate) struct TokenCache {
    pub(crate) token: Option<String>,
    pub(crate) expires_at: Option<i64>,
}

pub(crate) struct ClientInner {
    pub(crate) config: Config,
    pub(crate) http: reqwest::Client,
    pub(crate) base_url: String,
    pub(crate) can_refresh: bool,
    pub(crate) token: Mutex<TokenCache>,
    pub(crate) backoff: BackoffFn,
}

/// Per-call overrides layered on top of the shared [`ClientInner`].
#[derive(Clone, Default)]
pub(crate) struct Overrides {
    pub(crate) max_retries: Option<u32>,
    pub(crate) timeout: Option<Duration>,
}

/// The VideoSDK server SDK client.
///
/// Cloning is cheap: clones share one connection pool and one token cache. The
/// client mints and attaches the API token for its own requests automatically,
/// so you never hand-roll a JWT or set the `Authorization` header.
///
/// ```no_run
/// # #[tokio::main]
/// # async fn main() -> Result<(), videosdk::Error> {
/// // Reads VIDEOSDK_API_KEY and VIDEOSDK_SECRET from the environment.
/// let client = videosdk::Client::new()?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Client {
    inner: Arc<ClientInner>,
    overrides: Overrides,
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("base_url", &self.inner.base_url)
            .finish_non_exhaustive()
    }
}

impl Client {
    /// Constructs a client from the `VIDEOSDK_API_KEY`, `VIDEOSDK_SECRET` and
    /// `VIDEOSDK_API_ENDPOINT` environment variables.
    pub fn new() -> Result<Self> {
        ClientBuilder::new().build()
    }

    /// Starts building a client.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    pub(crate) fn from_parts(inner: Arc<ClientInner>, overrides: Overrides) -> Self {
        Self { inner, overrides }
    }

    /// The resolved API endpoint.
    pub fn base_url(&self) -> &str {
        &self.inner.base_url
    }

    /// Returns a clone of this client that retries a different number of times.
    ///
    /// The clone shares the same connection pool and token cache.
    pub fn with_max_retries(&self, max_retries: u32) -> Self {
        let mut client = self.clone();
        client.overrides.max_retries = Some(max_retries);
        client
    }

    /// Returns a clone of this client with a different per-request timeout.
    /// [`Duration::ZERO`] disables the timeout.
    pub fn with_request_timeout(&self, timeout: Duration) -> Self {
        let mut client = self.clone();
        client.overrides.timeout = Some(timeout);
        client
    }

    fn max_retries(&self) -> u32 {
        self.overrides
            .max_retries
            .unwrap_or(self.inner.config.max_retries)
    }

    fn timeout(&self) -> Duration {
        self.overrides.timeout.unwrap_or(self.inner.config.timeout)
    }

    /* --------------------------------- tokens --------------------------------- */

    fn credentials(&self, what: &str) -> Result<(&str, &str)> {
        match (
            self.inner.config.api_key.as_deref(),
            self.inner.config.secret.as_deref(),
        ) {
            (Some(api_key), Some(secret)) => Ok((api_key, secret)),
            _ => Err(Error::config(format!(
                "{what} requires the client to be constructed with an API key and secret"
            ))),
        }
    }

    /// Mints a fresh management token from the client's credentials, applying any
    /// configured [`TokenOptions`].
    pub fn generate_token(&self) -> Result<String> {
        let (api_key, secret) = self.credentials("generate_token")?;
        let TokenOptions {
            permissions,
            roles,
            version,
            expires_in,
        } = &self.inner.config.token_options;
        generate_token(&GenerateTokenParams {
            api_key: api_key.to_string(),
            secret_key: secret.to_string(),
            permissions: permissions.clone(),
            roles: roles.clone(),
            version: *version,
            expires_in: *expires_in,
            claims: Map::new(),
        })
    }

    /// Starts building an access token.
    ///
    /// Defaults to a participant token (`roles: ["rtc"]`); call
    /// [`AccessTokenBuilder::for_api`] for a management token.
    pub fn access_token(&self) -> Result<AccessTokenBuilder> {
        let (api_key, secret) = self.credentials("access_token")?;
        let mut builder = AccessTokenBuilder::new(api_key, secret);
        if let Some(ttl) = self.inner.config.token_options.expires_in {
            builder = builder.expires_in(ttl);
        }
        Ok(builder)
    }

    /// Verifies a token against the client's secret and returns its claims.
    pub fn verify_token(&self, token: &str) -> Result<TokenClaims> {
        let secret = self.inner.config.secret.as_deref().ok_or_else(|| {
            Error::config("verify_token requires the client to be constructed with a secret")
        })?;
        verify_token(token, secret)
    }

    /// Mints a short-lived API-scoped token (`roles: ["crawler"]`), used to
    /// authorize WHIP/WHEP publish and play. A zero TTL defaults to one hour.
    pub(crate) fn mint_api_token(&self, ttl: Duration) -> Result<String> {
        let ttl = if ttl.is_zero() {
            Duration::from_secs(3600)
        } else {
            ttl
        };
        self.access_token()?.for_api().expires_in(ttl).to_jwt()
    }

    fn resolve_token(&self) -> Result<String> {
        let mut cache = self
            .inner
            .token
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());

        if let Some(token) = &cache.token {
            let fresh = match cache.expires_at {
                None => true,
                Some(exp) => exp - TOKEN_REFRESH_BUFFER > unix_now(),
            };
            if fresh {
                return Ok(token.clone());
            }
        }

        if !self.inner.can_refresh {
            // A static token that may have expired: let the API decide.
            return cache.token.clone().ok_or_else(|| {
                Error::config("no token available and the client cannot generate one")
            });
        }

        let token = self.generate_token()?;
        cache.expires_at = decode_token(&token).ok().and_then(|c| c.expires_at);
        cache.token = Some(token.clone());
        Ok(token)
    }

    /* -------------------------------- execution -------------------------------- */

    /// Issues a request with retries, returning the raw response body. Empty for
    /// a 204, or when [`Expect::None`] was requested.
    pub(crate) async fn execute(
        &self,
        method: Method,
        path: &str,
        options: &CallOptions,
    ) -> Result<Vec<u8>> {
        let idempotent = is_idempotent(&method);
        let max_retries = self.max_retries();

        let mut attempt = 0u32;
        loop {
            match self.attempt(&method, path, options).await {
                Ok(body) => return Ok(body),
                Err(err) => {
                    if !should_retry(&err, idempotent) || attempt >= max_retries {
                        return Err(err);
                    }
                    // Honor the server's cooldown on a 429; otherwise back off.
                    let delay = err
                        .retry_after()
                        .filter(|_| err.status() == Some(429))
                        .unwrap_or_else(|| (self.inner.backoff)(attempt));
                    tokio::time::sleep(delay).await;
                    attempt += 1;
                }
            }
        }
    }

    /// Assembles the request headers, later layers replacing earlier ones:
    /// the SDK's defaults, then the client's, then this call's.
    fn build_headers(&self, token: &str, options: &CallOptions) -> Result<HeaderMap> {
        let mut headers = HeaderMap::new();

        // A raw JWT — no "Bearer " prefix.
        let mut authorization = HeaderValue::from_str(token)
            .map_err(|_| Error::config("the token contains characters invalid in a header"))?;
        authorization.set_sensitive(true);
        headers.insert(AUTHORIZATION, authorization);

        let accept = match options.expect {
            // A text response is whatever the endpoint produces, e.g. CSV.
            Expect::Text => "*/*",
            Expect::Json | Expect::None => "application/json",
        };
        headers.insert(ACCEPT, HeaderValue::from_static(accept));
        headers.insert(USER_AGENT, HeaderValue::from_static(USER_AGENT_VALUE));

        for (name, value) in &self.inner.config.headers {
            headers.insert(name.clone(), value.clone());
        }
        for (name, value) in &options.headers {
            let name = HeaderName::try_from(name.as_str())
                .map_err(|_| Error::validation(format!("invalid header name {name:?}")))?;
            let value = HeaderValue::try_from(value.as_str())
                .map_err(|_| Error::validation(format!("invalid value for header {name:?}")))?;
            headers.insert(name, value);
        }

        Ok(headers)
    }

    async fn attempt(&self, method: &Method, path: &str, options: &CallOptions) -> Result<Vec<u8>> {
        let token = self.resolve_token()?;
        let url = format!("{}{}", self.inner.base_url, ensure_leading_slash(path));

        let mut request = self.inner.http.request(method.clone(), &url);
        if !options.query.is_empty() {
            request = request.query(&options.query);
        }

        // `RequestBuilder::header` *appends*, so a caller-supplied `Authorization`
        // would be sent alongside ours rather than replacing it. Build the map
        // ourselves — `HeaderMap::insert` replaces — and hand it over in one go.
        request = request.headers(self.build_headers(&token, options)?);

        match &options.body {
            // `json` sets Content-Type only when it is not already present, so a
            // caller-supplied Content-Type still wins.
            Some(Body::Json(value)) => request = request.json(value),
            Some(Body::Raw(bytes)) => request = request.body(bytes.clone()),
            None => {}
        }

        let timeout = self.timeout();
        if !timeout.is_zero() {
            request = request.timeout(timeout);
        }

        let response = request
            .send()
            .await
            .map_err(|e| transport_error(e, method, path, timeout))?;

        let status = response.status();
        let request_id = read_request_id(response.headers());
        let retry_after = (status == StatusCode::TOO_MANY_REQUESTS)
            .then(|| parse_retry_after(response.headers()))
            .flatten();

        let body = response
            .bytes()
            .await
            .map_err(|e| transport_error(e, method, path, timeout))?;

        if !status.is_success() {
            return Err(Error::api(normalize_api_error(
                status.as_u16(),
                parse_maybe_json(&body),
                method.as_str(),
                path,
                request_id,
                retry_after,
            )));
        }

        if options.expect == Expect::None || status == StatusCode::NO_CONTENT {
            return Ok(Vec::new());
        }
        Ok(body.to_vec())
    }

    /// Uploads raw bytes to an absolute URL — typically an S3 or GCS presigned
    /// URL — with `PUT` and no `Authorization` header, since the presigned URL
    /// carries its own signature. Retries idempotently.
    pub(crate) async fn put_binary(
        &self,
        url: &str,
        body: &[u8],
        content_type: &str,
    ) -> Result<()> {
        let mut attempt = 0u32;
        loop {
            match self.attempt_put(url, body, content_type).await {
                Ok(()) => return Ok(()),
                Err(err) => {
                    if !should_retry(&err, true) || attempt >= self.max_retries() {
                        return Err(err);
                    }
                    tokio::time::sleep((self.inner.backoff)(attempt)).await;
                    attempt += 1;
                }
            }
        }
    }

    async fn attempt_put(&self, url: &str, body: &[u8], content_type: &str) -> Result<()> {
        // Keep the presigned signature out of error messages and logs.
        let path = safe_url_path(url);
        let timeout = self.timeout();

        let mut request = self
            .inner
            .http
            .put(url)
            .header(reqwest::header::CONTENT_TYPE, content_type)
            .body(body.to_vec());
        if !timeout.is_zero() {
            request = request.timeout(timeout);
        }

        let response = request
            .send()
            .await
            .map_err(|e| transport_error(e, &Method::PUT, path, timeout))?;

        let status = response.status();
        if status.is_success() {
            return Ok(());
        }

        let body = response.bytes().await.unwrap_or_default();
        let mut api_error = normalize_api_error(
            status.as_u16(),
            parse_maybe_json(&body),
            Method::PUT.as_str(),
            path,
            None,
            None,
        );
        api_error.message = format!("uploading the file to storage failed (HTTP {status})");
        api_error.code = Some("upload_failed".to_string());
        Err(Error::api(api_error))
    }

    fn decode<T: DeserializeOwned>(bytes: &[u8], method: &Method, path: &str) -> Result<T> {
        let context = format!("{method} {path}");
        if bytes.iter().all(u8::is_ascii_whitespace) {
            // Mirrors the Go SDK's zero-value return for an empty success body.
            // Only types with a `null` representation (Option, unit) can absorb it.
            return serde_json::from_str("null").map_err(|e| Error::decode(context, e));
        }
        serde_json::from_slice(bytes).map_err(|e| Error::decode(context, e))
    }
}

/* ------------------------- typed executors for resources ------------------------ */

/// One helper per response shape the API uses. There is no single generic
/// envelope: endpoints return a flat object, a `{"data": T}` envelope, a
/// envelope under a name of their own, a bare confirmation string, raw text, or
/// nothing at all.
impl Client {
    /// Issues a request and decodes a flat JSON response body into `T`.
    pub(crate) async fn json<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        options: CallOptions,
    ) -> Result<T> {
        let bytes = self.execute(method.clone(), path, &options).await?;
        Self::decode(&bytes, &method, path)
    }

    /// Issues a request and returns the response as a [`Value`], falling back to
    /// a JSON string for a non-JSON body.
    ///
    /// Egress `start` endpoints answer with a bare confirmation string on some
    /// paths and an id-bearing object on others, so neither can be assumed.
    pub(crate) async fn maybe_json(
        &self,
        method: Method,
        path: &str,
        options: CallOptions,
    ) -> Result<Value> {
        let bytes = self.execute(method, path, &options).await?;
        Ok(parse_maybe_json(&bytes).unwrap_or(Value::Null))
    }

    /// Issues a request and decodes the `data` field of a `{"data": T}` envelope.
    pub(crate) async fn data<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        options: CallOptions,
    ) -> Result<T> {
        self.wrapped(method, path, "data", options).await
    }

    /// Issues a request and decodes a single-key envelope, e.g. `{"alertRule": T}`.
    ///
    /// A missing key decodes as `null`, matching the Go SDK's zero value.
    pub(crate) async fn wrapped<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        key: &str,
        options: CallOptions,
    ) -> Result<T> {
        let bytes = self.execute(method.clone(), path, &options).await?;
        let context = format!("{method} {path}");
        if bytes.iter().all(u8::is_ascii_whitespace) {
            return serde_json::from_str("null").map_err(|e| Error::decode(context, e));
        }
        let mut envelope: Map<String, Value> =
            serde_json::from_slice(&bytes).map_err(|e| Error::decode(&context, e))?;
        let inner = envelope.remove(key).unwrap_or(Value::Null);
        serde_json::from_value(inner).map_err(|e| Error::decode(context, e))
    }

    /// Issues a request and returns a string confirmation. Mirrors the server's
    /// message endpoints: a JSON-string body is unquoted, anything else is
    /// returned as raw text.
    pub(crate) async fn message(
        &self,
        method: Method,
        path: &str,
        options: CallOptions,
    ) -> Result<String> {
        let bytes = self.execute(method, path, &options).await?;
        let text = String::from_utf8_lossy(&bytes);
        let trimmed = text.trim();
        if trimmed.is_empty() {
            return Ok(String::new());
        }
        if trimmed.starts_with('"') {
            if let Ok(unquoted) = serde_json::from_str::<String>(trimmed) {
                return Ok(unquoted);
            }
        }
        Ok(trimmed.to_string())
    }

    /// Issues a request and returns the raw response body as text, e.g. a CSV export.
    pub(crate) async fn text(
        &self,
        method: Method,
        path: &str,
        options: CallOptions,
    ) -> Result<String> {
        let bytes = self
            .execute(method, path, &options.expect(Expect::Text))
            .await?;
        Ok(String::from_utf8_lossy(&bytes).into_owned())
    }

    /// Issues a request and discards the response body.
    pub(crate) async fn none(
        &self,
        method: Method,
        path: &str,
        options: CallOptions,
    ) -> Result<()> {
        self.execute(method, path, &options.expect(Expect::None))
            .await?;
        Ok(())
    }
}

/* --------------------------------- escape hatch --------------------------------- */

impl Client {
    /// Calls any endpoint with an arbitrary HTTP method, applying auth and
    /// retries, and returns the undecoded JSON response.
    ///
    /// For the common verbs, [`Client::api`] reads better.
    pub async fn request(&self, method: Method, path: &str, request: RawRequest) -> Result<Value> {
        let expect = request.expect;
        // A raw body wins over a JSON one, as it is the more specific request.
        let body = match (request.raw_body, request.body) {
            (Some(bytes), _) => Some(Body::Raw(bytes)),
            (None, Some(value)) => Some(Body::Json(value)),
            (None, None) => None,
        };
        let options = CallOptions {
            query: request.query,
            body,
            headers: request.headers,
            expect,
        };
        let bytes = self.execute(method.clone(), path, &options).await?;
        match expect {
            Expect::None => Ok(Value::Null),
            // A text response is not JSON, so hand it back as a JSON string
            // rather than failing to parse it.
            Expect::Text => Ok(Value::String(String::from_utf8_lossy(&bytes).into_owned())),
            Expect::Json if bytes.iter().all(u8::is_ascii_whitespace) => Ok(Value::Null),
            Expect::Json => Self::decode(&bytes, &method, path),
        }
    }

    /// The raw HTTP escape hatch. Each method applies auth and retries, and
    /// returns the undecoded JSON response.
    pub fn api(&self) -> Api<'_> {
        Api { client: self }
    }
}

/// Configures a raw [`Api`] or [`Client::request`] call.
#[derive(Debug, Default)]
pub struct RawRequest {
    /// Query-string parameters.
    pub query: Vec<(String, String)>,
    /// A JSON request body. Ignored when [`raw_body`](RawRequest::raw_body) is set.
    pub body: Option<Value>,
    /// A pre-encoded request body, sent verbatim.
    ///
    /// Set `Content-Type` yourself via [`header`](RawRequest::header); unlike a
    /// JSON body, none is inferred.
    pub raw_body: Option<Vec<u8>>,
    /// Extra headers for this request.
    pub headers: Vec<(String, String)>,
    /// What to expect back. Defaults to [`Expect::Json`].
    pub expect: Expect,
}

impl RawRequest {
    /// A request with no query, body or headers.
    pub fn new() -> Self {
        Self::default()
    }

    /// Attaches a JSON body.
    pub fn body(mut self, body: Value) -> Self {
        self.body = Some(body);
        self
    }

    /// Attaches a pre-encoded body, sent verbatim.
    ///
    /// Pair it with a `Content-Type`, e.g. for an SDP offer:
    ///
    /// ```no_run
    /// # use videosdk::RawRequest;
    /// let request = RawRequest::new()
    ///     .raw_body(b"v=0\r\n".to_vec())
    ///     .header("content-type", "application/sdp");
    /// ```
    pub fn raw_body(mut self, body: impl Into<Vec<u8>>) -> Self {
        self.raw_body = Some(body.into());
        self
    }

    /// Attaches a header, replacing any the SDK would otherwise set.
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// Attaches a query parameter.
    pub fn query(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.query.push((name.into(), value.into()));
        self
    }

    /// Sets what to expect back.
    pub fn expect(mut self, expect: Expect) -> Self {
        self.expect = expect;
        self
    }
}

/// The raw HTTP escape hatch, reachable via [`Client::api`].
#[derive(Debug, Clone, Copy)]
pub struct Api<'a> {
    client: &'a Client,
}

macro_rules! api_method {
    ($name:ident, $method:expr, $doc:literal) => {
        #[doc = $doc]
        pub async fn $name(&self, path: &str, request: RawRequest) -> Result<Value> {
            self.client.request($method, path, request).await
        }
    };
}

impl Api<'_> {
    api_method!(get, Method::GET, "Issues a raw `GET`.");
    api_method!(post, Method::POST, "Issues a raw `POST`.");
    api_method!(put, Method::PUT, "Issues a raw `PUT`.");
    api_method!(patch, Method::PATCH, "Issues a raw `PATCH`.");
    api_method!(delete, Method::DELETE, "Issues a raw `DELETE`.");
}

/* ---------------------------------- helpers ---------------------------------- */

fn unix_now() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

fn ensure_leading_slash(path: &str) -> String {
    if path.starts_with('/') {
        path.to_string()
    } else {
        format!("/{path}")
    }
}

/// Strips the query string, which carries a presigned URL's signature.
fn safe_url_path(url: &str) -> &str {
    url.split('?').next().unwrap_or(url)
}

fn transport_error(
    source: reqwest::Error,
    method: &Method,
    path: &str,
    timeout: Duration,
) -> Error {
    if source.is_timeout() {
        Error::Timeout {
            method: method.to_string(),
            path: path.to_string(),
            elapsed: timeout,
        }
    } else {
        Error::Network {
            method: method.to_string(),
            path: path.to_string(),
            source,
        }
    }
}

/// Parses a body as JSON, falling back to the raw text for non-JSON bodies so
/// the error normalizer can still read a plain-text message.
fn parse_maybe_json(body: &[u8]) -> Option<Value> {
    if body.iter().all(u8::is_ascii_whitespace) {
        return None;
    }
    match serde_json::from_slice(body) {
        Ok(value) => Some(value),
        Err(_) => Some(Value::String(String::from_utf8_lossy(body).into_owned())),
    }
}

fn read_request_id(headers: &HeaderMap) -> Option<String> {
    [
        "x-request-id",
        "request-id",
        "x-amzn-requestid",
        "x-amz-request-id",
    ]
    .iter()
    .find_map(|name| headers.get(*name))
    .and_then(|value| value.to_str().ok())
    .filter(|value| !value.is_empty())
    .map(str::to_string)
}

/// Parses a `Retry-After` header, which is either delta-seconds or an HTTP-date.
fn parse_retry_after(headers: &HeaderMap) -> Option<Duration> {
    let value = headers.get("retry-after")?.to_str().ok()?.trim();
    if value.is_empty() {
        return None;
    }
    if let Ok(seconds) = value.parse::<i64>() {
        return (seconds > 0).then(|| Duration::from_secs(seconds as u64));
    }
    let deadline = httpdate::parse_http_date(value).ok()?;
    deadline.duration_since(SystemTime::now()).ok()
}

fn is_idempotent(method: &Method) -> bool {
    matches!(
        *method,
        Method::GET | Method::PUT | Method::DELETE | Method::HEAD | Method::OPTIONS
    )
}

/// Decides whether a failed attempt is worth retrying.
///
/// A 429 is always safe — the server rejected the request before processing it.
/// Otherwise only idempotent methods retry: a timeout or 5xx on a `POST` may
/// already have applied server-side, and retrying would duplicate the effect.
fn should_retry(error: &Error, idempotent: bool) -> bool {
    if error.status() == Some(429) {
        return true;
    }
    if !idempotent {
        return false;
    }
    match error {
        Error::Api(api) => api.status >= 500,
        Error::Network { .. } | Error::Timeout { .. } => true,
        _ => false,
    }
}

/// Exponential backoff capped at 8 seconds, plus jitter.
pub(crate) fn default_backoff(attempt: u32) -> Duration {
    let base = Duration::from_secs(1)
        .saturating_mul(1u32.checked_shl(attempt).unwrap_or(u32::MAX))
        .min(MAX_BACKOFF);
    base + Duration::from_millis(jitter_ms())
}

/// Up to 249 ms of jitter, derived from the clock. Backoff jitter only needs to
/// decorrelate concurrent retries, so this avoids pulling in an RNG dependency.
fn jitter_ms() -> u64 {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.subsec_nanos() as u64)
        .unwrap_or(0);
    let mut x = nanos
        .wrapping_mul(6_364_136_223_846_793_005)
        .wrapping_add(1_442_695_040_888_963_407);
    x ^= x >> 33;
    x = x.wrapping_mul(0xff51_afd7_ed55_8ccd);
    x ^= x >> 33;
    x % 250
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ApiError;
    use crate::error::ErrorKind;

    fn api_error(status: u16) -> Error {
        Error::api(ApiError {
            message: String::new(),
            kind: ErrorKind::from_status(status),
            code: None,
            status,
            request_id: None,
            details: None,
            method: "GET".into(),
            path: "/x".into(),
            retry_after: None,
        })
    }

    #[test]
    fn idempotent_methods() {
        for method in [
            Method::GET,
            Method::PUT,
            Method::DELETE,
            Method::HEAD,
            Method::OPTIONS,
        ] {
            assert!(is_idempotent(&method), "{method} should be idempotent");
        }
        assert!(!is_idempotent(&Method::POST));
        assert!(!is_idempotent(&Method::PATCH));
    }

    #[test]
    fn rate_limits_retry_for_any_method() {
        assert!(should_retry(&api_error(429), true));
        assert!(should_retry(&api_error(429), false));
    }

    #[test]
    fn server_errors_retry_only_when_idempotent() {
        assert!(should_retry(&api_error(500), true));
        assert!(should_retry(&api_error(503), true));
        assert!(!should_retry(&api_error(500), false));
    }

    #[test]
    fn client_errors_never_retry() {
        for status in [400, 401, 403, 404, 409] {
            assert!(!should_retry(&api_error(status), true), "status {status}");
        }
    }

    #[test]
    fn timeouts_retry_only_when_idempotent() {
        let err = Error::Timeout {
            method: "GET".into(),
            path: "/x".into(),
            elapsed: Duration::from_secs(1),
        };
        assert!(should_retry(&err, true));
        assert!(!should_retry(&err, false));
    }

    #[test]
    fn config_and_decode_errors_never_retry() {
        assert!(!should_retry(&Error::config("x"), true));
        assert!(!should_retry(&Error::validation("x"), true));
    }

    #[test]
    fn backoff_grows_exponentially_and_caps() {
        let bounds = |attempt: u32| {
            let d = default_backoff(attempt);
            (d.as_millis() as u64) / 1000
        };
        assert_eq!(bounds(0), 1);
        assert_eq!(bounds(1), 2);
        assert_eq!(bounds(2), 4);
        assert_eq!(bounds(3), 8);
        // Capped, plus jitter under 250ms.
        assert!(default_backoff(10) < Duration::from_millis(8_250));
        assert!(default_backoff(64) < Duration::from_millis(8_250));
    }

    #[test]
    fn jitter_stays_in_range() {
        for _ in 0..100 {
            assert!(jitter_ms() < 250);
        }
    }

    #[test]
    fn parses_retry_after_seconds() {
        let mut headers = HeaderMap::new();
        headers.insert("retry-after", "3".parse().unwrap());
        assert_eq!(parse_retry_after(&headers), Some(Duration::from_secs(3)));
    }

    #[test]
    fn ignores_non_positive_or_missing_retry_after() {
        assert_eq!(parse_retry_after(&HeaderMap::new()), None);
        let mut headers = HeaderMap::new();
        headers.insert("retry-after", "0".parse().unwrap());
        assert_eq!(parse_retry_after(&headers), None);
        headers.insert("retry-after", "-5".parse().unwrap());
        assert_eq!(parse_retry_after(&headers), None);
        headers.insert("retry-after", "garbage".parse().unwrap());
        assert_eq!(parse_retry_after(&headers), None);
    }

    #[test]
    fn parses_retry_after_http_date() {
        let future = SystemTime::now() + Duration::from_secs(120);
        let mut headers = HeaderMap::new();
        headers.insert(
            "retry-after",
            httpdate::fmt_http_date(future).parse().unwrap(),
        );
        let parsed = parse_retry_after(&headers).expect("should parse an HTTP-date");
        assert!(parsed > Duration::from_secs(60) && parsed <= Duration::from_secs(120));

        // A date in the past yields no delay.
        let past = SystemTime::now() - Duration::from_secs(60);
        headers.insert(
            "retry-after",
            httpdate::fmt_http_date(past).parse().unwrap(),
        );
        assert_eq!(parse_retry_after(&headers), None);
    }

    #[test]
    fn reads_request_id_in_priority_order() {
        let mut headers = HeaderMap::new();
        assert_eq!(read_request_id(&headers), None);
        headers.insert("x-amz-request-id", "amz".parse().unwrap());
        assert_eq!(read_request_id(&headers).as_deref(), Some("amz"));
        headers.insert("x-request-id", "primary".parse().unwrap());
        assert_eq!(read_request_id(&headers).as_deref(), Some("primary"));
    }

    #[test]
    fn parse_maybe_json_falls_back_to_text() {
        assert_eq!(parse_maybe_json(b"   "), None);
        assert_eq!(
            parse_maybe_json(b"{\"a\":1}"),
            Some(serde_json::json!({"a": 1}))
        );
        assert_eq!(
            parse_maybe_json(b"<html>oops</html>"),
            Some(Value::String("<html>oops</html>".into()))
        );
    }

    #[test]
    fn safe_url_path_strips_the_signature() {
        assert_eq!(
            safe_url_path("https://s3/bucket/key?X-Amz-Signature=secret"),
            "https://s3/bucket/key"
        );
        assert_eq!(safe_url_path("https://s3/key"), "https://s3/key");
    }

    #[test]
    fn ensures_a_leading_slash() {
        assert_eq!(ensure_leading_slash("v2/rooms"), "/v2/rooms");
        assert_eq!(ensure_leading_slash("/v2/rooms"), "/v2/rooms");
    }
}